-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathregrep~
1313 lines (1089 loc) · 43.8 KB
/
regrep~
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
#!/usr/bin/perl
# Copyright (c) 2006-2017, Mark Stephen Laker
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package ReGrep::Options;
use warnings;
use strict;
# How to treat binary files:
sub BinFilesBinary() {0} # Default: print a one-line message if there's a match, or nothing otherwise.
sub BinFilesNoMatch() {1} # Assume that a binary file never matches.
sub BinFilesText() {2} # Treat a binary file as if it were a textfile.
# How to treat directories:
sub DirActionRead() {0} # Default: read directories as if they were normal files
sub DirActionSkip() {1} # Silently ignore directories
sub DirActionRecurse() {2} # Recurse into directories
use fields
# Passed in by the caller:
'Binary', # On Dos-ish platforms, read files in binary mode
'ByteOffset', # Print the byte-offset of each line
'ContextAft', # Lines of context printed after a match
'ContextFore', # Lines of context printed before a match
'Count', # Print just a count of matches per file
'DevSkip', # True if you want to ignore devices
'DirAction', # One of the 'DirActionXxx' constants above
'DirExclude', # Pattern of filenames to exclude when recursing through a directory
'DirInclude', # Pattern of filenames to include when recursing through a directory
'ExtMatches', # Show only the text on each line that your regex captures using capturing brackets ( ).
'FileMatch', # print names of files with or without matches
'Filename', # print the filename
'Highlight', # Ansi control code to use for highlighting a match (undefined or empty if no highlighting is wanted)
'LineNo', # print the line number
'Invert', # Invert the match
'MaxCount', # Maximum number of (non-)matches we'll find and report
'NoMessages', # Suppress messages about nonexistent or unreadable files and directories
'NullIn', # Assume that input lines are separated by null bytes (\x00) instead of newlines.
'NullOut', # After printing a filename, output a null byte (\x00) instead of a colon or a dash.
'OnBinFile', # One of the 'BinFilesXxx' constants above
'OnlyMatching', # Print only the part of the line that matches the regex
'PerlBinary', # Print the auto-generated Perl function that greps binary files
'PerlFile', # Print the auto-generated Perl functions that do file-handling
'PerlText', # Print the auto-generated Perl function that greps text files
'Quiet', # Print no matches. Exit successfully as soon as a match is found.
'RX', # The regular expression we're searching for
'RxAfter', # If RxAfter is defined, a match is considered to extend up to (but not including) the next line matching RxAfter
'RxAIters', # If RxAfter and RxAIters are both define, a match extends up to the RxAIters'th line that matches RxAfter
'SemId', # The ID of the semaphore that allows us to print
'SemLock', # The semop string that acquires the semaphore that allows us to print
'SemUnlock', # The semop string that releases the semaphore
'SkipMatchFile',# Skip files whose names match the regex: useful for finding external references to a class or file
'Sparse', # Load small files into memory and pre-check them before breaking them into lines
'Threaded', # True if we're running multithreaded, and we must acquire a semaphore before printing.
'UnixOffset', # On Windows, print byte offsets as if this were a Unix file (i.e. with the CRs stripped out)
# Maintained by ReGrep:
'BinGrepper', # A reference to a hand-compiled function that greps binary files with the options the user has chosen
'CurFileNo', # Number of files processed with this Options object
'FhGrepper', # A reference to a hand-compiled function that determines whether a filehandle is text or binary and calls the right grepper
'FileGrepper', # A reference to a hand-compiled function that skips pipes, devices, etc, recurses into directories, and greps plain files
'PlainGrepper', # A reference to a hand-compiled function that opens a file and then calls FhGrepper
'Recurser', # A reference to a hand-compiled function that goes into directories and greps each file in turn
'TextGrepper', # A reference to a hand-compiled function that greps text files with the options the user has chosen
'OpenFailures'; # The number of files that couldn't be opened
sub new() {
return fields::new __PACKAGE__;
}
package ReGrep;
use warnings;
use strict;
sub AnsiCancelHighlight() {"\x1B[0m"}
# Compilation and execution proceed in the following stages:
#
# 1. Perl compiles and runs your program in the usual way.
# 2. At some point, your program gathers options and calls &ReGrep::compile.
# 3. &compile takes a copy of $sub_filehandle_grep_text and preprocesses it by
# removing code that implements features the user didn't ask for.
# 4. &compile eval()s the proprocessed text. The result is a reference to an
# anonymous sub that greps a text file in the way the user wants. The
# reference is stored in $$options{TextGrepper}.
# 5. Steps 3 and 4 are repeated for $sub_filehandle_grep_binary and the
# customisable file-handling subs.
# 6. At some later point, your program calls $$options{FileGrepper} () or
# $$options{FhGrepper} (). These functions end up calling the other
# anonymous subs compiled earlier.
#
# Why do we make life so complicated? By paring the grepper function down to
# the bone, we make it run as fast as possible. Rather than continually
# testing whether a feature is wanted and skipping over it if it isn't, we
# avoid the cost of the test by not compiling unwanted features into the code.
#
# We use three kinds of preprocessing:
#
# A. Conditional compilation (#if, #elsif, #else, #endif); the expressions in
# these lines are evaluated in step 3.
# B. Symbolic constants (#define), whose values are substituted into the code
# when they appear later in the text.
# C. Substitution of compile-time constants. The expression
# const«$$options{ContextFore}» evaluates $$options{ContextFore} during
# step 3 and writes its value as a literal number into the code.
#
# The preprocessing mechanism is deliberately reminiscent of the C
# preprocessor as a visual reminder that preprocessing directives are run
# before the rest of the code is compiled, let alone run.
#
# If you can think of ways to make this code even less maintainable, I'd be
# interested in hearing them.
##########################################################################
#
# Text-file grepper
my $sub_filehandle_grep_text = <<'SUB';
sub {
(my $fhout, my $fhin, my $filename, my ReGrep::Options $options) = @_;
my $nrmatches = 0;
my $rx = $$options{RX};
#define INVERT const«$$options{Invert}? 'not': ''»
#if defined $$options{Sparse}
my $sparse_found;
if (-f $fhin and -s _ <= const«$$options{Sparse}») {
read $fhin, my $buf, const«$$options{Sparse}»;
$sparse_found = INVERT $buf =~ $rx;
#if $$options{Quiet}
exit 0 if $sparse_found;
#endif
#if $$options{FileMatch}
$nrmatches = $sparse_found;
#define IF_SPARSE_ALLOWS unless (defined $sparse_found) {
#else
seek $fhin, 0, 0;
#define IF_SPARSE_ALLOWS if ($sparse_found or not defined $sparse_found) {
#endif
}
#else
#define IF_SPARSE_ALLOWS
#endif
#if $$options{ContextFore} or $$options{ContextAft} or $$options{RxAfter}
my $printlineno = defined($$options{CurFileNo})? -1: undef;
my $curfileno = $$options{CurFileNo} || 0;
#endif
#if $$options{NullOut}
#define POST_FN_MATCH "\x00"
#define POST_FN_CTX "\x00"
#define POST_FN_CNT "\x00"
#define POST_FN_FOUND "\x00"
#else
#define POST_FN_MATCH ":"
#define POST_FN_CTX "-"
#define POST_FN_CNT ":"
#define POST_FN_FOUND "\n"
#endif
#if $$options{ContextFore}
my @forecontext;
#if $$options{ByteOffset}
my @foreoffs;
#endif
my $hist_consume = 0;
#endif
#if $$options{ContextFore} or $$options{ContextAft} or $$options{RxAfter}
my $hist_length = 0;
#endif
#if $$options{ContextAft} or $$options{RxAfter}
my $aftershadow = 0;
#endif
#if $$options{RxAfter}
my $rx_after_iters;
#endif
#if $$options{ByteOffset}
my $lineoffs = 0;
#endif
#if $$options{NullIn}
#define LINETERM "\x00"
#define RX_LINETERM \x00
#else
#define LINETERM "\n"
#define RX_LINETERM \n
#endif
#if defined $$options{MaxCount}
my $maxcount = const«$$options{MaxCount}»;
my $seekback;
#endif
#if $$options{Binary}
binmode $fhin;
#endif
#if $$options{Highlight}
my $opt_highlight = $$options{Highlight};
#endif
#if $$options{Threaded} and not ($$options{Count} or $$options{FileMatch})
my $got_print_mtx;
#endif
#if $$options{RxAfter}
my $rx_after = $$options{RxAfter};
#endif
local $_;
IF_SPARSE_ALLOWS
while (<$fhin>) {
#if defined $$options{MaxCount}
#define CHECK_SHADOW const«($$options{ContextAft} or $$options{RxAfter})? 'or $aftershadow': ''»
last unless $maxcount CHECK_SHADOW;
#endif
#define CHECK_COUNT const«defined $$options{MaxCount}? 'and $maxcount': ''»
if (INVERT /$rx/ CHECK_COUNT) {
#if $$options{Quiet}
exit 0;
#endif
++$nrmatches;
#if defined $$options{MaxCount}
--$maxcount or $seekback = tell $fhin;
#endif
#if not($$options{Count} or defined $$options{FileMatch})
#if $$options{Threaded}
unless ($got_print_mtx) {
semop $$options{SemId}, $$options{SemLock}
or die "Can't acquire SysV mutex: $!\n";
$got_print_mtx = 1;
}
#endif
#if $$options{ContextFore} or $$options{ContextAft} or $$options{RxAfter}
#if $$options{ContextFore}
#define GAP 1 + $hist_length
#else
#define GAP 1
#endif
# Print dashes if we're printing context and there's been a
# gap in our output:
print $fhout "--\n" if defined $printlineno and $printlineno + GAP != $.;
#endif
#if $$options{ContextFore}
# Print the 'before' context:
while ($hist_length) {
#if not $$options{OnlyMatching}
#if $$options{Filename}
print $fhout $filename, POST_FN_CTX;
#endif
#if $$options{LineNo}
print $fhout $. - $hist_length, '-';
#endif
#if $$options{ByteOffset}
print $fhout $foreoffs[$hist_consume], '-';
#endif
print $fhout $forecontext[$hist_consume];
#endif
--$hist_length;
$hist_consume = ($hist_consume+1) % const«$$options{ContextFore}»;
}
#endif
# Print the matching line:
#if not $$options{OnlyMatching} # OnlyMatching has to make its own arrangements: it prints one intro for each match on the line
#if $$options{Filename}
print $fhout $filename, POST_FN_MATCH;
#endif
#if $$options{LineNo}
print $fhout $., ':';
#endif
#if $$options{ByteOffset}
print $fhout $lineoffs, ':';
#endif
#endif
#if $$options{Highlight}
chomp (my $text = $_);
print $fhout $1, $opt_highlight, $2, AnsiCancelHighlight while $text =~ /\G(.*?)($rx)/gc;
print $fhout substr($text, pos $text), "\n";
#elsif $$options{ExtMatches}
chomp (my $text = $_);
print $fhout $text =~ /$rx/g, "\n";
#elsif $$options{OnlyMatching}
chomp (my $text = $_);
while ($text =~ / \G .*? ($rx) /gx) {
#if $$options{Filename}
print $fhout $filename, POST_FN_MATCH;
#endif
#if $$options{LineNo}
print $fhout $., ':';
#endif
#if $$options{ByteOffset}
print $fhout $lineoffs + $+[0] - length($1), ':';
#endif
print $fhout $1, "\n";
}
#else
print $fhout $_;
print $fhout LINETERM unless /RX_LINETERM/;
#endif
#if $$options{RxAfter}
#define INITIAL_AFTER_ITERS const«defined($$options{RxAIters})? $$options{RxAIters}: 0»
$aftershadow = -1;
$rx_after_iters = INITIAL_AFTER_ITERS;
#elsif $$options{ContextAft}
$aftershadow = const«$$options{ContextAft}»;
#endif
#if $$options{ContextFore} or $$options{ContextAft} or $$options{RxAfter}
$printlineno = $.;
#endif
#endif
}
#if $$options{ContextFore} or $$options{ContextAft} or $$options{RxAfter}
else {
#endif
#if defined $$options{RxAfter}
#define AFTER_RX_SHADOW const«$$options{ContextAft}? $$options{ContextAft}: 0»
if ($aftershadow < 0 and /$rx_after/) {
#if defined $$options{RxAIters}
$rx_after_iters-- == 0 and
#endif
$aftershadow = AFTER_RX_SHADOW;
}
#endif
#if $$options{ContextAft} or $$options{RxAfter}
# If the line doesn't match, print any 'after' context.
if ($aftershadow) {
--$aftershadow;
#if not $$options{OnlyMatching}
#if $$options{Filename}
print $fhout $filename, POST_FN_CTX;
#endif
#if $$options{LineNo}
print $fhout $., '-';
#endif
#if $$options{ByteOffset}
print $fhout $lineoffs, '-';
#endif
print $fhout $_;
print $fhout LINETERM unless /RX_LINETERM/;
#endif
$printlineno = $.;
}
#endif
#if $$options{ContextFore}
#define CONJUNCTION const«$$options{ContextAft}? 'elsif': 'if'»
# If the line isn't printed, save it as possible 'before' context
# for the next match:
CONJUNCTION ($hist_length == const«$$options{ContextFore}») {
$forecontext[$hist_consume] = $_;
#if $$options{ByteOffset}
$foreoffs[$hist_consume] = $lineoffs;
#endif
$hist_consume = ($hist_consume+1) % const«$$options{ContextFore}»;
}
else {
my $savepos = ($hist_consume + $hist_length) % const«$$options{ContextFore}»;
$forecontext[$savepos] = $_;
#if $$options{ByteOffset}
$foreoffs[$savepos] = $lineoffs;
#endif
++$hist_length;
}
#endif
#if $$options{ContextFore} or $$options{ContextAft} or $$options{RxAfter}
}
#endif
#if $$options{ByteOffset}
#if $$options{UnixOffset}
$lineoffs += length;
#else
$lineoffs = tell $fhin;
#endif
#endif
}
#if defined $$options{Sparse}
}
#endif
#if defined $$options{FileMatch}
if (($nrmatches != 0) == const«$$options{FileMatch}») {
#if $$options{Threaded}
semop $$options{SemId}, $$options{SemLock}
or die "Can't acquire SysV mutex: $!\n";
#endif
print $fhout $filename, POST_FN_FOUND;
#if $$options{Threaded}
semop $$options{SemId}, $$options{SemUnlock}
or die "Can't release SysV mutex: $!\n";
#endif
}
#endif
#if $$options{Count}
#if $$options{Threaded}
semop $$options{SemId}, $$options{SemLock}
or die "Can't acquire SysV mutex: $!\n";
#endif
#if $$options{Filename}
print $fhout $filename, POST_FN_CNT;
#endif
print $nrmatches, "\n";
#if $$options{Threaded}
semop $$options{SemId}, $$options{SemUnlock}
or die "Can't release SysV mutex: $!\n";
#endif
#endif
#if $$options{Threaded} and not ($$options{Count} or $$options{FileMatch})
semop $$options{SemId}, $$options{SemUnlock}
or die "Can't release SysV mutex: $!\n"
if $got_print_mtx;
#endif
#if $$options{ContextFore} or $$options{ContextAft}
# Keep enough state to know whether we must print a separarator line
# before the next block of output:
$$options{CurFileNo} = $curfileno + 1;
#endif
#if defined $$options{MaxCount}
seek $fhin, $seekback, 0 if defined $seekback;
#endif
return $nrmatches;
}
SUB
##########################################################################
#
# Binary-file grepper
my $sub_filehandle_grep_binary = <<'SUB';
sub {
(my $fhout, my $fhin, my $filename) = @_;
my $nrmatches = 0;
my $rx = $$options{RX};
#if defined $$options{MaxCount}
my $maxcount = const«$$options{MaxCount}»;
#endif
while (<$fhin>) {
#if defined $$options{MaxCount}
last unless $maxcount;
#endif
if (
#if $$options{Invert}
not
#endif
/$rx/) {
#if $$options{Quiet}
exit 0;
#endif
#if not ($$options{Count} or defined $$options{FileMatch})
print $fhout "Binary file ";
print $fhout $filename, ' ' if defined $filename;
print $fhout "matches\n";
return 1;
#endif
++$nrmatches;
#if defined $$options{MaxCount}
--$maxcount;
#endif
}
}
#if $$options{NullOut}
#define POST_FN_MATCH "\x00"
#define POST_FN_COUNT "\x00"
#else
#define POST_FN_MATCH "\n"
#define POST_FN_COUNT ":"
#endif
#if $$options{FileMatch}
print $fhout $filename, POST_FN_MATCH if ($nrmatches != 0) == const«$$options{FileMatch}»;
#elsif $$options{Count}
print $fhout $filename, POST_FN_COUNT, $nrmatches, "\n";
#endif
return $nrmatches;
}
SUB
##########################################################################
#
# Grepper for any filehandle: works out whether we have a textfile or a
# binary file, and calls the appropriate grepper (if any):
my $sub_filehandle_grep = <<'SUB';
sub {
(my $fhout, my $fhin, my $filename, my ReGrep::Options $options) = @_;
local $/ = const«$$options{NullIn}? q/"\x00"/: q/"\n"/»;
#if $$options{OnBinFile} == ReGrep::Options::BinFilesText or $$options{NullIn}
return $$options{TextGrepper} ($fhout, $fhin, $filename, $options);
#else
return -T $fhin?
$$options{TextGrepper} ($fhout, $fhin, $filename, $options):
#if $$options{OnBinFile} == ReGrep::Options::BinFilesBinary
$$options{BinGrepper} ($fhout, $fhin, $filename, $options);
#else
0;
#endif
#endif
}
SUB
##########################################################################
#
# Grepper for any plain file (as opposed to a directory): opens the file
# and, on success, passes it to the filehandle grepper.
my $sub_plain_file_grep = <<'SUB';
sub {
(my $fhout, my $filename, my ReGrep::Options $options) = @_;
if (open my $fhin, '<', $filename) {
# print join(" :: ", PerlIO::get_layers $fhin), "\n";
# exit;
return $$options{FhGrepper} ($fhout, $fhin, $filename, $options);
}
else {
#if not $$options{NoMessages}
print STDERR "$filename: $!\n";
#endif
++$$options{OpenFailures};
return 0;
}
}
SUB
##########################################################################
#
# Given a directory name, greps all the files in the directory.
my $sub_recurse_into_dir = <<'SUB';
sub {
(my $fhout, my $dirname, my ReGrep::Options $options) = @_;
if (opendir my $dh, $dirname) {
$dirname .= '/' unless $dirname =~ m|[/\\]$|;
my $nrmatches = 0;
while (defined(my $basename = readdir $dh)) {
next if $basename =~ /^\.\.?$/;
#if defined $$options{DirExclude} or $$options{DirInclude}
my $fullname = $dirname . $basename;
next if (
#if defined $$options{DirInclude}
$basename !~ /const«$$options{DirInclude}»/
#if defined $$options{DirExclude}
or
#endif
#endif
#if defined $$options{DirExclude}
$basename =~ /const«$$options{DirExclude}»/
#endif
)
and not -d $fullname;
$nrmatches += $$options{FileGrepper} ($fhout, $fullname, $options);
#else
$nrmatches += $$options{FileGrepper} ($fhout, $dirname . $basename, $options);
#endif
}
return $nrmatches;
}
else {
#if not $$options{NoMessages}
print STDERR "$dirname: $!\n";
#endif
return 0;
}
}
SUB
##########################################################################
# Given a filename, this sub works out whether it refers to a plain file,
# a directory or a special file (pipe, device, etc), and calls the
# appropriate subfunction.
my $sub_file_grep = <<'SUB';
sub {
(my $fhout, my $filename, my ReGrep::Options $options) = @_;
#if $$options{SkipMatchFile}
return 0 if $filename =~ m| ([^/\\]+) $ |x and $1 =~ $$options{RX};
#endif
stat $filename;
#if $$options{DevSkip}
return 0 if -p _ or -S _ or -b _ or -c _;
#endif
#if $$options{DirAction} == ReGrep::Options::DirActionSkip
return 0 if -d _;
#endif
#if $$options{DirAction} == ReGrep::Options::DirActionRecurse
return $$options{Recurser} ($fhout, $filename, $options)
if -d _;
#endif
return $$options{PlainGrepper} ($fhout, $filename, $options);
}
SUB
##########################################################################
# Here are the preprocessor and compiler for the functions above.
# The #if/#elsif/#else/#endif processor doesn't recurse. It uses an array
# of states, called @stack, and emits text when all the states are On.
sub Off() {0} # This #if...#endif hasn't yet had a true branch.
sub On() {1} # We're in a true branch. Emit code.
sub Done() {2} # We've had a true branch. This and all following branches are false.
sub eval_or_die($$) {
(my $text, my ReGrep::Options $options) = @_;
my $code = eval $text;
die "Can't eval {$text}:\n$@\n" if $@;
return $code;
}
sub combine_states_for_elsif($$$) {
(my $state, my $condition, my ReGrep::Options $options) = @_;
return Done unless $state == Off;
return eval_or_die($condition, $options)? On: Off;
}
sub all_states_are_on(\@) {
my ($rstack) = @_;
return not grep {$_ != On} @$rstack;
}
# Tie together the #if...#endif system by answering the question:
# does this line belong in the output or not?
sub should_emit(\@$$) {
(my $rstack, my $line, my ReGrep::Options $options) = @_;
if (my ($cond) = $line =~ /^\s*#if\s+(.*)/) {
push @$rstack, eval_or_die($cond, $options)? On: Off;
return 0;
}
if (my ($cond) = $line =~ /^\s*#elsif\s+(.*)/) {
$$rstack[-1] = combine_states_for_elsif $$rstack[-1], $cond, $options;
return 0;
}
if ($line =~ /^\s*#else\b/) {
$$rstack[-1] = $$rstack[-1] == Off? On: Done;
return 0;
}
if ($line =~ /^\s*#endif\b/) {
pop @$rstack;
return 0;
}
return all_states_are_on @$rstack;
}
# Break the input code into lines. Discard anything that should be #if-ed out,
# implement define-constants, and do const«»-substitution.
# This completes step 3.
sub preprocess($$) {
(my $text, my ReGrep::Options $options) = @_;
my (%defs, $rx_defs);
my @stack;
my @result;
for my $line (split /\n/, $text) {
#Skip lines that are #if-ed out:
next unless should_emit @stack, $line, $options;
# Substitute constants for const«anything»:
0 while $line =~ s/ \b const « (.*?) » / eval_or_die $1, $options /ex;
# Catch #defines:
if ($line =~ / ^ \s* \#define \s+ (\w+) \s* (.*) /x) {
$defs{$1} = $2;
$rx_defs = join '|', keys %defs;
$rx_defs = qr/\b(?:$rx_defs)\b/;
next;
}
# Substitute #defined text:
if (defined $rx_defs) {
0 while $line =~ s/($rx_defs)/$defs{$1}/;
}
# And emit the result:
push @result, $line if $line =~ /\S/;
}
return join "\n", @result, '';
}
# Compile the resulting code into a set of anonymous subs, and store references
# to them in %$options. This is steps 4 and 5.
sub compile($$) {
(my $fhout, my ReGrep::Options $options) = @_;
$$options{OnBinFile} ||= ReGrep::Options::BinFilesBinary;
$$options{DirAction} ||= ReGrep::Options::DirActionRead;
my $text = preprocess $sub_filehandle_grep_text, $options;
print $fhout "\n", $text, "\n" if $$options{PerlText};
$$options{TextGrepper} = eval_or_die $text, $options;
$text = preprocess $sub_filehandle_grep, $options;
print $fhout "\n", $text, "\n" if $$options{PerlFile};
$$options{FhGrepper} = eval_or_die $text, $options;
$text = preprocess $sub_plain_file_grep, $options;
print $fhout "\n", $text, "\n" if $$options{PerlFile};
$$options{PlainGrepper} = eval_or_die $text, $options;
$text = preprocess $sub_file_grep, $options;
print $fhout "\n", $text, "\n" if $$options{PerlFile};
$$options{FileGrepper} = eval_or_die $text, $options;
if ($$options{DirAction} == ReGrep::Options::DirActionRecurse) {
$text = preprocess $sub_recurse_into_dir, $options;
print $fhout "\n", $text, "\n" if $$options{PerlFile};
$$options{Recurser} = eval_or_die $text, $options;
}
if ($$options{OnBinFile} == ReGrep::Options::BinFilesBinary) {
$text = preprocess $sub_filehandle_grep_binary, $options;
print $fhout "\n", $text, "\n" if $$options{PerlBinary};
$$options{BinGrepper} = eval_or_die $text, $options;
}
}
package main;
use warnings;
use strict;
use IPC::SysV qw/IPC_PRIVATE S_IRWXU IPC_CREAT IPC_RMID GETVAL/;
use Socket;
our $VERSION = 0.07;
# Won't start more --jobs than this:
sub MaxNrJobs() {12}
# Used to keep each file's output together when we run multiple threads:
my $semaphore;
END {
if ($semaphore) {
semctl $semaphore, 0, IPC_RMID, 0
or print STDERR "semop failed: $!\n";
}
}
# ... even if exit is violent:
$SIG{INT} = sub {exit 2};
# Gnu grep exits with status 2 on error:
$SIG{__DIE__} = sub {
if (defined $^S and not $^S) { # i.e. executing, not compiling, and not within an eval
(my $msg) = @_;
print $msg, "\n";
exit 2;
}
};
sub print_help_and_die() {
die <<'HELP';
regrep [options] <Perl5-regex> [<file...>]
Options are:
-A, --after-context <line-count>
-a, --text
-B, --before-context <line-count>
-b, --byte-offset
-C, --context <line-count>
-c, --count
-D, --devices {read,skip}
-d, --directories {read,skip,recurse}
-e, --regexp <Perl5-regex>
-F, --fixed-strings <strings-separated-by-newlines>
-f, --file <filename>
-H, --with-filename
-h, --no-filename
-I, --ignore-binary-files
-i, --ignore-case
-L, --files-without-match
-l, --files-with-matches
-m, --max-count <maximum-number-of-matches>
-n, --line-number
-o, --only-matching
-q, --quiet, --silent
-r, -R, --recursive
-s, --no-messages
-U, --binary
-u, --unix-byte-offsets
-v, --invert-match
-w, --word-regexp
-x, --line-regexp
-Z, --null
-z, --null-data
--binary-files
--colour, --color[={auto,never,always}]
--exclude <Perl5-regex>
--include <Perl5-regex>
--label
Same as in Gnu grep(1), except that regrep uses Perl 5 regular
expressions where Gnu grep(1) uses simpler regular expressions or
bash-style filename globs
--after can take a regular expression and optional iteration and line counts
using '*' and '+' symbols:
--after '^$' matches up to, not including, the next blank line.
--after '+1+^$' matches up to, and including, the next blank line.
--after '+3+^$' matches up to next blank line and two lines after.
--after '*2*^$' matches up to, not including, the third blank line.
--after '+1+*2*^$' matches up to and including the third blank line.
The second '+' and '*' can be omitted unless the next char is a digit:
--after '+1*2^$' is equivalent to the previous example.
-M, --exclude-matching
Exclude files whose basenames match the regex -- useful for finding
external references to classes or files.
-p, --pipe-filenames
Treat stdin as a newline-separated list of files to be grepped.
-j, --jobs <number-of-theads>
Grep multiple piped files in parallel.
-X, --extend-regexp
Compile the Perl regex with //x
-y, --extract-matches
Print only the parts of each line that your regex captures using
brackets ( ).
-S, --sparse <maximum-size-in-bytes>
Preload and pre-scan small files; only those that match are given a
full grep. Saves time when most files aren't expected to match.
HELP
}
sub default_to($$) {
$_[0] = $_[1] unless defined $_[0];
}
my ($opt_caseblind, $opt_extrx, $opt_wordrx, $opt_linerx, $opt_rx,
$opt_filename, $opt_label, $opt_pipefilenames, $opt_nullin, $opt_jobs);
sub decode_highlight($) {
my ($text) = @_;
$text = 'never' unless defined $text and $text ne '';
my $ansi_colour = defined $ENV{GREP_COLOR}? "\x1B[$ENV{GREP_COLOR}m": "\x1B[36m"; # cyan
return '' if $text eq 'never';
return $ansi_colour if $text eq 'always';
return -t STDOUT? $ansi_colour: '' if $text eq 'auto';
die "'--colour' must be followed by 'never', 'always' or 'auto'\n";
}
sub decode_on_bin_file($) {
my ($text) = @_;
default_to $text, 'binary';
return $text eq 'binary'? ReGrep::Options::BinFilesBinary:
$text eq 'without-match'? ReGrep::Options::BinFilesNoMatch:
$text eq 'text'? ReGrep::Options::BinFilesText:
die "'--binary-files' must be followed by 'binary', 'without-match' or 'text'\n";
}
sub decode_dev_skip($) {
my ($text) = @_;
default_to $text, 'read';
return $text eq 'read'? 0:
$text eq 'skip'? 1:
die "--devices must be followed by 'read' or 'skip'\n";
}
sub decode_dir_action($) {
my ($text) = @_;
default_to $text, 'read';
return $text eq 'read'? ReGrep::Options::DirActionRead:
$text eq 'skip'? ReGrep::Options::DirActionSkip:
$text eq 'recurse'? ReGrep::Options::DirActionRecurse:
die "--directories must be followed by 'read', 'skip' or 'recurse'\n";
}
# GNU grep has a --colour switch. It has an optional argument, which must be
# separated from the switch name by '=', not space. Getopt::Long doesn't
# support this syntax, so hack it in by hand.
sub get_colour_switch() {
my @colours = grep {/ ^ --colou?r \b =? /x} @ARGV or return 'never';
@ARGV = grep {not / ^ --colou?r \b /x} @ARGV;
return $colours[0] =~ /=(.*)/? $1: 'auto';
}
# Compile a regular expression provided by the user.
sub compile_rx($) {
my ($rx) = @_;
return defined $rx?
eval {qr/$rx/m} || die "Invalid regular expression, $rx:\n$@\n":
undef;
}
# Parse a --fixed-strings argument: a set of multiple regexen, separated by
# newlines. Return a string representation of a single regex that matches
# any of the strings.
my @fixed_strings; # Support multiple occurrences of --fixed-strings
sub read_fixed_strings($) {
my ($arg) = @_;
push @fixed_strings, map {"(?:\Q$_\E)"} split /\n/, $arg;
return join '|', @fixed_strings;
}
# Read a set of patterns from a file. Build a single regex that matches any
# of the patterns.
#
# We can't die if the file is unreadable, because Getopt::Long would catch the
# exception and return failure, which would cause us to display an unwanted
# syntax summary. So we just store the failure here for later display.