forked from mattn/jvgrep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jvgrep.go
1057 lines (989 loc) · 21.4 KB
/
jvgrep.go
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
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/signal"
"path/filepath"
"regexp"
"regexp/syntax"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"unicode/utf8"
"unsafe"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"github.com/mattn/jvgrep/mmap"
"golang.org/x/net/html/charset"
"golang.org/x/text/transform"
)
const version = "4.5"
const (
MAGENTA = "\x1b[35;1m"
CYAN = "\x1b[36;1m"
GREEN = "\x1b[32;1m"
RED = "\x1b[31;1m"
RESET = "\x1b[39;0m"
)
var encodings = []string{
"iso-2022-jp",
"euc-jp",
"sjis",
"utf-8",
"utf-16le",
"utf-16be",
}
var (
stdout = colorable.NewColorableStdout()
)
type GrepArg struct {
pattern interface{}
input interface{}
single bool
atty bool
bom []byte
}
const excludeDefaults = `/\.git$|/\.svn$|/\.hg$|\.o$|\.obj$|\.a$|\.exe~?$|/tags$`
var (
encs string // encodings
exclude string // exclude pattern
fixed bool // fixed search
ignorecase bool // ignorecase
ignorebinary bool // ignorebinary
infile string // input filename
invert bool // invert search
only bool // show only matched
list bool // show the list matches
number bool // show line number
recursive bool // recursible search
verbose bool // verbose output
utf8out bool // output utf-8 strings
perl bool // perl regexp syntax
basic bool // basic regexp syntax
oc io.Writer // output encoder
color string // color operation
cwd, _ = os.Getwd() // current directory
zeroFile bool // write \0 after the filename
zeroData bool // write \0 after the match
countMatch = 0 // count of matches
count bool // count of matches
fullpath = true // show full path
after = 0 // show after lines
before = 0 // show before lines
separator = ":" // column separator
)
var walk = filepath.Walk
func walkAsync(base string, walkFn filepath.WalkFunc) error {
fi, err := os.Lstat(base)
if err != nil {
return err
}
if !fi.IsDir() {
return fmt.Errorf("%q is not a directory", base)
}
wg := new(sync.WaitGroup)
var fn func(p string)
fn = func(p string) {
defer wg.Done()
var f *os.File
f, err = os.Open(p)
if err != nil {
return
}
defer f.Close()
fis, err := f.Readdir(-1)
if err != nil {
return
}
for _, fi := range fis {
tp := filepath.Join(p, fi.Name())
err = walkFn(tp, fi, err)
if err != nil {
if err == filepath.SkipDir {
continue
}
return
}
if fi.IsDir() {
wg.Add(1)
go fn(tp)
}
}
}
wg.Add(1)
go fn(base)
wg.Wait()
return nil
}
func printline_zero(s string) {
printstr(s + "\x00")
}
func printline_norm(s string) {
printstr(s + "\n")
}
var printline func(string) = printline_norm
func printstr(s string) {
printbytes(*(*[]byte)(unsafe.Pointer(&s)))
}
func printbytes_utf8(b []byte) {
syscall.Write(syscall.Stdout, b)
}
func printbytes_outc(b []byte) {
oc.Write(b)
}
func printbytes_norm(b []byte) {
stdout.Write(b)
}
var printbytes func([]byte) = printbytes_norm
func matchedfile(f string) {
if !fullpath {
if fe, err := filepath.Rel(cwd, f); err == nil {
f = fe
}
}
printline(f)
}
func matchedline(f string, l int, m string, a *GrepArg) {
lc := separator
if l < 0 {
lc = "-"
l = -l
}
if !a.atty {
if f != "" {
if !fullpath {
if fe, err := filepath.Rel(cwd, f); err == nil {
f = fe
}
}
if zeroFile {
printstr(f + separator + fmt.Sprint(l) + "\x00")
} else {
printstr(f + separator + fmt.Sprint(l) + lc)
}
}
printline(m)
return
}
if f != "" {
if !fullpath {
if fe, err := filepath.Rel(cwd, f); err == nil {
f = fe
}
}
if zeroFile {
printstr(MAGENTA + f + RESET + "\x00" + GREEN + fmt.Sprint(l) + CYAN + separator + RESET)
} else {
printstr(MAGENTA + f + RESET + separator + GREEN + fmt.Sprint(l) + CYAN + separator + RESET)
}
}
if re, ok := a.pattern.(*regexp.Regexp); ok {
ill := re.FindAllStringIndex(m, -1)
if len(ill) == 0 {
printline(m)
return
}
for i, il := range ill {
if i > 0 {
printstr(m[ill[i-1][1]:il[0]] + RED + m[il[0]:il[1]] + RESET)
} else {
printstr(m[0:il[0]] + RED + m[il[0]:il[1]] + RESET)
}
}
printline(m[ill[len(ill)-1][1]:])
} else if s, ok := a.pattern.(string); ok {
l := len(s)
for {
i := strings.Index(m, s)
if i < 0 {
printline(m)
break
}
printstr(m[0:i] + RED + m[i:i+l] + RESET)
m = m[i+l:]
}
}
}
func errorline(s string) {
os.Stderr.WriteString(s + "\n")
}
func maybeBinary(b []byte) bool {
l := len(b)
if l > 10000000 {
l = 1024
}
if l > 1024 {
l /= 2
}
for i := 0; i < l; i++ {
if 0 < b[i] && b[i] < 0x9 {
return true
}
}
return false
}
func doGrep(path string, f []byte, arg *GrepArg) {
encs := encodings
if ignorebinary {
if maybeBinary(f) {
return
}
}
if len(f) > 2 {
if f[0] == 0xfe && f[1] == 0xff {
arg.bom = f[0:2]
f = f[2:]
} else if f[0] == 0xff && f[1] == 0xfe {
arg.bom = f[0:2]
f = f[2:]
}
}
if len(arg.bom) > 0 {
if arg.bom[0] == 0xfe && arg.bom[1] == 0xff {
encs = []string{"utf-16be"}
} else if arg.bom[0] == 0xff && arg.bom[1] == 0xfe {
encs = []string{"utf-16le"}
}
}
re, _ := arg.pattern.(*regexp.Regexp)
rs, _ := arg.pattern.(string)
for _, enc := range encs {
if verbose {
println("trying("+enc+"):", path)
}
if len(arg.bom) > 0 && enc != "utf-16be" && enc != "utf-16le" {
continue
}
did := false
var t []byte
var n, l, size, next, prev int
if enc != "" {
if len(arg.bom) > 0 || !maybeBinary(f) {
ee, _ := charset.Lookup(enc)
if ee == nil {
continue
}
var buf bytes.Buffer
ic := transform.NewWriter(&buf, ee.NewDecoder())
_, err := ic.Write(f)
if err != nil {
next = -1
continue
}
lf := false
if len(arg.bom) > 0 && len(f)%2 != 0 {
ic.Write([]byte{0})
lf = true
}
err = ic.Close()
if err != nil {
if verbose {
println(err.Error())
}
next = -1
continue
}
f = buf.Bytes()
if lf {
f = f[:len(f)-1]
}
}
}
size = len(f)
if size == 0 {
continue
}
for next != -1 {
for {
if next >= size {
next = -1
break
}
if f[next] == '\n' {
break
}
next++
}
n++
if next == -1 {
t = f[prev:]
} else {
t = f[prev:next]
prev = next + 1
next++
}
l = len(t)
if l > 0 && t[l-1] == '\r' {
t = t[:l-1]
l--
}
var match bool
if only {
var matches []string
ts := string(t)
if re != nil {
matches = re.FindAllString(ts, -1)
} else {
if ignorecase {
ts = strings.ToLower(ts)
}
ti := 0
tl := len(ts)
matches = make([]string, 10)
for ti != -1 && ti < tl-1 {
ti = strings.Index(ts[ti:], rs)
if ti != -1 {
matches = append(matches, rs)
ti++
}
}
}
match = len(matches) > 0
// skip if not match without invert, or match with invert.
if match == invert {
continue
}
if verbose {
println("found("+enc+"):", path)
}
if list {
matchedfile(path)
did = true
break
}
for _, m := range matches {
countMatch++
if count {
continue
}
if maybeBinary(*(*[]byte)(unsafe.Pointer(&m))) {
errorline(fmt.Sprintf("matched binary file: %s", path))
did = true
break
} else {
if number {
if utf8.ValidString(m) {
matchedline(path, n, m, arg)
} else {
errorline(fmt.Sprintf("matched binary file: %s", path))
did = true
break
}
} else {
if utf8.ValidString(m) {
matchedline("", 0, m, arg)
} else {
errorline(fmt.Sprintf("matched binary file: %s", path))
did = true
break
}
}
}
}
} else {
if re != nil {
if len(re.FindAllIndex(t, 1)) > 0 {
match = true
}
} else {
if ignorecase {
if strings.Index(strings.ToLower(string(t)),
strings.ToLower(rs)) > -1 {
match = true
}
} else {
if strings.Index(string(t), rs) > -1 {
match = true
}
}
}
// skip if not match without invert, or match with invert.
if match == invert {
continue
}
if verbose {
println("found("+enc+"):", path)
}
if list {
matchedfile(path)
did = true
break
}
countMatch++
if count {
did = true
continue
}
if arg.single && !number {
if utf8.Valid(t) {
matchedline("", -1, string(t), arg)
} else {
errorline(fmt.Sprintf("matched binary file: %s", path))
did = true
break
}
} else {
if maybeBinary(t) {
errorline(fmt.Sprintf("matched binary file: %s", path))
did = true
break
} else if utf8.Valid(t) {
if after <= 0 && before <= 0 {
matchedline(path, n, string(t), arg)
} else {
if countMatch > 1 {
os.Stdout.WriteString("---\n")
}
bprev, bnext := next-l-2, next-l-2
lines := make([]string, 10)
for i := 0; i < before && bprev > 0; i++ {
for {
if bprev == 0 || f[bprev-1] == '\n' {
lines = append(lines, string(f[bprev:bnext]))
bnext = bprev - 1
bprev--
break
}
bprev--
}
}
for i := len(lines); i > 0; i-- {
matchedline(path, i-n, lines[i-1], arg)
}
matchedline(path, n, string(t), arg)
lines = make([]string, 10)
aprev, anext := next, next
for i := 0; i < after && anext >= 0 && anext < size; i++ {
for {
if anext == size || f[anext] == '\n' {
lines = append(lines, string(f[aprev:anext]))
aprev = anext + 1
anext++
break
}
anext++
}
}
for i := 0; i < len(lines); i++ {
matchedline(path, -n-i-1, lines[i], arg)
}
}
} else {
errorline(fmt.Sprintf("matched binary file: %s", path))
did = true
break
}
}
}
did = true
}
runtime.GC()
if did || next == -1 {
break
}
}
}
func Grep(arg *GrepArg) {
var f []byte
var path = ""
var ok bool
var stdin *bufio.Reader
if path, ok = arg.input.(string); ok {
if fi, err := os.Stat(path); err == nil && fi.Size() == 0 {
return
}
mf, err := mmap.Open(path)
if err != nil {
errorline(err.Error() + ": " + path)
return
}
defer mf.Close()
f = mf.Data()
doGrep(path, f, arg)
} else if in, ok := arg.input.(io.Reader); ok {
stdin = bufio.NewReader(in)
for {
f, _, err := stdin.ReadLine()
doGrep("stdin", f, arg)
if err != nil {
break
}
}
}
}
func GoGrep(ch chan *GrepArg, done chan int) {
for {
arg := <-ch
if arg == nil {
break
}
Grep(arg)
}
done <- 1
}
func usage(simple bool) {
fmt.Fprintln(os.Stderr, "Usage: jvgrep [OPTION] [PATTERN] [FILE]...")
if simple {
fmt.Fprintln(os.Stderr, "Try `jvgrep --help' for more information.")
} else {
fmt.Fprintf(os.Stderr, `Version %s
Regexp selection and interpretation:
-F : PATTERN is a set of newline-separated fixed strings
-G : PATTERN is a basic regular expression (BRE)
-P : PATTERN is a Perl regular expression (ERE)
Miscellaneous:
-S : verbose messages
-V : print version information and exit
Output control:
-8 : show result as utf8 text
-R : search files recursively
--enc encodings : encodings: comma separated
--exclude regexp : exclude files: specify as regexp
(default: %s)
--no-color : do not print colors
--color [=WHEN] : always/never/auto
-c : count matches
-r : print relative path
-f file : obtain pattern file
-i : ignore case
-I : ignore binary files
-l : print only names of FILEs containing matches
-n : print line number with output lines
-o : show only the part of a line matching PATTERN
-v : select non-matching lines
-z : a data line ends in 0 byte, not newline
-Z : print 0 byte after FILE name
Experimental feature:
--findasync : find asynchronously
Context control:
-B : print NUM lines of leading context
-A : print NUM lines of trailing context
`, version, excludeDefaults)
fmt.Fprintln(os.Stderr, " Supported Encodings:")
for _, enc := range encodings {
if enc != "" {
fmt.Fprintln(os.Stderr, " "+enc)
}
}
}
os.Exit(2)
}
func main() {
var args []string
argv := os.Args
argc := len(argv)
for n := 1; n < argc; n++ {
if len(argv[n]) > 1 && argv[n][0] == '-' && argv[n][1] != '-' {
switch argv[n][1] {
case 'A':
if n < argc-1 {
after, _ = strconv.Atoi(argv[n+1])
n++
continue
}
case 'B':
if n < argc-1 {
before, _ = strconv.Atoi(argv[n+1])
n++
continue
}
case '8':
utf8out = true
printbytes = printbytes_utf8
case 'F':
fixed = true
case 'R':
recursive = true
case 'S':
verbose = true
case 'c':
count = true
case 'r':
fullpath = false
case 'i':
ignorecase = true
case 'I':
ignorebinary = true
case 'l':
list = true
case 'n':
number = true
case 'P':
perl = true
case 'G':
basic = true
case 'v':
invert = true
case 'o':
only = true
case 'f':
if n < argc-1 {
infile = argv[n+1]
n++
continue
}
case 'z':
zeroData = true
printline = printline_zero
case 'Z':
zeroFile = true
case 'V':
fmt.Fprintf(os.Stdout, "%s\n", version)
os.Exit(0)
default:
usage(true)
}
if len(argv[n]) > 2 {
argv[n] = "-" + argv[n][2:]
n--
}
} else if len(argv[n]) > 1 && argv[n][0] == '-' && argv[n][1] == '-' {
name := argv[n][2:]
switch {
case strings.HasPrefix(name, "enc="):
encs = name[4:]
case name == "enc" && n < argc-1:
encs = argv[n+1]
n++
case strings.HasPrefix(name, "exclude="):
exclude = name[8:]
case name == "exclude" && n < argc-1:
exclude = argv[n+1]
n++
case strings.HasPrefix(name, "color="):
color = name[6:]
case name == "no-color":
color = "never"
case name == "color" && n < argc-1:
color = argv[n+1]
n++
case strings.HasPrefix(name, "separator="):
separator = name[10:]
case name == "separator":
separator = argv[n+1]
n++
case name == "null":
zeroFile = true
case name == "null-data":
zeroData = true
case name == "help":
usage(false)
case name == "findasync":
walk = walkAsync
default:
usage(true)
}
} else {
args = append(args, argv[n])
}
}
if len(args) == 0 {
usage(true)
}
var err error
var pattern interface{}
if encs != "" {
encodings = strings.Split(encs, ",")
} else {
enc_env := os.Getenv("JVGREP_ENCODINGS")
if enc_env != "" {
encodings = strings.Split(enc_env, ",")
}
}
out_enc := os.Getenv("JVGREP_OUTPUT_ENCODING")
if out_enc != "" {
ee, _ := charset.Lookup(out_enc)
if ee == nil {
errorline(fmt.Sprintf("unknown encoding: %s", out_enc))
os.Exit(1)
}
oc = transform.NewWriter(stdout, ee.NewEncoder())
if !utf8out {
printbytes = printbytes_outc
}
}
instr := ""
argindex := 0
if len(infile) > 0 {
b, err := ioutil.ReadFile(infile)
if err != nil {
errorline(err.Error())
os.Exit(1)
}
instr = strings.TrimSpace(string(b))
} else {
instr = args[0]
argindex = 1
}
if fixed {
pattern = instr
} else if perl {
re, err := syntax.Parse(instr, syntax.Perl)
if err != nil {
errorline(err.Error())
os.Exit(1)
}
rec, err := syntax.Compile(re)
if err != nil {
errorline(err.Error())
os.Exit(1)
}
instr = rec.String()
if ignorecase {
instr = "(?i:" + instr + ")"
}
if isLiteralRegexp(instr, syntax.Perl) {
if verbose {
println("pattern treated as literal:", instr)
}
pattern = instr
} else {
pattern, err = regexp.Compile(instr)
if err != nil {
errorline(err.Error())
os.Exit(1)
}
}
} else {
if ignorecase {
instr = "(?i:" + instr + ")"
}
if isLiteralRegexp(instr, syntax.POSIX) {
if verbose {
println("pattern treated as literal:", instr)
}
pattern = instr
} else {
pattern, err = regexp.Compile(instr)
if err != nil {
errorline(err.Error())
os.Exit(1)
}
}
}
if exclude == "" {
exclude = os.Getenv("JVGREP_EXCLUDE")
}
if exclude == "" {
exclude = excludeDefaults
}
ere, err := regexp.Compile(exclude)
if err != nil {
errorline(err.Error())
os.Exit(1)
}
atty := false
if color == "" {
color = os.Getenv("JVGREP_COLOR")
}
if color == "" || color == "auto" {
atty = isatty.IsTerminal(os.Stdout.Fd())
} else if color == "always" {
atty = true
} else if color == "never" {
atty = false
} else {
usage(true)
}
if atty {
sc := make(chan os.Signal, 10)
signal.Notify(sc, syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP)
go func() {
for _ = range sc {
printstr(RESET)
os.Exit(0)
}
}()
}
if len(args) == 1 && argindex != 0 {
Grep(&GrepArg{
pattern: pattern,
input: os.Stdin,
single: true,
atty: atty,
})
return
}
envre := regexp.MustCompile(`^(\$[a-zA-Z][a-zA-Z0-9_]+|\$\([a-zA-Z][a-zA-Z0-9_]+\))$`)
globmask := ""
ch := make(chan *GrepArg, 10)
done := make(chan int)
go GoGrep(ch, done)
nargs := len(args[argindex:])
for _, arg := range args[argindex:] {
globmask = ""
root := ""
arg = strings.Trim(arg, `"`)
slashed := filepath.ToSlash(arg)
volume := filepath.VolumeName(slashed)
if volume != "" {
slashed = slashed[len(volume):]
}
for n, i := range strings.Split(slashed, "/") {
if root == "" && strings.Index(i, "*") != -1 {
if globmask == "" {
root = "."
} else {
root = filepath.ToSlash(globmask)
}
}
if n == 0 && i == "~" {
if runtime.GOOS == "windows" {
i = os.Getenv("USERPROFILE")
} else {
i = os.Getenv("HOME")
}
}
if envre.MatchString(i) {
i = strings.Trim(strings.Trim(os.Getenv(i[1:]), "()"), `"`)
}
globmask = filepath.Join(globmask, i)
if n == 0 {
if runtime.GOOS == "windows" && filepath.VolumeName(i) != "" {
globmask = i + "/"
} else if len(globmask) == 0 {
globmask = "/"
}
}
}
if volume != "" {
root = filepath.Join(volume, root)
globmask = filepath.Join(volume, globmask)
}
if root == "" {
path, _ := filepath.Abs(arg)
fi, err := os.Stat(path)
if err != nil {
errorline(fmt.Sprintf("jvgrep: %s: No such file or directory", arg))
os.Exit(1)
}
if !fi.IsDir() {
if verbose {
println("search:", path)
}
ch <- &GrepArg{
pattern: pattern,
input: path,
single: nargs == 1,
atty: atty,
}
continue
} else {
root = path
if fi.IsDir() {
globmask = "**/*"
} else {
globmask = "**/" + globmask
}
}
}
if globmask == "" {
globmask = "."
}
globmask = filepath.ToSlash(filepath.Clean(globmask))
if recursive {
if strings.Index(globmask, "/") > -1 {
globmask += "/"
} else {
globmask = "**/" + globmask
}
}
cc := []rune(globmask)
dirmask := ""
filemask := ""
for i := 0; i < len(cc); i++ {
if cc[i] == '*' {
if i < len(cc)-2 && cc[i+1] == '*' && cc[i+2] == '/' {
filemask += "(.*/)?"
dirmask = filemask
i += 2
} else {
filemask += "[^/]*"
}
} else {
c := cc[i]
if c == '/' || ('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || 255 < c {
filemask += string(c)
} else {
filemask += fmt.Sprintf("[\\x%x]", c)
}
if c == '/' && dirmask == "" && strings.Index(filemask, "*") != -1 {
dirmask = filemask
}
}
}
if dirmask == "" {
dirmask = filemask
}
if len(filemask) > 0 && filemask[len(filemask)-1] == '/' {
if root == "" {
root = filemask
}
filemask += "[^/]*"
}
if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
dirmask = "(?i:" + dirmask + ")"
filemask = "(?i:" + filemask + ")"
}
dre := regexp.MustCompile("^" + dirmask)
fre := regexp.MustCompile("^" + filemask + "$")
root = filepath.Clean(root)
if verbose {
println("dirmask:", dirmask)