forked from eisop-plume-lib/plume-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search
executable file
·2090 lines (1892 loc) · 61.1 KB
/
search
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
: # Use -*- Perl -*- without knowing its path
eval 'exec perl -S $0 "$@"'
if 0;
# The above three lines used to be just: #!/usr/bin/perl -w
# The below is legal nroff (but looks like a string to Perl), so that
# This can be processed as a man page.
'di
.ig 00
';
##############################################################################
##
## search
##
## Jeffrey Friedl ([email protected]), Dec 1994.
## Copyright 19.... ah hell, just take it.
##
## BLURB:
## A combo of find and grep -- more or less do a 'grep' on a whole
## directory tree. Fast, with lots of options. Much more powerful than
## the simple "find ... | xargs grep ....". Has a full man page.
## Powerfully customizable. Emacs interface included.
##
## This file is big, but mostly comments and man page.
##
## See man page for usage info.
## Return value: 2=error, 1=nothing found, 0=something found.
##
$version = "960908.11";
## "960908.11"
## Added -depth=0, 'cause I needed it.
##
## "960506.10"
## Added -F/-R, and made it a bit more smart about $ and @ in arguments.
##
## "960426.9"
## Sigh -- fixed a perl4 backward-compatabilty problem.
## "960330.8"
## Made $&-clean!
## "960325.7"
## Added the "filter" directive to the startup file so I could have
## search automatically look inside compressed files.
##
## Implementation: slightly changed semantics with how EVALs are
## removed from the inlined program.
## "960227.6"
## From Lionel Cons a few bug fixes and cool emacs interface:
##
## ``Also, I integrated search in Emacs so that I can use "M-x search"
## and then "C-x `" to browse through the occurences (like grep).
## Here is the code that I use:
##
## (defun search (dir what) "Run search with all grep goodies."
## (interactive "DSearch under: \nsSearch for: ")
## (setq default-directory
## (if (string-match "/$" dir) dir (concat dir "/")))
## (compile-internal (concat "search -n " what)
## "No more search hits" "grep" nil grep-regexp-alist))
## "951019.5"
## Add color stuff (-bold, -red, etc...)
## Fix up nroff stuff to work with groff
## "950918.4 1/2";
## Changed all 'sysread' to 'read' because Linux perl's don't seem
## to like sysread()
## "941227.4"
## Added -n, -u
## "941222.3"
## Added -nice (due to Lionel Cons <[email protected]>)
## Removed any leading "./" from name.
## Added default flags for ~/.search, including TTY, -nice, -list, etc.
## Program name now has path removed when printed in diagnostics.
## Added simple tilde-expansion to -dir arg.
## Added -dskip, etc. Fixed -iregex bug.
## Changed -dir to be additive, adding -ddir.
## Now screen out devices, pipes, and sockets.
## More tidying and lots of expanding of the man page
## "941217.2";
## initial release.
$stripped=0;
&init;
$rc_file = join('/', $ENV{'HOME'}, ".search");
&check_args;
## Make sure we've got a regex.
## Don't need one if -find or -showrc was specified.
$!=2, die "expecting regex arguments.\n"
if $FIND_ONLY == 0 && $showrc == 0 && @ARGV == 0;
&prepare_to_search($rc_file);
&import_program if !defined &dodir; ## BIG key to speed.
## do search while there are directories to be done.
&dodir(shift(@todo)) while @todo;
&clear_message if $VERBOSE && $STDERR_IS_TTY;
exit($retval);
###############################################################################
sub init
{
## initialize variables that might be reset by command-line args
$DOREP=0; ## set true by -dorep (redo multi-hardlink files)
$DO_SORT=0; ## set by -sort (sort files in a dir before checking)
$FIND_ONLY=0; ## set by -find (don't search files)
$LIST_ONLY=0; ## set true by -l (list filenames only)
$NEWER=0; ## set by -newer, "-mtime -###"
$NICE=0; ## set by -nice (print human-readable output)
$NOLINKS=0; ## set true by -nolinks (don't follow symlinks)
$OLDER=0; ## set by -older, "-mtime ###"
$PREPEND_FILENAME=1; ## set false by -h (don't prefix lines with filename)
$REPORT_LINENUM=0; ## set true by -n (show line numbers)
$VERBOSE=0; ## set to a value by -v, -vv, etc. (verbose messages)
$WHY=0; ## set true by -why, -vvv+ (report why skipped)
$XDEV=0; ## set true by -xdev (stay on one filesystem)
$all=0; ## set true by -all (don't skip many kinds of files)
$iflag = ''; ## set to 'i' by -i (ignore case);
$norc=0; ## set by -norc (don't load rc file)
$showrc=0; ## set by -showrc (show what happens with rc file)
$underlineOK=0; ## set true by -u (watch for underline stuff)
$words=0; ## set true by -w (match whole-words only)
$MARK=''; ## set by -bold (-red, etc.). Does ANSI markup.
$literal=0; ## set by -F -- "regex" args taken as literal strings
$paragraph=0; ## set by -para, meaning to read input by paragraphs
$retval=1; ## will set to 0 if we find anything.
$DESCEND_SUBDIRECTORIES=1;## set to false by -depth=0
## various elements of stat() that we might access
$STAT_DEV = 1;
$STAT_INODE = 2;
$STAT_MTIME = 9;
$VV_PRINT_COUNT = 50; ## with -vv, print every VV_PRINT_COUNT files, or...
$VV_SIZE = 1024*1024; ## ...every VV_SIZE bytes searched
$vv_print = $vv_size = 0; ## running totals.
## set default options, in case the rc file wants them
$opt{'TTY'}= 1 if -t STDOUT;
## want to know this for debugging message stuff
$STDERR_IS_TTY = -t STDERR ? 1 : 0;
$STDERR_SCREWS_STDOUT = ($STDERR_IS_TTY && -t STDOUT) ? 1 : 0;
$0 =~ s,.*/,,; ## clean up $0 for any diagnostics we'll be printing.
}
##
## Check arguments.
##
sub check_args
{
while (@ARGV && $ARGV[0] =~ m/^-/)
{
$arg = shift(@ARGV);
if ($arg eq '-version' || ($VERBOSE && $arg eq '-help')) {
print qq/Jeffrey\'s file search, version "$version".\n/;
exit(0) unless $arg eq '-help';
}
if ($arg eq '-help') {
print <<INLINE_LITERAL_TEXT;
usage: $0 [options] [-e] [PerlRegex ....]
OPTIONS TELLING *WHERE* TO SEARCH:
-dir DIR start search at the named directory (default is current dir).
-xdev stay on starting file system.
-sort sort the files in each directory before processing.
-nolinks don\'t follow symbolic links.
-depth=0 don\'t descend into subdirectories
OPTIONS TELLING WHICH FILES TO EVEN CONSIDER:
-mtime # consider files modified > # days ago (-# for < # days old)
-newer FILE consider files modified more recently than FILE
-older FILE consider files modified less recently than FILE
-name GLOB consider files whose name matches pattern (same as -regex).
-regex GLOB consider files whose name matches pattern (same as -name).
-skip GLOB opposite of -name: identifies files to not consider.
-path GLOB like -name, but for files whose whole path is described.
-dregex/-dskip/-dpath versions for selecting or pruning directories.
-all don\'t skip any files marked to be skipped by the startup file.
-x<SPECIAL> (see manual, and/or try -showrc).
-why report why a file isn\'t checked (also implied by -vvvv).
OPTIONS TELLING WHAT TO DO WITH FILES THAT WILL BE CONSIDERED:
-f | -find just list files (PerlRegex ignored). Default is to grep them.
-ff | -ffind Does a faster -find (implies -find -all -dorep)
OPTIONS CONTROLLING HOW THE SEARCH IS DONE (AND WHAT IS PRINTED):
-F | -lit "regex" args taken as literal strings (like fgrep)
-R | -regex undoes -F -- regex ares really are perl regexes
-l | -list only list files with matches, not the lines themselves.
-nice | -nnice print more "human readable" output.
-bold | -red mark found items (various colors supported)
-n prefix each output line with its line number in the file.
-h don\'t prefix output lines with file name.
-u also look "inside" manpage-style underlined text
-i do case-insensitive searching.
-w match words only (as defined by perl\'s \\b).
OTHER OPTIONS:
-v, -vv, -vvv various levels of message verbosity.
-e end of options (in case a regex looks like an option).
-showrc show what the rc file sets, then exit.
-norc don\'t load the rc file.
-dorep check files with multiple hard links multiple times.
INLINE_LITERAL_TEXT
print "Use -v -help for more verbose help.\n" unless $VERBOSE;
print "This script file is also a man page.\n" unless $stripped;
print <<INLINE_LITERAL_TEXT if $VERBOSE;
If -f (or -find) given, PerlRegex is optional and ignored.
Otherwise, will search for files with lines matching any of the given regexes.
Combining things like -name and -mtime implies boolean AND.
However, duplicating things (such as -name '*.c' -name '*.txt') implies OR.
-mtime may be given floating point (i.e. 1.5 is a day and a half).
-iskip/-idskip/-ipath/... etc are case-insensitive versions.
If any letter in -newer/-older is upper case, "or equal" is
inserted into the test.
You can always find the latest version on the World Wide Web in
http://www.wg.omron.co.jp/~jfriedl/perl/
INLINE_LITERAL_TEXT
exit(0);
}
$DOREP=1, next if $arg eq '-dorep'; ## do repeats
$DO_SORT=1, next if $arg eq '-sort'; ## sort files
$NOLINKS=1, next if $arg eq '-nolinks'; ## no sym. links
$PREPEND_FILENAME=0, next if $arg eq '-h'; ## no filename prefix
$REPORT_LINENUM=1, next if $arg eq '-n'; ## show line numbers
$WHY=1, next if $arg eq '-why'; ## tell why skipped
$XDEV=1, next if $arg eq '-xdev'; ## don't leave F.S.
$all=1,$opt{'-all'}=1,next if $arg eq '-all'; ## don't skip *.Z, etc
$iflag='i', next if $arg eq '-i'; ## ignore case
$iflag='', next if $arg eq '-noi'; ## don't ignore case
$norc=1, next if $arg eq '-norc'; ## don't load rc file
$showrc=1, next if $arg eq '-showrc'; ## show rc file
$underlineOK=1, next if $arg eq '-u'; ## look throuh underln.
$words=1, next if $arg eq '-w'; ## match "words" only
$literal=1, next if $arg eq '-F'; ## args are literal
$literal=1, next if $arg eq '-lit'; ## args are literal
$literal=0, next if $arg eq '-R'; ## args are regexes
$literal=0, next if $arg eq '-regex'; ## args are regexes
$/="\n\n",$paragraph=1,next if $arg eq '-para'; ## search by paragraphs
&strip if $arg eq '-strip'; ## dump this program
last if $arg eq '-e';
$mark = '\e[7m', next if $arg eq '-bold'; ## embold found items]
$mark = '\e[30m', next if $arg eq '-black'; ## embold found items]
$mark = '\e[31m', next if $arg eq '-red'; ## embold found items]
$mark = '\e[32m', next if $arg eq '-green'; ## embold found items]
$mark = '\e[33m', next if $arg eq '-yellow'; ## embold found items]
$mark = '\e[34m', next if $arg eq '-blue'; ## embold found items]
$mark = '\e[36m', next if $arg eq '-cyan'; ## embold found items]
$mark = '\e[37m', next if $arg eq '-white'; ## embold found items]
$FIND_ONLY=1, next if $arg =~/^-f(ind)?$/;## do "find" only
$FIND_ONLY=1, $DOREP=1, $all=1,
next if $arg =~/^-ff(ind)?$/;## fast -find
$LIST_ONLY=1,$opt{'-list'}=1,
next if $arg =~/^-l(ist)?$/;## only list files
if ($arg =~ m/^-depth=(\d+)$/) {
die qq/$0: only -depth of 0 currently supported\n/ if $1 != 0;
$DESCEND_SUBDIRECTORIES=0;
next;
}
if ($arg =~ m/^-(v+)$/) { ## verbosity
$VERBOSE =length($1);
foreach $len (1..$VERBOSE) { $opt{'-'.('v' x $len)}=1 }
next;
}
if ($arg =~ m/^-(n+)ice$/) { ## "nice" output
$NICE =length($1);
foreach $len (1..$NICE) { $opt{'-'.('n' x $len).'ice'}=1 }
next;
}
if ($arg =~ m/^-(i?)(d?)skip$/) {
local($i) = $1 eq 'i';
local($d) = $2 eq 'd';
$! = 2, die qq/$0: expecting glob arg to -$arg\n/ unless @ARGV;
foreach (split(/\s+/, shift @ARGV)) {
if ($d) {
$idskip{$_}=1 if $i;
$dskip{$_}=1;
} else {
$iskip{$_}=1 if $i;
$skip{$_}=1;
}
}
next;
}
if ($arg =~ m/^-(i?)(d?)(regex|path|name)$/) {
local($i) = $1 eq 'i';
$! = 2, die qq/$0: expecting arg to -$arg\n/ unless @ARGV;
foreach (split(/\s+/, shift @ARGV)) {
$iname{join(',', $arg, $_)}=1 if $i;
$name{join(',', $arg, $_)}=1;
}
next;
}
if ($arg =~ m/^-d?dir$/) {
$opt{'-dir'}=1;
$! = 2, die qq/$0: expecting filename arg to -$arg\n/ unless @ARGV;
$start = shift(@ARGV);
$start =~ s#^~(/+|$)#$ENV{'HOME'}$1# if defined $ENV{'HOME'};
$! = 2, die qq/$0: can\'t find ${arg}\'s "$start"\n/ unless -e $start;
$! = 2, die qq/$0: ${arg}\'s "$start" not a directory.\n/ unless -d _;
undef(@todo), $opt{'-ddir'}=1 if $arg eq '-ddir';
push(@todo, $start);
next;
}
if ($arg =~ m/^-(new|old)er$/i) {
$! = 2, die "$0: expecting filename arg to -$arg\n" unless @ARGV;
local($file, $time) = shift(@ARGV);
$! = 2, die qq/$0: can\'t stat -${arg}\'s "$file"./
unless $time = (stat($file))[$STAT_MTIME];
local($upper) = $arg =~ tr/A-Z//;
if ($arg =~ m/new/i) {
$time++ unless $upper;
$NEWER = $time if $NEWER < $time;
} else {
$time-- unless $upper;
$OLDER = $time if $OLDER == 0 || $OLDER > $time;
}
next;
}
if ($arg =~ m/-mtime/) {
$! = 2, die "$0: expecting numerical arg to -$arg\n" unless @ARGV;
local($days) = shift(@ARGV);
$! = 2, die qq/$0: inappropriate arg ($days) to $arg\n/ if $days==0;
$days *= 3600 * 24;
if ($days < 0) {
local($time) = $^T + $days;
$NEWER = $time if $NEWER < $time;
} else {
local($time) = $^T - $days;
$OLDER = $time if $OLDER == 0 || $OLDER > $time;
}
next;
}
## special user options
if ($arg =~ m/^-x(.+)/) {
foreach (split(/[\s,]+/, $1)) { $user_opt{$_} = $opt{$_}= 1; }
next;
}
$! = 2, die "$0: unknown arg [$arg]\n";
}
$DOMARK = defined($mark) ? 1 : 0;
}
##
## Given a filename glob, return a regex.
## If the glob has no globbing chars (no * ? or [..]), then
## prepend an effective '*' to it.
##
sub glob_to_regex
{
local($glob) = @_;
local(@parts) = $glob =~ m/\\.|[*?]|\[]?[^]]*]|[^[\\*?]+/g;
local($trueglob)=0;
foreach (@parts) {
if ($_ eq '*' || $_ eq '?') {
$_ = ".$_";
$trueglob=1; ## * and ? are a real glob
} elsif (substr($_, 0, 1) eq '[') {
$trueglob=1; ## [..] is a real glob
} else {
s/^\\//; ## remove any leading backslash;
s/(\W)/\\$1/g; ## now quote anything dangerous;
}
}
unshift(@parts, '.*') unless $trueglob;
join('', '^', @parts, q/$/);
}
sub prepare_to_search
{
local($rc_file) = @_;
$HEADER_BYTES=0; ## Might be set nonzero in &read_rc;
$last_message_length = 0; ## For &message and &clear_message.
&read_rc($rc_file, $showrc) unless $norc;
exit(0) if $showrc;
$NEXT_DIR_ENTRY = $DO_SORT ? 'shift @files' : 'readdir(DIR)';
$WHY = 1 if $VERBOSE > 3; ## Arg -vvvv or above implies -why.
@todo = ('.') if @todo == 0; ## Where we'll start looking
## see if any user options were specified that weren't accounted for
foreach $opt (keys %user_opt) {
next if defined $seen_opt{$opt};
warn "warning: -x$opt never considered.\n";
}
die "$0: multiple time constraints exclude all possible files.\n"
if ($NEWER && $OLDER) && ($NEWER > $OLDER);
##
## Process any -skip/-iskip args that had been given
##
local(@skip_test);
foreach $glob (keys %skip) {
$i = defined($iskip{$glob}) ? 'i': '';
push(@skip_test, '$name =~ m/'. &glob_to_regex($glob). "/$i");
}
if (@skip_test) {
$SKIP_TEST = join('||',@skip_test);
$DO_SKIP_TEST = 1;
} else {
$DO_SKIP_TEST = $SKIP_TEST = 0;
}
##
## Process any -dskip/-idskip args that had been given
##
local(@dskip_test);
foreach $glob (keys %dskip) {
$i = defined($idskip{$glob}) ? 'i': '';
push(@dskip_test, '$name =~ m/'. &glob_to_regex($glob). "/$i");
}
if (@dskip_test) {
$DSKIP_TEST = join('||',@dskip_test);
$DO_DSKIP_TEST = 1;
} else {
$DO_DSKIP_TEST = $DSKIP_TEST = 0;
}
##
## Process any -name, -path, -regex, etc. args that had been given.
##
undef @name_test;
undef @dname_test;
foreach $key (keys %name) {
local($type, $pat) = split(/,/, $key, 2);
local($i) = defined($iname{$key}) ? 'i' : '';
if ($type =~ /regex/) {
$pat =~ s/!/\\!/g;
$test = "\$name =~ m!^$pat\$!$i";
} else {
local($var) = $type eq 'name' ? '$name' : '$file';
$test = "$var =~ m/". &glob_to_regex($pat). "/$i";
}
if ($type =~ m/^-i?d/) {
push(@dname_test, $test);
} else {
push(@name_test, $test);
}
}
if (@name_test) {
$GLOB_TESTS = join('||', @name_test);
$DO_GLOB_TESTS = 1;
} else {
$GLOB_TESTS = $DO_GLOB_TESTS = 0;
}
if (@dname_test) {
$DGLOB_TESTS = join('||', @dname_test);
$DO_DGLOB_TESTS = 1;
} else {
$DGLOB_TESTS = $DO_DGLOB_TESTS = 0;
}
##
## Process any 'magic' things from the startup file.
##
if (@magic_tests && $HEADER_BYTES) {
## the $magic' one is for when &dodir is not inlined
$tests = join('||',@magic_tests);
$MAGIC_TESTS = "{ package magic; \$val = ($tests) }";
$DO_MAGIC_TESTS = 1;
} else {
$MAGIC_TESTS = 1;
$DO_MAGIC_TESTS = 0;
}
##
## Prepare regular expressions.
##
{
local(@regex_tests);
local(@mark_commands);
if ($LIST_ONLY) {
$mflag = '';
## need to have $* set, but perl5 just won't shut up about it.
if ($] >= 5) {
$mflag = 'm';
} else {
eval ' $* = 1 ';
}
}
##
## Until I figure out a better way to deal with it,
## We have to worry about a regex like [^xyz] when doing $LIST_ONLY.
## Such a regex *will* match \n, and if I'm pulling in multiple
## lines, it can allow lines to match that would otherwise not match.
##
## Therefore, if there is a '[^' in a regex, we can NOT take a chance
## and use the fast listonly.
##
$CAN_USE_FAST_LISTONLY = $LIST_ONLY;
local(@extra, $orig);
local($underline_glue) = ($] >= 5) ? '(:?_\cH)?' : '(_\cH)?';
while (@ARGV) {
$regex = shift(@ARGV);
if ($literal) {
$orig = $regex if $literal;
$regex =~ s/(\W)/\\$1/g; ## quote everything
} else {
## try to be smart about a $ in the regex. If it looks
## like an end-of-line metacharacter, we'll leave it.
## Otherwise, escape it so that it has no variable
## substutition
$regex =~ s/(.?)\$([^\)|])/
$1 eq '\\' ? $& : "$1\\\$$2"/eg; ## quote some $
if ($] >= 5) {
$regex =~ s/\@/\\@/g; ## quote @
}
}
if ($DOMARK) {
local($tmp) = $regex;
$tmp =~ s,/,\/,g;
$tmp = join($tmp, '\b(', ')\b') if $words;
push(@mark_commands, "s/($tmp)/$mark\$1\e[m/g$iflag");
}
##
## If watching for underlined things too, add another regex.
##
if ($underlineOK) {
if ($regex =~ m/[?*+{}()\\.|^\$\[]/) {
warn "$0: warning, can't underline-safe ``$regex''.\n";
} else {
$regex = join($underline_glue, split(//, $regex));
}
}
## If nothing special in the regex, just use index...
## is quite a bit faster.
if (($iflag eq '') && ($words == 0) &&
($literal || ($regex !~ m/[?*+{}()\\.|^\$\[]/)))
{
$regex = $orig if $literal;
push(@regex_tests, "(index(\$_, q\001$regex\001)>=0)");
} else {
#$regex =~ s!([\$\@\/]\w)!\\$1!g;
if ($words) {
if ($regex =~ m/\|/) {
## could be dangerous -- see if we can wrap in parens.
if ($regex =~ m/\\\d/) {
warn "warning: -w and a | in a regex is dangerous.\n"
} else {
$regex = join($regex, '(', ')');
}
}
$regex = join($regex, '\b', '\b');
}
$CAN_USE_FAST_LISTONLY = 0 if substr($regex, "[^") >= 0;
push(@regex_tests, "m'$regex'$iflag$mflag");
}
## If we're done, but still have @extra to do, get set for that.
if (@ARGV == 0 && @extra) {
@ARGV = @extra; ## now deal with the extra stuff.
$underlineOK = 0; ## but no more of this.
undef @extra; ## or this.
}
}
if (@regex_tests) {
$REGEX_TEST = join('||', @regex_tests);
## print STDERR $REGEX_TEST, "\n"; exit;
} else {
## must be doing -find -- just give something syntactically correct.
$REGEX_TEST = 1;
}
if ($DOMARK) {
$MARK = join(';', @mark_commands);
}
}
##
## Make sure we can read the first item(s).
##
foreach $start (@todo) {
$! = 2, die qq/$0: can\'t stat "$start"\n/
unless ($dev,$inode) = (stat($start))[$STAT_DEV,$STAT_INODE];
if (defined $dir_done{"$dev,$inode"}) {
## ignore the repeat.
warn(qq/ignoring "$start" (same as "$dir_done{"$dev,$inode"}").\n/)
if $VERBOSE;
next;
}
## if -xdev was given, remember the device.
$xdev{$dev} = 1 if $XDEV;
## Note that we won't want to do it again
$dir_done{"$dev,$inode"} = $start;
}
}
##
## See the comment above the __END__ above the 'sub dodir' below.
##
sub import_program
{
sub bad {
print STDERR "$0: internal error (@_)\n";
exit 2;
}
## Read from data, up to next __END__. This will be &dodir.
local($/) = "\n__END__";
$prog = <DATA>;
close(DATA);
## Inline uppercase $-variables by their current values, removing
## any preceeding eval if applicable
if ($] >= 5) {
eval '
$prog =~ s/(?:\beval\s*)?\$([A-Z][A-Z0-9_]{2,}\b)/
&bad($1) if !defined ${$main::{$1}}; ${$main::{$1}};/eg;
';
} else {
$prog =~ s/(\beval\s*)?\$([A-Z][A-Z0-9_]{2,}\b)/local(*VAR) = $_main{$2};
&bad($2) if !defined $VAR; $VAR;/eg;
}
eval $prog; ## now do it. This will define &dodir;
$!=2, die "$0 internal error: $@\n" if $@;
}
###########################################################################
##
## Read the .search file:
## Blank lines and lines that are only #-comments ignored.
## Newlines may be escaped to create long lines
## Other lines are directives.
##
## A directive may begin with an optional tag in the form <...>
## Things inside the <...> are evaluated as with:
## <(this || that) && must>
## will be true if
## -xmust -xthis or -xmust -xthat
## were specified on the command line (order doesn't matter, though)
## A directive is not done if there is a tag and it's false.
## Any characters but whitespace and &|()>,! may appear after an -x
## (although "-xdev" is special). -xmust,this is the same as -xmust -xthis.
## Something like -x~ would make <~> true, and <!~> false.
##
## Directives are in the form:
## filter: EXPR : "command"
## option: STRING
## magic : NUMBYTES : EXPR
##
## With option:
## The STRING is parsed like a Bourne shell command line, and the
## options are used as if given on the command line.
## No comments are allowed on 'option' lines.
## Examples:
## # skip objects and libraries
## option: -skip '.o .a'
## # skip emacs *~ and *# files, unless -x~ given:
## <!~> option: -skip '~ #'
##
## With magic:
## EXPR can be pretty much any perl (comments allowed!).
## If it evaluates to true for any particular file, it is skipped.
## The only info you'll have about a file is the variable $H, which
## will have at least the first NUMBYTES of the file (less if the file
## is shorter than that, of course, and maybe more). You'll also have
## any variables you set in previous 'magic' lines.
## Examples:
## magic: 6 : ($x6 = substr($H, 0, 6)) eq 'GIF87a'
## magic: 6 : $x6 eq 'GIF89a'
##
## magic: 6 : (($x6 = substr($H, 0, 6)) eq 'GIF87a' ## old gif \
## || $x6 eq 'GIF89a' ## new gif
## (the above two sets are the same)
## ## Check the first 32 bytes for "binarish" looking bytes.
## ## Don't blindly dump on any high-bit set, as non-ASCII text
## ## often has them set. \x80 and \xff seem to be special, though.
## ## Require two in a row to not get things like perl's $^T.
## ## This is known to get *.Z, *.gz, pkzip, *.elc and about any
## ## executable you'll find.
## magic: 32 : $H =~ m/[\x00-\x06\x10-\x1a\x1c-\x1f\x80\xff]{2}/
##
sub read_rc
{
local($file, $show) = @_;
local($line_num, $ln, $tag) = 0;
local($use_default, @default) = 0;
{ package magic; $WARNING = 0; } ## turn off warnings for when we run EXPR's
unless (open(RC, "$file")) {
$use_default=1;
$file = "<internal default startup file>";
## no RC file -- use this default.
@default = split(/\n/,<<'--------INLINE_LITERAL_TEXT');
magic: 32 : $H =~ m/[\x00-\x06\x10-\x1a\x1c-\x1f\x80\xff]{2}/
filter: $N =~ m/\.(gz|Z)$/ : "zcat %"
option: -skip '.a .COM .elc .EXE .o .pbm .xbm .dvi'
option: -iskip '.tarz .zip .lzh .jpg .jpeg .gif .uu'
<!~> option: -skip '~ #'
--------INLINE_LITERAL_TEXT
}
##
## Make an eval error pretty.
##
sub clean_eval_error {
local($_) = @_;
s/ in file \(eval\) at line \d+,//g; ## perl4-style error
s/ at \(eval \d+\) line \d+,//g; ## perl5-style error
s/\n[\x00-\xff]*//; ## remove all but first line
"$_\n";
}
print "reading RC file: $file\n" if $show;
while ($_ = ($use_default ? shift(@default) : <RC>)) {
$ln = ++$line_num; ## note starting line num.
$_ .= <RC>, $line_num++ while s/\\\n?$/\n/; ## allow continuations
next if /^\s*(#.*)?$/; ## skip blank or comment-only lines.
$do = '';
## look for an initial <...> tag.
if (s/^\s*<([^>]*)>//) {
## This simple s// will make the tag ready to eval.
($tag = $msg = $1) =~
s/([^\s&|(!)]+)/
$seen_opt{$1}=1; ## note seen option
"defined(\$opt{q>$1>})" ## (q>> is safe quoting here)
/eg;
## see if the tag is true or not, abort this line if not.
$dothis = (eval $tag);
$!=2, die "$file $ln <$msg>: $_".&clean_eval_error($@) if $@;
if ($show) {
$msg =~ s/([^\s&|(!)]+)/-x$1/;
$msg =~ s/\s*!\s*/ no /g;
$msg =~ s/\s*&&\s*/ and /g;
$msg =~ s/\s*\|\|\s*/ or /g;
$msg =~ s/^\s+//; $msg =~ s/\s+$//;
$do = $dothis ? "(doing because $msg)" :
"(do if $msg)";
} elsif (!$dothis) {
next;
}
}
if (m/^\s*filter\s*:(.*):\s*"(.*)\s*"\s*$/) {
local($expr, $cmd) = ($1, $2);
eval "local(\$^W) = 0; $expr; 1";
die "$file $ln: ".&clean_eval_error($@) if $@;
$filter_cmd{$expr} = $cmd;
next;
}
if (m/^\s*option\s*:\s*(.*)/) {
next if $all && !$show; ## -all turns off these checks;
local($_) = $1;
s/\n$//;
local($orig) = $_;
print " $do option: $_\n" if $show;
local($0) = "$0 ($file)"; ## for any error message.
local(@ARGV);
local($this);
##
## Parse $_ as a Bourne shell line -- fill @ARGV
##
while (length) {
if (s/^\s+//) {
push(@ARGV, $this) if defined $this;
undef $this;
next;
}
$this = '' if !defined $this;
$this .= $1 while s/^\'([^\']*)\'// ||
s/^\"([^\"]*)\"// ||
s/^([^\'\"\s\\]+)//||
s/^(\\[\D\d])//;
die "$file $ln: error parsing $orig at $_\n" if m/^\S/;
}
push(@ARGV, $this) if defined $this;
&check_args;
die qq/$file $ln: unused arg "@ARGV".\n/ if @ARGV;
next;
}
if (m/^\s*magic\s*:\s*(\d+)\s*:\s*(.*)/) {
next if $all && !$show; ## -all turns off these checks;
local($bytes, $check) = ($1, $2);
if ($show) {
$check =~ s/\n?$/\n/;
print " $do contents: $check";
}
## Check to make sure the thing at least compiles.
eval "package magic; (\$H = '1'x \$main'bytes) && (\n$check\n)\n";
$! = 2, die "$file $ln: ".&clean_eval_error($@) if $@;
$HEADER_BYTES = $bytes if $bytes > $HEADER_BYTES;
push(@magic_tests, "(\n$check\n)");
next;
}
$! = 2, die "$file $ln: unknown command\n";
}
close(RC);
}
sub message
{
if (!$STDERR_IS_TTY) {
print STDERR $_[0], "\n";
} else {
local($text) = @_;
$thislength = length($text);
if ($thislength >= $last_message_length) {
print STDERR $text, "\r";
} else {
print STDERR $text, ' 'x ($last_message_length-$thislength),"\r";
}
$last_message_length = $thislength;
}
}
sub clear_message
{
print STDERR ' ' x $last_message_length, "\r" if $last_message_length;
$vv_print = $vv_size = $last_message_length = 0;
}
##
## Output a copy of this program with comments, extra whitespace, and
## the trailing man page removed. On an ultra slow machine, such a copy
## might load faster (but I can't tell any difference on my machine).
##
sub strip {
seek(DATA, 0, 0) || die "$0: can't reset internal pointer.\n";
while(<DATA>) {
print, next if /INLINE_LITERAL_TEXT/.../INLINE_LITERAL_TEXT/;
## must mention INLINE_LITERAL_TEXT on this line!
s/\#\#.*|^\s+|\s+$//; ## remove cruft
last if $_ eq '.00';
next if ($_ eq '') || ($_ eq "'di'") || ($_ eq "'ig00'");
s/\$stripped=0;/\$stripped=1;/;
s/\s\s+/ /; ## squish multiple whitespaces down to one.
print $_, "\n";
}
exit(0);
}
##
## Just to shut up -w. Never executed.
##
sub dummy {
1 || &dummy || &dir_done || &bad || &message || $NEXT_DIR_ENTRY ||
$VV_SIZE || $VV_PRINT_COUNT || $STDERR_SCREWS_STDOUT || @files ||
@files || $magic'H || $magic'H || $magic'val || $magic'val ||
$filter_cmd{1} || $xdev{''} || $MARK;
}
##
## If the following __END__ is in place, what follows will be
## inlined when the program first starts up. Any $ variable name
## all in upper case, specifically, any string matching
## \$([A-Z][A-Z0-9_]{2,}\b
## will have the true value for that variable inlined. Also, any 'eval'
## immediately preceeding one of the inlined variables is removed.
##
##
## The idea is that when the whole thing is then eval'ed to define &dodir,
## the perl optimizer will make all the decisions that are based upon
## command-line options (such as $VERBOSE), since they'll be inlined as
## constants
##
## Also, and here's the big win, the tests for matching the regex, and a
## few others, are all inlined. Should be blinding speed here.
##
## See the read from <DATA> above for where all this takes place.
## But all-in-all, you *want* the __END__ here. Comment it out only for
## debugging....
##
__END__
##
## Given a directory, check all "appropriate" files in it.
## Shove any subdirectories into the global @todo, so they'll be done
## later.
##
## Be careful about adding any upper-case variables, as they are subject
## to being inlined. See comments above the __END__ above.
##
sub dodir
{
local($dir) = @_;
$dir =~ s,/+$,,; ## remove any trailing slash.
unless (opendir(DIR, "$dir/.")) {
&clear_message if $VERBOSE && $STDERR_SCREWS_STDOUT;
warn qq($0: can\'t opendir "$dir/".\n);
return;
}
if ($VERBOSE) {
&message($dir);
$vv_print = $vv_size = 0;
}
@files = sort readdir(DIR) if $DO_SORT;
while (defined($name = eval $NEXT_DIR_ENTRY))
{
next if $name eq '.' || $name eq '..'; ## never follow these.
## create full relative pathname.
$file = $dir eq '.' ? $name : "$dir/$name";
## if link and skipping them, do so.
if ($NOLINKS && -l $file) {
warn qq/skip (symlink): $file\n/ if $WHY;
next;
}
## skip things unless files or directories
unless (-f $file || -d _) {
if ($WHY) {
$why = (-S _ && "socket") ||
(-p _ && "pipe") ||
(-b _ && "block special")||
(-c _ && "char special") || "somekinda special";
warn qq/skip ($why): $file\n/;
}
next;
}
## skip things we can't read
unless (-r _) {
if ($WHY) {
$why = (-l $file) ? "follow" : "read";
warn qq/skip (can\'t $why): $file\n/;
}
next;
}
## skip things that are empty
unless (-s _) {
warn qq/skip (empty): $file\n/ if $WHY;
next;
}
## Note file device & inode. If -xdev, skip if appropriate.
($dev, $inode) = (stat(_))[$STAT_DEV, $STAT_INODE];
if ($XDEV && defined $xdev{$dev}) {
warn qq/skip (other device): $file\n/ if $WHY;
next;
}
$id = "$dev,$inode";
## special work for a directory
if (-d _) {
if ($DESCEND_SUBDIRECTORIES == 0) {
warn qq/skip (-depth): $file\n/ if $WHY;
next;
}
## Do checks for directory file endings.
if ($DO_DSKIP_TEST && (eval $DSKIP_TEST)) {
warn qq/skip (-dskip): $file\n/ if $WHY;
next;
}
## do checks for -name/-regex/-path tests
if ($DO_DGLOB_TESTS && !(eval $DGLOB_TESTS)) {