xurls 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #!/usr/bin/perl
  2. use warnings;
  3. $hostchars = '[a-z0-9-._+]';
  4. $pathchars = '[a-z0-9-._+#=?&:;%/!,~]';
  5. sub scan($$$)
  6. {
  7. my ($file, $lineno, $line) = @_;
  8. chomp $line;
  9. while($line =~ s!
  10. ([a-z]+://)?
  11. # http://
  12. $hostchars+\.[a-z]+
  13. # www.tim.google.com - the [a-z].com is the main anchor for the whole regex - incase http:// is omitted
  14. # note no trailing slash
  15. ($pathchars+/\?)*
  16. # check for the index.php? part
  17. ($pathchars+|\($pathchars+\))*
  18. # check for pathchars, or a set of nested parens
  19. !!xoi){ # allow space + comments, compile once, strcasecmp
  20. my($p,$m,$e) = ($`,$&,$');
  21. $e = '.' . $e if $m =~ s/\.$//;
  22. if($opt{fname} && $file){
  23. print "$col{red}$file$col{none}:";
  24. }
  25. if($opt{lineno}){
  26. print "$col{green}$lineno$col{none}: ";
  27. }elsif($opt{fname} && $file){
  28. print ' ';
  29. }
  30. if($opt{hl}){
  31. print "$p$col{brown}$m$col{none}$e\n";
  32. }else{
  33. print "$m\n";
  34. }
  35. }
  36. }
  37. sub usage(){
  38. $printme =<<"!";
  39. Usage: $0 -[Chn] [FILES...]
  40. -h: highlight
  41. -c: force colour on (for pipes)
  42. -C: colour off (only makes sense with -h)
  43. -n: show line number
  44. !
  45. print STDERR $printme;
  46. exit 1;
  47. }
  48. %opt = (
  49. colour => 1,
  50. lineno => 0,
  51. fname => 0,
  52. hl => 0
  53. );
  54. %col = (
  55. brown => "\e[0;31m", # hl
  56. red => "\e[0;35m", # fname
  57. green => "\e[0;32m", # lineno
  58. none => "\e[0;0m"
  59. );
  60. for $arg (@ARGV){
  61. if($arg eq '-h'){
  62. $opt{hl} = 1;
  63. }elsif($arg eq '-n'){
  64. $opt{lineno} = 1;
  65. }elsif($arg eq '-C'){
  66. $opt{colour} = 0;
  67. }elsif($arg eq '-c'){
  68. usage() if $opt{colour} == 0;
  69. $opt{colour} = 2; # force on
  70. }elsif($arg eq '--help'){
  71. usage();
  72. }else{
  73. push @files, $arg;
  74. }
  75. }
  76. usage() if $opt{hl} && !$opt{colour};
  77. $opt{fname} = 1 if $#files > 0 || $opt{lineno};
  78. if(!$opt{colour} || ($opt{colour} == 1 && !-t STDOUT)){
  79. $col{$_} = '' for keys %col;
  80. }
  81. $| = 1;
  82. if(@files){
  83. for my $f (@files){
  84. my $n = 1;
  85. open F, '<', $f or warn "$f: $!\n";
  86. scan($f, $n++, $_) for <F>;
  87. close F;
  88. }
  89. }else{
  90. scan(undef, $., $_) while <STDIN>;
  91. }