-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfastwalk_test.go
1500 lines (1397 loc) · 37.2 KB
/
fastwalk_test.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 fastwalk_test
import (
"bytes"
"crypto/md5"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"math"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"github.com/charlievieth/fastwalk"
)
func formatFileModes(m map[string]os.FileMode) string {
var keys []string
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
var buf bytes.Buffer
for _, k := range keys {
fmt.Fprintf(&buf, "%-20s: %v\n", k, m[k])
}
return buf.String()
}
func writeFile(filename string, data interface{}, perm os.FileMode) error {
if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
return err
}
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
switch v := data.(type) {
case []byte:
_, err = f.Write(v)
case string:
_, err = f.WriteString(v)
case io.Reader:
_, err = io.Copy(f, v)
default:
f.Close()
return &os.PathError{Op: "WriteFile", Path: filename,
Err: fmt.Errorf("invalid data type: %T", data)}
}
if err1 := f.Close(); err1 != nil && err == nil {
err = err1
}
return err
}
func symlink(t testing.TB, oldname, newname string) error {
err := os.Symlink(oldname, newname)
if err != nil {
if writeErr := os.WriteFile(newname, []byte(newname), 0644); writeErr == nil {
// Couldn't create symlink, but could write the file.
// Probably this filesystem doesn't support symlinks.
// (Perhaps we are on an older Windows and not running as administrator.)
t.Skipf("skipping because symlinks appear to be unsupported: %v", err)
}
}
return err
}
func cleanupOrLogTempDir(t *testing.T, tempdir string) {
if e := recover(); e != nil {
t.Log("TMPDIR:", filepath.ToSlash(tempdir))
t.Fatal(e)
}
if t.Failed() {
t.Log("TMPDIR:", filepath.ToSlash(tempdir))
} else {
os.RemoveAll(tempdir)
}
}
func testCreateFiles(t *testing.T, tempdir string, files map[string]string) {
symlinks := map[string]string{}
for path, contents := range files {
file := filepath.Join(tempdir, "/src", path)
if err := os.MkdirAll(filepath.Dir(file), 0755); err != nil {
t.Fatal(err)
}
var err error
if strings.HasPrefix(contents, "LINK:") {
symlinks[file] = filepath.FromSlash(strings.TrimPrefix(contents, "LINK:"))
} else {
err = os.WriteFile(file, []byte(contents), 0644)
}
if err != nil {
t.Fatal(err)
}
}
// Create symlinks after all other files. Otherwise, directory symlinks on
// Windows are unusable (see https://golang.org/issue/39183).
for file, dst := range symlinks {
if err := symlink(t, dst, file); err != nil {
t.Fatal(err)
}
}
}
func testFastWalkConf(t *testing.T, conf *fastwalk.Config, files map[string]string,
callback fs.WalkDirFunc, want map[string]os.FileMode) {
tempdir, err := os.MkdirTemp("", "test-fast-walk")
if err != nil {
t.Fatal(err)
}
defer cleanupOrLogTempDir(t, tempdir)
testCreateFiles(t, tempdir, files)
got := map[string]os.FileMode{}
var mu sync.Mutex
err = fastwalk.Walk(conf, tempdir, func(path string, de fs.DirEntry, err error) error {
if de == nil {
t.Errorf("nil fs.DirEntry on %q", path)
return nil
}
mu.Lock()
defer mu.Unlock()
if !strings.HasPrefix(path, tempdir) {
t.Errorf("bogus prefix on %q, expect %q", path, tempdir)
}
key := filepath.ToSlash(strings.TrimPrefix(path, tempdir))
if old, dup := got[key]; dup {
t.Errorf("callback called twice for key %q: %v -> %v", key, old, de.Type())
}
got[key] = de.Type()
return callback(path, de, err)
})
if err != nil {
t.Fatalf("callback returned: %v", err)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("walk mismatch.\n got:\n%v\nwant:\n%v", formatFileModes(got), formatFileModes(want))
diffFileModes(t, got, want)
}
}
func testFastWalk(t *testing.T, files map[string]string,
callback fs.WalkDirFunc, want map[string]os.FileMode) {
testFastWalkConf(t, nil, files, callback, want)
}
func requireNoError(t testing.TB, err error) {
t.Helper()
if err != nil {
t.Error("WalkDirFunc called with error:", err)
panic(err)
}
}
func TestFastWalk_Basic(t *testing.T) {
testFastWalk(t, map[string]string{
"foo/foo.go": "one",
"bar/bar.go": "two",
"skip/skip.go": "skip",
},
func(path string, typ fs.DirEntry, err error) error {
requireNoError(t, err)
return nil
},
map[string]os.FileMode{
"": os.ModeDir,
"/src": os.ModeDir,
"/src/bar": os.ModeDir,
"/src/bar/bar.go": 0,
"/src/foo": os.ModeDir,
"/src/foo/foo.go": 0,
"/src/skip": os.ModeDir,
"/src/skip/skip.go": 0,
})
}
func maxFileNameLength(t testing.TB) int {
tmp := t.TempDir()
long := strings.Repeat("a", 8192)
// Returns if n is an invalid file name length
invalidLength := func(n int) bool {
path := filepath.Join(tmp, long[:n])
err := os.WriteFile(path, []byte("1"), 0644)
if err == nil {
os.Remove(path)
}
return err != nil
}
// Use a binary search to find the max filename length (+1)
n := sort.Search(8192, invalidLength)
if n <= 1 {
t.Fatal("Failed to find the max filename length:", n)
}
max := n - 1
if invalidLength(max) {
t.Fatal("Failed to find the max filename length:", n)
}
return max
}
// This test identified a "checkptr: converted pointer straddles multiple allocations"
// error on darwin when getdirentries64 was used with the race-detector enabled.
func TestFastWalk_LongFileName(t *testing.T) {
// Test is slow since we need to find the longest allowed filename
t.Parallel()
maxNameLen := maxFileNameLength(t)
if maxNameLen > 255 {
maxNameLen = 255
}
want := map[string]os.FileMode{
"": os.ModeDir,
"/src": os.ModeDir,
}
files := make(map[string]string)
// This triggers with only one sub-directory but use 2 just to be sure.
for r := 'a'; r <= 'b'; r++ {
s := string(r)
name := s + "/" + strings.Repeat(s, maxNameLen)
for i := len("_/") + 1; i <= len(name); i++ {
files[name[:i]] = "1"
want["/src/"+name[:i]] = 0
}
want["/src/"+s] = os.ModeDir
}
testFastWalk(t, files,
func(path string, typ fs.DirEntry, err error) error {
requireNoError(t, err)
return nil
},
want,
)
}
func maxPathLength(t testing.TB) (root string, pathMax int) {
tmp, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
switch len(tmp) % 4 {
case 0:
case 1:
// Can't just add 1 "/" so add 5 ("/aaaa")
tmp = filepath.Join(tmp, "/aaaa")
case 2:
tmp = filepath.Join(tmp, "/a")
case 3:
tmp = filepath.Join(tmp, "/aa")
}
base := tmp
// Returns if n is an invalid file name length
var longestPath string
invalidPathLength := func(n int) bool {
m := n - len(tmp)
if m <= 0 {
return false
}
var w strings.Builder
w.Grow(n + 1)
w.WriteString(base)
elem := "/" + strings.Repeat("a", 127) // path element
for w.Len() < n-len(elem) {
w.WriteString(elem)
}
for w.Len() < n {
w.WriteByte('b')
}
path := w.String()
if len(path) != n {
t.Fatalf("invalid PATH length: %d want: %d", len(path), n)
}
err := os.MkdirAll(path, 0755)
if err == nil {
// Don't remove directories on success since it's slow
// and we'll use them again as the path length increases.
longestPath = path
}
return err != nil
}
// Use a binary search to find the max path length (+1)
n := sort.Search(16*1024, invalidPathLength)
if n <= 1 {
t.Fatal("Failed to find the max path length:", n)
}
pathMax = n - 1
if invalidPathLength(pathMax) {
t.Fatal("Failed to find the max path length:", n)
}
// Make sure longestPath exists
if _, err := os.Stat(longestPath); err != nil {
t.Fatalf("Invalid longest path (%q): %v", longestPath, err)
}
// Create directories under the tmp/root dir: /{TMP}/{b..z}/{LONGEST_PATH}
root = filepath.Dir(tmp)
name := filepath.Base(tmp)
long := strings.TrimPrefix(longestPath, tmp)
end := 'z'
if testing.Short() {
end = 'e'
}
for r := 'b'; r <= end; r++ {
newBase := strings.Repeat(string(r), len(name))
if err := os.MkdirAll(filepath.Join(root, newBase, long), 0755); err != nil {
t.Fatal(err)
}
}
return root, pathMax
}
// Test that we can handle PATH_MAX. This is mostly for the Unix tests
// where we pass a buffer to ReadDirect (often getdents64(2)).
func TestFastWalk_LongPath(t *testing.T) {
// Test is slow since we need to find the longest allowed file path
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("test not needed on Windows")
}
root, pathMax := maxPathLength(t)
t.Log("PATH_MAX:", pathMax)
var want []string
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
want = append(want, filepath.Clean(path))
return nil
})
if err != nil {
t.Fatal(err)
}
var got []string
var mu sync.Mutex
err = fastwalk.Walk(nil, root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
mu.Lock()
got = append(got, filepath.Clean(path))
mu.Unlock()
return nil
})
if err != nil {
t.Fatal(err)
}
sort.Strings(want)
sort.Strings(got)
if !reflect.DeepEqual(want, got) {
// Don't print the delta here since it might be very large. Instead
// write it to two temp files in a directory that is not removed on
// test exit so that the user can compare them themselves.
tempdir, err := os.MkdirTemp("", "fastwalk-test-*")
if err != nil {
t.Error(err)
}
if err := writeFile(tempdir+"/want.txt", strings.Join(want, "\n"), 0666); err != nil {
t.Error(err)
}
if err := writeFile(tempdir+"/got.txt", strings.Join(got, "\n"), 0666); err != nil {
t.Error(err)
}
t.Fatalf("Output does not match: see the files in: %q", tempdir)
}
}
func TestFastWalk_WindowsRootPaths(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("test only supported on Windows")
}
sameFile := func(t *testing.T, name1, name2 string) bool {
fi1, err := os.Stat(name1)
if err != nil {
t.Fatal(err)
}
fi2, err := os.Stat(name2)
if err != nil {
t.Fatal(err)
}
return os.SameFile(fi1, fi2)
}
walk := func(t *testing.T, root string) map[string]fs.DirEntry {
var mu sync.Mutex
seen := make(map[string]fs.DirEntry)
errStop := errors.New("errStop")
fn := func(path string, de fs.DirEntry, err error) error {
if err != nil {
return err
}
mu.Lock()
seen[path] = de
mu.Unlock()
if path != root && de.IsDir() {
return fs.SkipDir
}
return nil
}
err := fastwalk.Walk(nil, root, fastwalk.IgnorePermissionErrors(fn))
if err != nil && err != errStop {
t.Fatal(err)
}
if len(seen) <= 1 {
// If we are a child of the root directory we should have visited at
// least two entries: the root itself and a directory that leads to,
// or is, our current working directory.
t.Fatalf("empty directory: %s", root)
}
return seen
}
pwd, err := filepath.Abs(".")
if err != nil {
t.Fatal(err)
}
vol := filepath.VolumeName(pwd)
if !regexp.MustCompile(`^[A-Za-z]:$`).MatchString(vol) {
// Ignore UNC names and other weird Windows paths to keep this simple.
t.Skipf("unsupported volume name: %s for path: %s", vol, pwd)
}
if !sameFile(t, pwd, vol) {
t.Skipf("skipping %s and %s should be considered the same file", pwd, vol)
}
// Test that walking the disk root ("C:\") actually walks the disk root.
// Previously, there was a bug where the path "C:\" was transformed to "C:"
// before walking which caused fastwalk to walk the current directory.
//
// https://github.com/charlievieth/fastwalk/issues/37
t.Run("FullyQualified", func(t *testing.T) {
root := vol + `\`
if sameFile(t, pwd, root) {
t.Skipf("the current working directory (%s) is the disk root: %s", pwd, root)
}
seen := walk(t, root)
// Make sure we don't append an extraneous slash to the root ("C:\" => "C:\\a").
for path := range seen {
rest := strings.TrimPrefix(path, vol)
if strings.Contains(rest, `\\`) {
t.Errorf(`path contains multiple consecutive slashes after volume (%s): "%s"`,
vol, path)
}
if s := filepath.Clean(path); s != path {
t.Errorf(`filepath.Clean("%s") == "%s"`, path, s)
}
}
// Make sure we didn't walk the current directory. This will happen if
// the root argument to Walk is a drive letter ("C:\") but we strip off
// the trailing slash ("C:\" => "C:") since this makes the path relative
// to the current directory on drive "C".
//
// See: https://github.com/charlievieth/fastwalk/issues/37
//
// Docs: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#fully-qualified-vs-relative-paths
for path, de := range seen {
if path == root {
// Ignore root since filepath.Base("C:\") == "\" and "C:\" and "\"
// are equivalent.
continue
}
fi1, err := de.Info()
if err != nil {
if os.IsNotExist(err) || os.IsPermission(err) {
continue
}
t.Fatal(err)
}
name := filepath.Base(path)
fi2, err := os.Lstat(name)
if err != nil {
continue
}
if os.SameFile(fi1, fi2) {
t.Errorf("Walking root (%s) returned entries for the current working "+
"directory (%s): file %s is the same as %s", root, pwd, path, name)
}
}
// Add file base name mappings
for _, de := range seen {
seen[de.Name()] = de
}
// Make sure we read some files from the disk root.
des, err := os.ReadDir(root)
if err != nil {
t.Fatal(err)
}
if len(des) == 0 {
t.Fatalf("Disk root %s contains no files!", root)
}
same := 0
for _, d2 := range des {
d1 := seen[d2.Name()]
if d1 == nil {
continue
}
fi1, err := d1.Info()
if err != nil {
t.Log(err)
continue
}
fi2, err := d2.Info()
if err != nil {
t.Log(err)
continue
}
if os.SameFile(fi1, fi2) {
same++
}
}
// TODO: Expect to see N% of files and use
// a more descriptive error message
if same == 0 {
t.Fatalf(`Error failed to walk dist root: "%s"`, root)
}
})
// Test that paths like "C:" are treated as a relative path.
t.Run("Relative", func(t *testing.T) {
seen := walk(t, vol)
// Make sure we don't append an extraneous slash to the root ("C:\" => "C:\\a").
for path := range seen {
rest := strings.TrimPrefix(path, vol)
if strings.Contains(rest, `\\`) {
t.Errorf(`path contains multiple consecutive slashes after volume (%s): "%s"`,
vol, path)
}
if path == vol {
continue // Clean("C:") => "C:."
}
if s := filepath.Clean(path); s != path {
t.Errorf(`filepath.Clean("%s") == "%s"`, path, s)
}
}
// Make sure we walk the current directory.
for path, de := range seen {
if path == vol {
// Ignore the volume since filepath.Base("C:") == "\" and "C:" and "\"
// are not equivalent.
continue
}
fi1, err := de.Info()
if err != nil {
t.Fatal(err)
}
name := filepath.Base(path)
fi2, err := os.Lstat(name)
if err != nil {
// NB: This test will fail if this file is removed while it's
// running. There are workarounds for this, but for now it's
// simpler to just error if that happens.
t.Fatal(err)
}
if !os.SameFile(fi1, fi2) {
t.Errorf("Expected files (%s) and (%s) to be the same", path, name)
}
}
})
}
func TestFastWalk_Symlink(t *testing.T) {
testFastWalk(t, map[string]string{
"foo/foo.go": "one",
"bar/bar.go": "LINK:../foo/foo.go",
"symdir": "LINK:foo",
"broken/broken.go": "LINK:../nonexistent",
},
func(path string, typ fs.DirEntry, err error) error {
requireNoError(t, err)
return nil
},
map[string]os.FileMode{
"": os.ModeDir,
"/src": os.ModeDir,
"/src/bar": os.ModeDir,
"/src/bar/bar.go": os.ModeSymlink,
"/src/foo": os.ModeDir,
"/src/foo/foo.go": 0,
"/src/symdir": os.ModeSymlink,
"/src/broken": os.ModeDir,
"/src/broken/broken.go": os.ModeSymlink,
})
}
// Test that the fs.DirEntry passed to WalkFunc is always a fastwalk.DirEntry.
func TestFastWalk_DirEntryType(t *testing.T) {
testFastWalk(t, map[string]string{
"foo/foo.go": "one",
"bar/bar.go": "LINK:../foo/foo.go",
"symdir": "LINK:foo",
"broken/broken.go": "LINK:../nonexistent",
},
func(path string, de fs.DirEntry, err error) error {
requireNoError(t, err)
if _, ok := de.(fastwalk.DirEntry); !ok {
t.Errorf("%q: not a fastwalk.DirEntry: %T", path, de)
}
if de.Type() != de.Type().Type() {
t.Errorf("%s: type mismatch got: %q want: %q",
path, de.Type(), de.Type().Type())
}
return nil
},
map[string]os.FileMode{
"": os.ModeDir,
"/src": os.ModeDir,
"/src/bar": os.ModeDir,
"/src/bar/bar.go": os.ModeSymlink,
"/src/foo": os.ModeDir,
"/src/foo/foo.go": 0,
"/src/symdir": os.ModeSymlink,
"/src/broken": os.ModeDir,
"/src/broken/broken.go": os.ModeSymlink,
})
}
func TestFastWalk_SkipDir(t *testing.T) {
test := func(t *testing.T, mode fastwalk.SortMode) {
conf := fastwalk.DefaultConfig.Copy()
conf.Sort = mode
testFastWalkConf(t, conf, map[string]string{
"foo/foo.go": "one",
"bar/bar.go": "two",
"skip/skip.go": "skip",
},
func(path string, de fs.DirEntry, err error) error {
requireNoError(t, err)
typ := de.Type().Type()
if typ == os.ModeDir && strings.HasSuffix(path, "skip") {
return filepath.SkipDir
}
return nil
},
map[string]os.FileMode{
"": os.ModeDir,
"/src": os.ModeDir,
"/src/bar": os.ModeDir,
"/src/bar/bar.go": 0,
"/src/foo": os.ModeDir,
"/src/foo/foo.go": 0,
"/src/skip": os.ModeDir,
})
}
// Test that sorting respects fastwalk.ErrSkipFiles
for _, mode := range []fastwalk.SortMode{
fastwalk.SortNone,
fastwalk.SortLexical,
fastwalk.SortDirsFirst,
fastwalk.SortFilesFirst,
} {
t.Run(mode.String(), func(t *testing.T) {
test(t, mode)
})
}
}
func TestFastWalk_SkipFiles(t *testing.T) {
mapKeys := func(m map[string]os.FileMode) []string {
a := make([]string, 0, len(m))
for k := range m {
a = append(a, k)
}
return a
}
test := func(t *testing.T, mode fastwalk.SortMode) {
// Directory iteration order is undefined, so there's no way to know
// which file to expect until the walk happens. Rather than mess
// with the test infrastructure, just mutate want.
want := map[string]os.FileMode{
"": os.ModeDir,
"/src": os.ModeDir,
"/src/zzz": os.ModeDir,
"/src/zzz/c.go": 0,
}
conf := fastwalk.DefaultConfig.Copy()
conf.Sort = mode
var mu sync.Mutex
testFastWalkConf(t, conf, map[string]string{
"a_skipfiles.go": "a",
"b_skipfiles.go": "b",
"zzz/c.go": "c",
},
func(path string, _ fs.DirEntry, err error) error {
requireNoError(t, err)
if strings.HasSuffix(path, "_skipfiles.go") {
mu.Lock()
defer mu.Unlock()
want["/src/"+filepath.Base(path)] = 0
return fastwalk.ErrSkipFiles
}
return nil
},
want)
if len(want) != 5 {
t.Errorf("invalid number of files visited: wanted 5, got %v (%q)",
len(want), mapKeys(want))
}
}
// Test that sorting respects fastwalk.ErrSkipFiles
for _, mode := range []fastwalk.SortMode{
fastwalk.SortNone,
fastwalk.SortLexical,
fastwalk.SortDirsFirst,
fastwalk.SortFilesFirst,
} {
t.Run(mode.String(), func(t *testing.T) {
test(t, mode)
})
}
}
func TestFastWalk_TraverseSymlink(t *testing.T) {
testFastWalk(t, map[string]string{
"foo/foo.go": "one",
"bar/bar.go": "two",
"symdir": "LINK:foo",
},
func(path string, de fs.DirEntry, err error) error {
requireNoError(t, err)
typ := de.Type().Type()
if typ == os.ModeSymlink {
return fastwalk.ErrTraverseLink
}
return nil
},
map[string]os.FileMode{
"": os.ModeDir,
"/src": os.ModeDir,
"/src/bar": os.ModeDir,
"/src/bar/bar.go": 0,
"/src/foo": os.ModeDir,
"/src/foo/foo.go": 0,
"/src/symdir": os.ModeSymlink,
"/src/symdir/foo.go": 0,
})
}
func TestFastWalk_Follow(t *testing.T) {
subTests := []struct {
Name string
OnLink func(path string, d fs.DirEntry) error
}{
// Test that the walk func does *not* need to return
// ErrTraverseLink for links to be followed.
{
Name: "Default",
OnLink: func(path string, d fs.DirEntry) error { return nil },
},
// Test that returning ErrTraverseLink does not interfere
// with the Follow logic.
{
Name: "ErrTraverseLink",
OnLink: func(path string, d fs.DirEntry) error {
if d.Type()&os.ModeSymlink != 0 {
if fi, err := fastwalk.StatDirEntry(path, d); err == nil && fi.IsDir() {
return fastwalk.ErrTraverseLink
}
}
return nil
},
},
}
for _, x := range subTests {
t.Run(x.Name, func(t *testing.T) {
conf := fastwalk.Config{
Follow: true,
}
testFastWalkConf(t, &conf, map[string]string{
"foo/foo.go": "one",
"bar/bar.go": "two",
"foo/symlink": "LINK:foo.go",
"bar/symdir": "LINK:../foo/",
"bar/link1": "LINK:../foo/",
},
func(path string, de fs.DirEntry, err error) error {
requireNoError(t, err)
if err != nil {
return err
}
if de.Type()&os.ModeSymlink != 0 {
return x.OnLink(path, de)
}
return nil
},
map[string]os.FileMode{
"": os.ModeDir,
"/src": os.ModeDir,
"/src/bar": os.ModeDir,
"/src/bar/bar.go": 0,
"/src/bar/link1": os.ModeSymlink,
"/src/bar/link1/foo.go": 0,
"/src/bar/link1/symlink": os.ModeSymlink,
"/src/bar/symdir": os.ModeSymlink,
"/src/bar/symdir/foo.go": 0,
"/src/bar/symdir/symlink": os.ModeSymlink,
"/src/foo": os.ModeDir,
"/src/foo/foo.go": 0,
"/src/foo/symlink": os.ModeSymlink,
})
})
}
}
func TestFastWalk_Follow_SkipDir(t *testing.T) {
conf := fastwalk.Config{
Follow: true,
}
testFastWalkConf(t, &conf, map[string]string{
".dot/baz.go": "one",
"bar/bar.go": "three",
"bar/dot": "LINK:../.dot/",
"bar/symdir": "LINK:../foo/",
"foo/foo.go": "two",
"foo/symlink": "LINK:foo.go",
},
func(path string, de fs.DirEntry, err error) error {
requireNoError(t, err)
if err != nil {
return err
}
if strings.HasPrefix(de.Name(), ".") {
return filepath.SkipDir
}
return nil
},
map[string]os.FileMode{
"": os.ModeDir,
"/src": os.ModeDir,
"/src/.dot": os.ModeDir,
"/src/bar": os.ModeDir,
"/src/bar/bar.go": 0,
"/src/bar/dot": os.ModeSymlink,
"/src/bar/dot/baz.go": 0,
"/src/bar/symdir": os.ModeSymlink,
"/src/bar/symdir/foo.go": 0,
"/src/bar/symdir/symlink": os.ModeSymlink,
"/src/foo": os.ModeDir,
"/src/foo/foo.go": 0,
"/src/foo/symlink": os.ModeSymlink,
})
}
func TestFastWalk_Follow_SymlinkLoop(t *testing.T) {
tempdir, err := os.MkdirTemp("", "fastwalk-test-*")
if err != nil {
t.Fatal(err)
}
defer cleanupOrLogTempDir(t, tempdir)
if err := writeFile(tempdir+"/src/foo.go", "hello", 0644); err != nil {
t.Fatal(err)
}
if err := symlink(t, "../src", tempdir+"/src/loop"); err != nil {
t.Fatal(err)
}
conf := fastwalk.Config{
Follow: true,
}
var walked int32
err = fastwalk.Walk(&conf, tempdir, func(path string, de fs.DirEntry, err error) error {
if err != nil {
return err
}
if n := atomic.AddInt32(&walked, 1); n > 20 {
return fmt.Errorf("symlink loop: %d", n)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
// Test that ErrTraverseLink is ignored when following symlinks
// if it would cause a symlink loop.
func TestFastWalk_Follow_ErrTraverseLink(t *testing.T) {
conf := fastwalk.Config{
Follow: true,
}
testFastWalkConf(t, &conf, map[string]string{
"foo/foo.go": "one",
"bar/bar.go": "two",
"bar/symdir": "LINK:../foo/",
"bar/loop": "LINK:../bar/", // symlink loop
},
func(path string, de fs.DirEntry, err error) error {
requireNoError(t, err)
if err != nil {
return err
}
if de.Type()&os.ModeSymlink != 0 {
if fi, err := fastwalk.StatDirEntry(path, de); err == nil && fi.IsDir() {
return fastwalk.ErrTraverseLink
}
}
return nil
},
map[string]os.FileMode{
"": os.ModeDir,
"/src": os.ModeDir,
"/src/bar": os.ModeDir,
"/src/bar/bar.go": 0,
"/src/bar/loop": os.ModeSymlink,
"/src/bar/symdir": os.ModeSymlink,
"/src/bar/symdir/foo.go": 0,
"/src/foo": os.ModeDir,
"/src/foo/foo.go": 0,
})
}
func TestFastWalk_Error(t *testing.T) {
tmp := t.TempDir()
for _, child := range []string{
"foo/foo.go",
"bar/bar.go",
"skip/skip.go",
} {
if err := writeFile(filepath.Join(tmp, child), child, 0644); err != nil {
t.Fatal(err)
}
}
exp := errors.New("expected")
err := fastwalk.Walk(nil, tmp, func(_ string, _ fs.DirEntry, err error) error {
requireNoError(t, err)
return exp
})
if !errors.Is(err, exp) {
t.Errorf("want error: %#v got: %#v", exp, err)
}
}
func TestFastWalk_ErrNotExist(t *testing.T) {
tmp := t.TempDir()
if err := os.Remove(tmp); err != nil {
t.Fatal(err)
}
err := fastwalk.Walk(nil, tmp, func(_ string, _ fs.DirEntry, err error) error {
return err
})
if !os.IsNotExist(err) {
t.Fatalf("os.IsNotExist(%+v) = false want: true", err)
}
}
func TestFastWalk_ErrPermission(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("test not supported for Windows")
}
tempdir := t.TempDir()
want := map[string]os.FileMode{
"": os.ModeDir,
"/bad": os.ModeDir,
}
for i := 0; i < runtime.NumCPU()*4; i++ {
dir := fmt.Sprintf("/d%03d", i)
name := fmt.Sprintf("%s/f%03d.txt", dir, i)
if err := writeFile(filepath.Join(tempdir, name), "data", 0644); err != nil {
t.Fatal(err)
}
want[name] = 0
want[filepath.Dir(name)] = os.ModeDir
}