-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
1591 lines (1462 loc) · 48.4 KB
/
file.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 fs
import (
"bytes"
"context"
"encoding/gob"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
iofs "io/fs"
"iter"
"path"
"slices"
"strings"
"time"
"github.com/ungerik/go-fs/fsimpl"
)
var (
_ FileReader = File("")
_ fmt.Stringer = File("")
_ gob.GobEncoder = File("")
_ gob.GobDecoder = File("")
)
// InvalidFile is a file with an empty path and thus invalid.
const InvalidFile = File("")
// File is a local file system path or a complete URI.
// It is a string underneath, so string literals can be passed everywhere a File is expected.
// Marshalling functions that use reflection will also work out of the box
// when they detect that File is of kind reflect.String.
// File implements FileReader.
type File string
// FilesFromStrings returns Files for the given fileURIs.
func FilesFromStrings(fileURIs []string) []File {
if len(fileURIs) == 0 {
return nil
}
files := make([]File, len(fileURIs))
for i := range fileURIs {
files[i] = File(fileURIs[i])
}
return files
}
// FileSystem returns the FileSystem of the File.
// Defaults to Local if not a complete URI,
// or Invalid for an empty path.
func (file File) FileSystem() FileSystem {
return GetFileSystem(string(file))
}
// ParseRawURI returns a FileSystem for the passed URI and the path component within that file system.
// Returns the local file system if no other file system could be identified.
func (file File) ParseRawURI() (fs FileSystem, fsPath string) {
return ParseRawURI(string(file))
}
// RawURI rurns the string value of File.
func (file File) RawURI() string {
return string(file)
}
// String returns information about the File and its FileSystem.
// String implements the fmt.Stringer interface.
func (file File) String() string {
return fmt.Sprintf("%s (%s)", string(file), file.FileSystem().Name())
}
// URL of the file
func (file File) URL() string {
fileSystem, path := file.ParseRawURI()
return fileSystem.URL(path)
}
// Path returns the cleaned path of the file.
// It may differ from the string value of File
// because it will be cleaned depending on the FileSystem
func (file File) Path() string {
fileSystem, path := file.ParseRawURI()
return fileSystem.JoinCleanPath(path)
}
// PathWithSlashes returns the cleaned path of the file
// always using the slash '/' as separator.
// It may differ from the string value of File
// because it will be cleaned depending on the FileSystem
func (file File) PathWithSlashes() string {
fileSystem, path := file.ParseRawURI()
path = fileSystem.JoinCleanPath(path)
if sep := fileSystem.Separator(); sep != "/" {
path = strings.Replace(path, sep, "/", -1)
}
return path
}
// LocalPath returns the cleaned local file-system path of the file,
// or an empty string if it is not on the local file system.
func (file File) LocalPath() string {
fileSystem, path := file.ParseRawURI()
if fileSystem != Local {
return ""
}
return fileSystem.JoinCleanPath(path)
}
// MustLocalPath returns the cleaned local file-system path of the file,
// or panics if it is not on the local file system or an empty path.
func (file File) MustLocalPath() string {
if file == "" {
panic("empty file path")
}
localPath := file.LocalPath()
if localPath == "" {
panic(fmt.Sprintf("not a local file-system path: %q", string(file)))
}
return localPath
}
// Name returns the name part of the file path,
// which is usually the string after the last path Separator.
func (file File) Name() string {
_, name := file.DirAndName()
return name
}
// Dir returns the parent directory of the File.
func (file File) Dir() File {
dir, _ := file.DirAndName()
return dir
}
// DirAndName returns the parent directory of filePath and the name with that directory of the last filePath element.
// If filePath is the root of the file systeme, then an empty string will be returned for name.
func (file File) DirAndName() (dir File, name string) {
fileSystem, path := file.ParseRawURI()
dirPath, name := fileSystem.SplitDirAndName(path)
return fileSystem.JoinCleanFile(dirPath), name
}
// VolumeName returns the name of the volume at the beginning of the file path,
// or an empty string if the path has no volume.
// A volume is for example "C:" on Windows
func (file File) VolumeName() string {
fileSystem, path := file.ParseRawURI()
if fs, ok := fileSystem.(VolumeNameFileSystem); ok {
return fs.VolumeName(path)
}
return ""
}
// Ext returns the extension of file name including the point, or an empty string.
//
// Example:
//
// File("image.png").Ext() == ".png"
// File("dir.with.ext/file").Ext() == ""
// File("dir.with.ext/file.ext").Ext() == ".ext"
func (file File) Ext() string {
return fsimpl.Ext(string(file), file.FileSystem().Separator())
}
// ExtLower returns the lower case extension of file name including the point, or an empty string.
// Example: File("Image.PNG").ExtLower() == ".png"
func (file File) ExtLower() string {
return strings.ToLower(file.Ext())
}
// TrimExt returns a File with a path where the extension is removed.
// Note that this does not rename an actual existing file.
func (file File) TrimExt() File {
return File(fsimpl.TrimExt(string(file), file.FileSystem().Separator()))
}
// Join returns a new File with pathParts cleaned and joined to the current File's URI.
// Every element of pathParts is a subsequent directory or file
// that will be appended to the File URI with a path separator.
// The resulting URI path will be cleaned, removing relative directory names like "..".
func (file File) Join(pathParts ...string) File {
if len(pathParts) == 0 {
return file
}
fileSystem, path := file.ParseRawURI()
if path != "" {
pathParts = append([]string{path}, pathParts...)
}
return fileSystem.JoinCleanFile(pathParts...)
}
// Joinf returns a new File with smf.Sprintf(format, args...) cleaned and joined to the current File's URI.
// The resulting URI path will be cleaned, removing relative directory names like "..".
func (file File) Joinf(format string, args ...any) File {
fileSystem, path := file.ParseRawURI()
return fileSystem.JoinCleanFile(path, fmt.Sprintf(format, args...))
}
// IsReadable returns if the file exists and is readable.
func (file File) IsReadable() bool {
if file == "" {
return false
}
fileSystem, filePath := file.ParseRawURI()
if readFS, _ := fileSystem.ReadableWritable(); !readFS {
return false
}
info, err := fileSystem.Stat(filePath)
if err != nil {
return false
}
return (info.Mode().IsDir() || info.Mode().IsRegular()) && (info.Mode()&0400 != 0)
}
// IsWriteable returns if the file exists and is writeable
// or in case it doesn't exist,
// if the parent directory exists and is writeable.
func (file File) IsWriteable() bool {
if file == "" {
return false
}
fileSystem, pathFile := file.ParseRawURI()
if _, writeFS := fileSystem.ReadableWritable(); !writeFS {
return false
}
info, err := fileSystem.Stat(pathFile)
if err == nil {
return info.Mode().IsRegular() && (info.Mode()&0200 != 0)
}
// File does not exist, check if parent directory is writeable
parentDir, _ := fileSystem.SplitDirAndName(pathFile)
info, err = fileSystem.Stat(parentDir)
if err != nil {
return false // Parent directory does not exist
}
return info.Mode().IsDir() && (info.Mode()&0200 != 0)
}
// Stat returns a standard library io/fs.FileInfo describing the file.
func (file File) Stat() (iofs.FileInfo, error) {
if file == "" {
return nil, ErrEmptyPath
}
fileSystem, path := file.ParseRawURI()
return fileSystem.Stat(path)
}
// Info returns FileInfo.
//
// Use File.Stat to get a standard library io/fs.FileInfo.
func (file File) Info() *FileInfo {
fileSystem, path := file.ParseRawURI()
info, err := fileSystem.Stat(path)
if err != nil {
return NewNonExistingFileInfo(file)
}
return NewFileInfo(file, info, fileSystem.IsHidden(path))
}
// InfoWithContentHash returns a FileInfo, but in contrast to Stat
// it always fills the ContentHash field.
// func (file File) InfoWithContentHash() (FileInfo, error) {
// return file.InfoWithContentHashContext(context.Background())
// }
// InfoWithContentHashContext returns a FileInfo, but in contrast to Stat
// it always fills the ContentHash field.
// func (file File) InfoWithContentHashContext(ctx context.Context) (FileInfo, error) {
// if file == "" {
// return FileInfo{}, ErrEmptyPath
// }
// info := file.Info()
// if !info.IsDir && info.ContentHash == "" {
// reader, err := file.OpenReader()
// if err != nil {
// return FileInfo{}, err
// }
// defer reader.Close()
// info.ContentHash, err = DefaultContentHash(ctx, reader)
// if err != nil {
// return FileInfo{}, err
// }
// }
// return info, nil
// }
// Exists returns a file or directory with the path of File exists.
func (file File) Exists() bool {
fileSystem, path := file.ParseRawURI()
if fs, ok := fileSystem.(ExistsFileSystem); ok {
return fs.Exists(path)
}
_, err := fileSystem.Stat(path)
return err == nil
}
// CheckExists return an ErrDoesNotExist error
// if the file does not exist or ErrEmptyPath
// if the file path is empty.
func (file File) CheckExists() error {
if file == "" {
return ErrEmptyPath
}
if !file.Exists() {
return NewErrDoesNotExist(file)
}
return nil
}
// IsDir returns a directory with the path of File exists.
func (file File) IsDir() bool {
stat, err := file.Stat()
if err != nil {
return false
}
return stat.IsDir()
}
// CheckIsDir return an ErrDoesNotExist error
// if the file does not exist, ErrEmptyPath
// if the file path is empty, or ErrIsNotDirectory
// if a file exists, but is not a directory,
// or nil if the file is a directory.
func (file File) CheckIsDir() error {
stat, err := file.Stat()
switch {
case err != nil:
return err
case stat.IsDir():
return nil
default:
return NewErrIsNotDirectory(file)
}
}
// AbsPath returns the absolute path of the file
// depending on the file system.
func (file File) AbsPath() string {
fileSystem, path := file.ParseRawURI()
return fileSystem.AbsPath(path)
}
// HasAbsPath returns wether the file has an absolute
// path depending on the file system.
func (file File) HasAbsPath() bool {
fileSystem, path := file.ParseRawURI()
return fileSystem.IsAbsPath(path)
}
// ToAbsPath returns the file with an absolute
// path depending on the file system.
func (file File) ToAbsPath() File {
fileSystem, path := file.ParseRawURI()
uri := fileSystem.Prefix() + fileSystem.AbsPath(path)
return File(strings.TrimPrefix(uri, LocalPrefix))
}
// IsRegular reports if this is a regular file.
func (file File) IsRegular() bool {
stat, err := file.Stat()
if err != nil {
return false
}
return stat.Mode().IsRegular()
}
// IsEmptyDir returns if file is an empty directory.
func (file File) IsEmptyDir() bool {
l, err := file.ListDirMax(1)
return len(l) == 0 && err == nil
}
// IsHidden returns true if the filename begins with a dot,
// or if on Windows the hidden file attribute is set.
func (file File) IsHidden() bool {
fileSystem, path := file.ParseRawURI()
return fileSystem.IsHidden(path)
}
// IsSymbolicLink returns if the file is a symbolic link
// Use LocalFileSystem.CreateSymbolicLink and LocalFileSystem.ReadSymbolicLink
// to handle symbolic links.
func (file File) IsSymbolicLink() bool {
fileSystem, path := file.ParseRawURI()
return fileSystem.IsSymbolicLink(path)
}
// Size returns the size of the file or 0 if it does not exist or is a directory.
func (file File) Size() int64 {
stat, err := file.Stat()
if err != nil {
return 0
}
return stat.Size()
}
// ContentHash returns the DefaultContentHash for the file.
// If the FileSystem implementation does not have this hash pre-computed,
// then the whole file is read to compute it.
// If the file is a directory, then an empty string will be returned.
func (file File) ContentHash() (string, error) {
return file.ContentHashContext(context.Background())
}
// ContentHashContext returns the DefaultContentHash for the file.
// If the FileSystem implementation does not have this hash pre-computed,
// then the whole file is read to compute it.
// If the file is a directory, then an empty string will be returned.
func (file File) ContentHashContext(ctx context.Context) (string, error) {
if file == "" {
return "", ErrEmptyPath
}
if file.IsDir() {
return "", nil
}
reader, err := file.OpenReader()
if err != nil {
return "", err
}
defer reader.Close()
return DefaultContentHash(ctx, reader)
}
func (file File) Modified() time.Time {
stat, err := file.Stat()
if err != nil {
return time.Time{}
}
return stat.ModTime()
}
func (file File) Permissions() Permissions {
stat, err := file.Stat()
if err != nil {
return 0
}
return PermissionsFromStdFileInfo(stat)
}
func (file File) SetPermissions(perm Permissions) error {
if file == "" {
return ErrEmptyPath
}
fileSystem, path := file.ParseRawURI()
if fs, ok := fileSystem.(PermissionsFileSystem); ok {
return fs.SetPermissions(path, perm)
}
return NewErrUnsupported(fileSystem, "SetPermissions")
}
// ListDir calls the passed callback function for every file and directory.
// If any patterns are passed, then only files with a name that matches
// at least one of the patterns are returned.
func (file File) ListDir(callback func(File) error, patterns ...string) error {
return file.ListDirContext(context.Background(), callback, patterns...)
}
// ListDirContext calls the passed callback function for every file and directory in the directory.
// If any patterns are passed, then only files with a name that matches
// at least one of the patterns are returned.
// Canceling the context or returning an error from the callback
// will stop the listing and return the context or callback error.
func (file File) ListDirContext(ctx context.Context, callback func(File) error, patterns ...string) error {
if file == "" {
return ErrEmptyPath
}
fileSystem, path := file.ParseRawURI()
return fileSystem.ListDirInfo(ctx, path, FileInfoToFileCallback(callback), patterns)
}
// ListDirIter returns an iterator that yields every file and directory in the directory.
// If any patterns are passed, then only files with a name that matches
// at least one of the patterns are returned.
// In case of an error, the iterator will yield InvalidFile and the error
// as last key and value and then stop the iteration.
func (file File) ListDirIter(patterns ...string) iter.Seq2[File, error] {
return file.ListDirIterContext(context.Background(), patterns...)
}
// ListDirIterContext returns an iterator that yields every file and directory in the directory.
// If any patterns are passed, then only files with a name that matches
// at least one of the patterns are returned.
// In case of an error, the iterator will yield InvalidFile and the error
// as last key and value and then stop the iteration.
// Canceling the context will stop the iteration and yield the context error.
func (file File) ListDirIterContext(ctx context.Context, patterns ...string) iter.Seq2[File, error] {
return func(yield func(File, error) bool) {
var cancel SentinelError
err := file.ListDirContext(ctx,
func(listedFile File) error {
if !yield(listedFile, nil) {
return cancel
}
return nil
},
patterns...,
)
if err != nil && !errors.Is(err, cancel) {
yield(InvalidFile, err)
}
}
}
// MustGlob yields files and wildcard substituting path segments
// matching a path pattern.
//
// The pattern is appended to the current working directory
// if it is not an absolute path.
//
// The yielded path segments are the strings necessary
// to substitute all wildcard containing path segments
// in the pattern to form a valid path for a yielded file.
// This includes the name of the yielded file itself
// if the pattern contains wildcards for the last segment.
// Non wildcard segments are not included.
//
// The syntax of patterns is the same as in [path.Match].
// It always uses slash '/' as path segment separator
// independently of the file's file system.
//
// MustGlob ignores file system errors such as I/O errors reading directories.
// The only possible panic is in case of a malformed pattern.
func MustGlob(pattern string) iter.Seq2[File, []string] {
globIter, err := Glob(pattern)
if err != nil {
panic(err)
}
return globIter
}
// MustGlob yields files and wildcard substituting path segments
// matching a path pattern.
//
// The yielded path segments are the strings necessary
// to substitute all wildcard containing path segments
// in the pattern to form a valid path for a yielded file.
// This includes the name of the yielded file itself
// if the pattern contains wildcards for the last segment.
// Non wildcard segments are not included.
//
// The syntax of patterns is the same as in [path.Match].
// It always uses slash '/' as path segment separator
// independently of the file's file system.
//
// A pattern ending with a slash '/' will match only directories.
//
// MustGlob ignores file system errors such as I/O errors reading directories.
// The only possible panic is in case of a malformed pattern.
func (file File) MustGlob(pattern string) iter.Seq2[File, []string] {
globIter, err := file.Glob(pattern)
if err != nil {
panic(err)
}
return globIter
}
// Glob yields files and wildcard substituting path segments
// matching a path pattern.
//
// The pattern is appended to the current working directory
// if it is not an absolute path.
//
// The yielded path segments are the strings necessary
// to substitute all wildcard containing path segments
// in the pattern to form a valid path for a yielded file.
// This includes the name of the yielded file itself
// if the pattern contains wildcards for the last segment.
// Non wildcard segments are not included.
//
// The syntax of patterns is the same as in [path.Match].
// It always uses slash '/' as path segment separator
// independently of the file's file system.
//
// A pattern ending with a slash '/' will match only directories.
//
// Glob ignores file system errors such as I/O errors reading directories.
// The only possible returned error is [path.ErrBadPattern],
// reporting that the pattern is malformed.
func Glob(pattern string) (iter.Seq2[File, []string], error) {
// Find the first wildcard
i := strings.IndexAny(pattern, `*?[\`)
if i == -1 {
// No wildcard in pattern, yield the pattern as File
return File(path.Clean(pattern)).Glob("")
}
// Find the last path separator before the first wildcard
i = strings.LastIndexByte(pattern[:i], '/')
if i == -1 {
// No path separator before the first wildcard
// means that the pattern is relative to the current directory
return CurrentWorkingDir().Glob(pattern)
}
// Split pattern into base directory and glob pattern
return File(pattern[:i+1]).Glob(pattern[i+1:])
}
// Glob yields files and wildcard substituting path segments
// matching a path pattern.
//
// The yielded path segments are the strings necessary
// to substitute all wildcard containing path segments
// in the pattern to form a valid path for a yielded file.
// This includes the name of the yielded file itself
// if the pattern contains wildcards for the last segment.
// Non wildcard segments are not included.
//
// The syntax of patterns is the same as in [path.Match].
// It always uses slash '/' as path segment separator
// independently of the file's file system.
//
// A pattern ending with a slash '/' will match only directories.
//
// Glob ignores file system errors such as I/O errors reading directories.
// The only possible returned error is [path.ErrBadPattern],
// reporting that the pattern is malformed.
func (file File) Glob(pattern string) (iter.Seq2[File, []string], error) {
onlyDirs := strings.HasSuffix(pattern, "/")
pattern = strings.Trim(pattern, "/")
// Check if the pattern is valid
if _, err := path.Match(pattern, ""); err != nil {
return nil, fmt.Errorf("%w: %s", err, pattern)
}
pSegments := strings.Split(pattern, "/")
pSegments = slices.DeleteFunc(pSegments, func(s string) bool {
return s == "" || s == "."
})
if slices.Contains(pSegments, "..") {
return nil, fmt.Errorf("%w, must not contain '..': %s", path.ErrBadPattern, pattern)
}
switch i := slices.IndexFunc(pSegments, containsWildcard); {
case i < 0:
// No wildcard in pattern, join path and yield file if it exists
file = file.Join(pSegments...)
pSegments = nil
case i > 0:
// Join non wildcard path before first wildcard
file = file.Join(pSegments[:i]...)
pSegments = pSegments[i:]
}
file.CheckIsDir()
return file.glob(onlyDirs, pSegments, nil), nil
}
func containsWildcard(pattern string) bool {
return strings.ContainsAny(pattern, `*?[\`)
}
func (file File) glob(onlyDirs bool, segments, values []string) iter.Seq2[File, []string] {
return func(yield func(File, []string) bool) {
switch len(segments) {
case 0:
// No more segments, yield the file itself
if onlyDirs && file.IsDir() || !onlyDirs && file.Exists() {
yield(file, values)
}
case 1:
// Last segment, yield all matching files
if pattern := segments[0]; containsWildcard(pattern) {
// Wildcard in last segment, list directory with segment as pattern
for f, err := range file.ListDirIter(pattern) {
// If file is not a directory then ErrIsNotDirectory is expected
if err != nil {
return
}
if onlyDirs && !f.IsDir() || !onlyDirs && !f.Exists() {
continue
}
if !yield(f, append(slices.Clone(values), f.Name())) {
return
}
}
} else {
// No wildcard in last segment, join path and yield file if it exists
f := file.Join(pattern)
if onlyDirs && f.IsDir() || !onlyDirs && f.Exists() {
yield(f, values)
}
}
default:
if pattern := segments[0]; containsWildcard(pattern) {
// Wildcard in segment, list directory with segment as pattern
for matchedFile, err := range file.ListDirIter(pattern) {
// If file is not a directory then ErrIsNotDirectory is expected
if err != nil {
return
}
for f, v := range matchedFile.glob(onlyDirs, segments[1:], append(slices.Clone(values), matchedFile.Name())) {
if !yield(f, v) {
return
}
}
}
} else {
// No wildcard in segment, join path and recurse
for f, v := range file.Join(segments[0]).glob(onlyDirs, segments[1:], values) {
if !yield(f, v) {
return
}
}
}
}
}
}
// ListDirInfo calls the passed callback function for every file and directory in dirPath.
// If any patterns are passed, then only files with a name that matches
// at least one of the patterns are returned.
func (file File) ListDirInfo(callback func(*FileInfo) error, patterns ...string) error {
return file.ListDirInfoContext(context.Background(), callback, patterns...)
}
// ListDirInfoContext calls the passed callback function for every file and directory in dirPath.
// If any patterns are passed, then only files with a name that matches
// at least one of the patterns are returned.
func (file File) ListDirInfoContext(ctx context.Context, callback func(*FileInfo) error, patterns ...string) error {
if file == "" {
return ErrEmptyPath
}
fileSystem, path := file.ParseRawURI()
return fileSystem.ListDirInfo(ctx, path, callback, patterns)
}
// ListDirRecursive returns only files.
// patterns are only applied to files, not to directories
func (file File) ListDirRecursive(callback func(File) error, patterns ...string) error {
return file.ListDirInfoRecursiveContext(context.Background(), FileInfoToFileCallback(callback), patterns...)
}
// ListDirRecursiveContext returns only files.
// patterns are only applied to files, not to directories
func (file File) ListDirRecursiveContext(ctx context.Context, callback func(File) error, patterns ...string) error {
return file.ListDirInfoRecursiveContext(ctx, FileInfoToFileCallback(callback), patterns...)
}
// ListDirRecursiveIter returns an iterator that yields every file and directory
// recursively in the directory and sub-directories.
// If any patterns are passed, then only files with a name that matches
// at least one of the patterns are returned.
// In case of an error, the iterator will yield InvalidFile and the error
// as last key and value and then stop the iteration.
func (file File) ListDirRecursiveIter(patterns ...string) iter.Seq2[File, error] {
return file.ListDirRecursiveIterContext(context.Background(), patterns...)
}
// ListDirRecursiveIterContext returns an iterator that yields every file and directory
// recursively in the directory and sub-directories.
// If any patterns are passed, then only files with a name that matches
// at least one of the patterns are returned.
// In case of an error, the iterator will yield InvalidFile and the error
// as last key and value and then stop the iteration.
// Canceling the context will stop the iteration and yield the context error.
func (file File) ListDirRecursiveIterContext(ctx context.Context, patterns ...string) iter.Seq2[File, error] {
return func(yield func(File, error) bool) {
const cancel SentinelError = "cancel"
err := file.ListDirRecursiveContext(ctx,
func(listedFile File) error {
if !yield(listedFile, nil) {
return cancel
}
return nil
},
patterns...,
)
if err != nil && !errors.Is(err, cancel) {
yield(InvalidFile, err)
}
}
}
// ListDirInfoRecursive calls the passed callback function for every file (not directory) in dirPath
// recursing into all sub-directories.
// If any patterns are passed, then only files (not directories) with a name that matches
// at least one of the patterns are returned.
func (file File) ListDirInfoRecursive(callback func(*FileInfo) error, patterns ...string) error {
return file.ListDirInfoRecursiveContext(context.Background(), callback, patterns...)
}
// ListDirInfoRecursiveContext calls the passed callback function for every file
// (not directory) in dirPath recursing into all sub-directories.
// If any patterns are passed, then only files (not directories) with a name that matches
// at least one of the patterns are returned.
func (file File) ListDirInfoRecursiveContext(ctx context.Context, callback func(*FileInfo) error, patterns ...string) error {
if file == "" {
return ErrEmptyPath
}
fileSystem, path := file.ParseRawURI()
if fs, ok := fileSystem.(ListDirRecursiveFileSystem); ok {
return fs.ListDirInfoRecursive(ctx, path, callback, patterns)
}
return fileSystem.ListDirInfo(ctx, path,
func(info *FileInfo) error {
if info.IsDir {
// Not returning directories, but recursing into them
err := info.File.ListDirInfoRecursiveContext(ctx, callback, patterns...)
// Don't mind files that have been deleted while iterating
return RemoveErrDoesNotExist(err)
}
match, err := fileSystem.MatchAnyPattern(info.Name, patterns)
if !match || err != nil {
return err
}
return callback(info)
},
nil, // No patterns
)
}
// ListDirMax returns at most max files and directories in dirPath.
// A max value of -1 returns all files.
// If any patterns are passed, then only files or directories with a name that matches
// at least one of the patterns are returned.
func (file File) ListDirMax(max int, patterns ...string) (files []File, err error) {
return file.ListDirMaxContext(context.Background(), max, patterns...)
}
// ListDirMaxContext returns at most max files and directories in dirPath.
// A max value of -1 returns all files.
// If any patterns are passed, then only files or directories with a name that matches
// at least one of the patterns are returned.
func (file File) ListDirMaxContext(ctx context.Context, max int, patterns ...string) (files []File, err error) {
if file == "" {
return nil, ErrEmptyPath
}
if max == 0 {
return nil, nil
}
fileSystem, path := file.ParseRawURI()
if fs, ok := fileSystem.(ListDirMaxFileSystem); ok {
return fs.ListDirMax(ctx, path, max, patterns)
}
done := errors.New("done") // used as an internal flag, won't be returned
err = fileSystem.ListDirInfo(ctx, path, func(info *FileInfo) error {
if max >= 0 && len(files) >= max {
return done
}
if files == nil {
// Reserve space for files
capacity := max
if capacity < 0 {
capacity = 64
}
files = make([]File, 0, capacity)
}
files = append(files, info.File)
return nil
}, patterns)
if err != nil && !errors.Is(err, done) {
return nil, err
}
return files, nil
}
func (file File) ListDirRecursiveMax(max int, patterns ...string) (files []File, err error) {
return file.ListDirRecursiveMaxContext(context.Background(), max, patterns...)
}
func (file File) ListDirRecursiveMaxContext(ctx context.Context, max int, patterns ...string) (files []File, err error) {
if file == "" {
return nil, ErrEmptyPath
}
return listDirMaxImpl(ctx, max, func(ctx context.Context, callback func(File) error) error {
return file.ListDirRecursiveContext(ctx, callback, patterns...)
})
}
// ListDirChan returns listed files over a channel.
// An error or nil will returned from the error channel.
// The file channel will be closed after sending all files.
// If cancel is not nil and an error is sent to this channel, then the listing will be canceled
// and the error returned in the error channel returned by the method.
// See pipeline pattern: http://blog.golang.org/pipelines
func (file File) ListDirChan(cancel <-chan error, patterns ...string) (<-chan File, <-chan error) {
files := make(chan File)
errs := make(chan error, 1)
go func() {
defer close(files)
callback := func(f File) error {
select {
case files <- f:
return nil
case err := <-cancel:
return err
}
}
errs <- file.ListDir(callback, patterns...)
}()
return files, errs
}
// ListDirRecursiveChan returns listed files over a channel.
// An error or nil will returned from the error channel.
// The file channel will be closed after sending all files.
// If cancel is not nil and an error is sent to this channel, then the listing will be canceled
// and the error returned in the error channel returned by the method.
// See pipeline pattern: http://blog.golang.org/pipelines
func (file File) ListDirRecursiveChan(cancel <-chan error, patterns ...string) (<-chan File, <-chan error) {
files := make(chan File)
errs := make(chan error, 1)
go func() {
defer close(files)
callback := func(f File) error {
select {
case files <- f:
return nil
case err := <-cancel:
return err
}
}
errs <- file.ListDirRecursive(callback, patterns...)
}()
return files, errs
}
func (file File) User() (string, error) {
if file == "" {
return "", ErrEmptyPath
}
fileSystem, path := file.ParseRawURI()
if fs, ok := fileSystem.(UserFileSystem); ok {
return fs.User(path)
}
return "", NewErrUnsupported(fileSystem, "User")
}
func (file File) SetUser(user string) error {
if file == "" {
return ErrEmptyPath
}
fileSystem, path := file.ParseRawURI()
if fs, ok := fileSystem.(UserFileSystem); ok {
return fs.SetUser(path, user)
}
return NewErrUnsupported(fileSystem, "SetUser")
}
func (file File) Group() (string, error) {
if file == "" {
return "", ErrEmptyPath
}
fileSystem, path := file.ParseRawURI()
if fs, ok := fileSystem.(GroupFileSystem); ok {
return fs.Group(path)
}
return "", NewErrUnsupported(fileSystem, "Group")
}
func (file File) SetGroup(group string) error {
if file == "" {
return ErrEmptyPath
}
fileSystem, path := file.ParseRawURI()
if fs, ok := fileSystem.(GroupFileSystem); ok {
return fs.SetGroup(path, group)
}
return NewErrUnsupported(fileSystem, "SetGroup")
}
func (file File) Touch(perm ...Permissions) error {
if file == "" {
return ErrEmptyPath
}
fileSystem, path := file.ParseRawURI()
if fs, ok := fileSystem.(TouchFileSystem); ok {
return fs.Touch(path, perm)
}
w, err := file.OpenWriter(perm...)
if err != nil {
return err
}
return w.Close()
}
// MakeDir creates a directory if it does not exist yet.
// No error is returned if the directory already exists.
func (file File) MakeDir(perm ...Permissions) error {
if file == "" {
return ErrEmptyPath
}
if file.IsDir() {
return nil
}
fileSystem, path := file.ParseRawURI()
return fileSystem.MakeDir(path, perm)
}
// MakeAllDirs creates all directories up to this one,
// does not return an error if the directories already exist