-
Notifications
You must be signed in to change notification settings - Fork 8
/
files.go
1898 lines (1736 loc) · 49.4 KB
/
files.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
/*
* Copyright (C) 2020-2022 Arm Limited or its affiliates and Contributors. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package filesystem
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/user"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/bmatcuk/doublestar/v3"
"github.com/shirou/gopsutil/v3/disk"
"github.com/spf13/afero"
"github.com/ARM-software/golang-utils/utils/commonerrors"
"github.com/ARM-software/golang-utils/utils/parallelisation"
"github.com/ARM-software/golang-utils/utils/platform"
"github.com/ARM-software/golang-utils/utils/reflection"
"github.com/ARM-software/golang-utils/utils/resource"
"github.com/ARM-software/golang-utils/utils/safeio"
)
var (
ErrLinkNotImplemented = fmt.Errorf("link not implemented: %w", commonerrors.ErrNotImplemented)
ErrChownNotImplemented = fmt.Errorf("chown not implemented: %w", commonerrors.ErrNotImplemented)
ErrPathNotExist = errors.New("readdirent: no such file or directory")
globalFileSystem = NewFs(StandardFS)
)
const (
UnsetFileHandle = ^uint64(0)
)
type UsageStat struct {
Total uint64
Free uint64
Used uint64
UsedPercent float64
InodesTotal uint64
InodesUsed uint64
InodesFree uint64
InodesUsedPercent float64
}
func (d *UsageStat) GetTotal() uint64 { return d.Total }
func (d *UsageStat) GetFree() uint64 { return d.Free }
func (d *UsageStat) GetUsed() uint64 { return d.Used }
func (d *UsageStat) GetUsedPercent() float64 { return d.UsedPercent }
func (d *UsageStat) GetInodesTotal() uint64 { return d.InodesTotal }
func (d *UsageStat) GetInodesUsed() uint64 { return d.InodesUsed }
func (d *UsageStat) GetInodesFree() uint64 { return d.Free }
func (d *UsageStat) GetInodesUsedPercent() float64 { return d.InodesUsedPercent }
func IdentityPathConverterFunc(path string) string {
return path
}
type VFS struct {
resourceInUse resource.ICloseableResource
vfs afero.Fs
fsType FilesystemType
pathConverter func(path string) string
}
// NewVirtualFileSystem returns a virtual filesystem similarly to NewCloseableVirtualFileSystem
func NewVirtualFileSystem(vfs afero.Fs, fsType FilesystemType, pathConverter func(path string) string) FS {
return NewCloseableVirtualFileSystem(vfs, fsType, nil, "", pathConverter)
}
// NewCloseableVirtualFileSystem returns a virtual filesystem which requires closing after use.
// It is a wrapper over afero.FS virtual filesystem and tends to define common filesystem utilities as the ones available in posix.
func NewCloseableVirtualFileSystem(vfs afero.Fs, fsType FilesystemType, resourceInUse io.Closer, resourceInUseDescription string, pathConverter func(path string) string) ICloseableFS {
var resourceInUseByFs resource.ICloseableResource
if resourceInUse == nil {
resourceInUseByFs = resource.NewNonCloseableResource()
} else {
resourceInUseByFs = resource.NewCloseableResource(resourceInUse, resourceInUseDescription)
}
return &VFS{
resourceInUse: resourceInUseByFs,
vfs: vfs,
fsType: fsType,
pathConverter: pathConverter,
}
}
func GetGlobalFileSystem() FS {
return globalFileSystem
}
func GetType() FilesystemType {
return globalFileSystem.GetType()
}
// checkWhetherUnderlyingResourceIsClosed checks whether the filesystem is in a working state when relying on a ICloseableResource.
func (fs *VFS) checkWhetherUnderlyingResourceIsClosed() error {
if fs.resourceInUse.IsClosed() {
return fmt.Errorf("%w: the resource this filesystem is based on [%v] has been closed", commonerrors.ErrCondition, fs.resourceInUse.String())
}
return nil
}
// Walk walks https://golang.org/pkg/path/filepath/#WalkDir
func (fs *VFS) Walk(root string, fn filepath.WalkFunc) error {
return fs.WalkWithContext(context.Background(), root, fn)
}
func (fs *VFS) WalkWithContext(ctx context.Context, root string, fn filepath.WalkFunc) error {
return fs.WalkWithContextAndExclusionPatterns(ctx, root, fn)
}
func (fs *VFS) WalkWithContextAndExclusionPatterns(ctx context.Context, root string, fn filepath.WalkFunc, exclusionPatterns ...string) (err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
root = filepath.Join(root, string(fs.PathSeparator()))
exclusionRegex, err := NewExclusionRegexList(fs.PathSeparator(), exclusionPatterns...)
if err != nil {
return
}
if IsPathExcluded(root, exclusionRegex...) {
// In this case, the whole tree is excluded and so, we can stop here
return
}
info, err := fs.Lstat(root)
if err != nil {
err = fn(root, nil, err)
} else {
err = fs.walk(ctx, root, info, exclusionRegex, fn)
}
if commonerrors.Any(err, filepath.SkipDir) {
return nil
}
return err
}
// walks recursively descends path, calling fn.
func (fs *VFS) walk(ctx context.Context, path string, info os.FileInfo, exclusions []*regexp.Regexp, fn filepath.WalkFunc) (err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
err = parallelisation.DetermineContextError(ctx)
if err != nil {
return
}
err = fn(path, info, nil)
if err != nil || !info.IsDir() {
if commonerrors.Any(err, filepath.SkipDir) && info.IsDir() {
err = nil
}
return
}
items, err := fs.Ls(path)
if err != nil {
err = fn(path, info, err)
if err != nil {
return
}
}
cleansedList, err := ExcludeFiles(items, exclusions)
if err != nil {
err = fn(path, info, err)
if err != nil {
return
}
}
for i := range cleansedList {
itemName := cleansedList[i]
subErr := parallelisation.DetermineContextError(ctx)
if subErr != nil {
return subErr
}
filename := filepath.Join(path, itemName)
fileInfo, subErr := fs.Lstat(filename)
if subErr != nil {
if err := fn(filename, fileInfo, subErr); err != nil && err != filepath.SkipDir {
return err
}
} else {
subErr = fs.walk(ctx, filename, fileInfo, exclusions, fn)
if subErr != nil {
if !fileInfo.IsDir() || subErr != filepath.SkipDir {
return subErr
}
}
}
}
return nil
}
func (fs *VFS) GetType() FilesystemType {
return fs.fsType
}
func (fs *VFS) ConvertFilePath(name string) string {
return fs.pathConverter(name)
}
func TempDirectory() string {
return globalFileSystem.TempDirectory()
}
func (fs *VFS) TempDirectory() string {
return afero.GetTempDir(fs.vfs, "")
}
func CurrentDirectory() (string, error) {
return globalFileSystem.CurrentDirectory()
}
func (fs *VFS) CurrentDirectory() (string, error) {
current, err := os.Getwd()
return fs.ConvertFilePath(current), err
}
func Lstat(name string) (fileInfo os.FileInfo, err error) {
return globalFileSystem.Lstat(name)
}
func (fs *VFS) Lstat(name string) (fileInfo os.FileInfo, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
if correctobj, ok := fs.vfs.(IStater); ok {
fileInfo, _, err = correctobj.LstatIfPossible(name)
return
}
fileInfo, err = fs.Stat(name)
if err != nil {
err = commonerrors.ErrNotImplemented
}
return
}
func (fs *VFS) Open(name string) (doublestar.File, error) {
return fs.GenericOpen(name)
}
func GenericOpen(name string) (File, error) {
return globalFileSystem.GenericOpen(name)
}
func (fs *VFS) GenericOpen(name string) (File, error) {
err := fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return nil, err
}
return convertFile(func() (afero.File, error) { return fs.vfs.Open(name) }, func() error { return nil })
}
func OpenFile(name string, flag int, perm os.FileMode) (File, error) {
return globalFileSystem.OpenFile(name, flag, perm)
}
func (fs *VFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
err := fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return nil, err
}
return convertFile(func() (afero.File, error) { return fs.vfs.OpenFile(name, flag, perm) }, func() error { return nil })
}
func CreateFile(name string) (File, error) {
return globalFileSystem.CreateFile(name)
}
func (fs *VFS) CreateFile(name string) (File, error) {
err := fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return nil, err
}
return convertFile(func() (afero.File, error) { return fs.vfs.Create(name) }, func() error { return nil })
}
func (fs *VFS) NewRemoteLockFile(id string, dirToLock string) ILock {
return NewRemoteLockFile(fs, id, dirToLock)
}
func ReadFile(name string) ([]byte, error) {
return globalFileSystem.ReadFile(name)
}
func (fs *VFS) ReadFile(filename string) (content []byte, err error) {
return fs.readFileWithContextAndLimits(context.Background(), filename, NoLimits())
}
func ReadFileWithLimits(filename string, limits ILimits) ([]byte, error) {
return globalFileSystem.ReadFileWithLimits(filename, limits)
}
func (fs *VFS) ReadFileWithLimits(filename string, limits ILimits) ([]byte, error) {
return fs.readFileWithContextAndLimits(context.Background(), filename, limits)
}
func (fs *VFS) ReadFileWithContext(ctx context.Context, filename string) ([]byte, error) {
return fs.readFileWithContextAndLimits(ctx, filename, NoLimits())
}
func (fs *VFS) ReadFileWithContextAndLimits(ctx context.Context, filename string, limits ILimits) ([]byte, error) {
return fs.readFileWithContextAndLimits(ctx, filename, limits)
}
func (fs *VFS) readFileWithContextAndLimits(ctx context.Context, filename string, limits ILimits) (content []byte, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
err = parallelisation.DetermineContextError(ctx)
if err != nil {
return
}
if limits == nil {
err = fmt.Errorf("%w: missing file system limits definition", commonerrors.ErrUndefined)
return
}
// Really similar to afero ioutils Read file but using our utilities instead.
f, err := fs.GenericOpen(filename)
if err != nil {
return
}
defer func() { _ = f.Close() }()
content, err = fs.ReadFileContent(ctx, f, limits)
return
}
// ReadFileContent reads the file content.
func ReadFileContent(ctx context.Context, file File) ([]byte, error) {
return globalFileSystem.ReadFileContent(ctx, file, NoLimits())
}
func (fs *VFS) ReadFileContent(ctx context.Context, file File, limits ILimits) (content []byte, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
err = parallelisation.DetermineContextError(ctx)
if err != nil {
return
}
if file == nil {
err = fmt.Errorf("%w: missing file definition", commonerrors.ErrUndefined)
return
}
if limits == nil {
err = fmt.Errorf("%w: missing file system limits definition", commonerrors.ErrUndefined)
return
}
var bufferCapacity int64 = bytes.MinRead
var max int64 = -1
if limits.Apply() {
max = limits.GetMaxFileSize()
}
fi, err := file.Stat()
if err == nil {
// Don't preallocate a huge buffer, just in case.
fileSize := fi.Size()
if fileSize < 1e9 {
bufferCapacity += fileSize
}
if limits.Apply() && fileSize > max {
err = fmt.Errorf("%w: file [%v] is bigger than allowed size [%vB]", commonerrors.ErrTooLarge, file.Name(), max)
return
}
}
content, err = safeio.ReadAtMost(ctx, file, max, bufferCapacity)
return
}
// WriteFile writes data to a file
func WriteFile(filename string, data []byte, perm os.FileMode) error {
return globalFileSystem.WriteFile(filename, data, perm)
}
func (fs *VFS) WriteFile(filename string, data []byte, perm os.FileMode) error {
return fs.WriteFileWithContext(context.Background(), filename, data, perm)
}
func (fs *VFS) WriteFileWithContext(ctx context.Context, filename string, data []byte, perm os.FileMode) (err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
reader := bytes.NewReader(data)
n, err := fs.WriteToFile(ctx, filename, reader, perm)
if err != nil {
return
}
if int(n) < len(data) {
err = io.ErrShortWrite
}
return
}
func (fs *VFS) WriteToFile(ctx context.Context, filename string, reader io.Reader, perm os.FileMode) (written int64, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
err = parallelisation.DetermineContextError(ctx)
if err != nil {
return
}
f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return
}
defer func() { _ = f.Close() }()
written, err = safeio.CopyDataWithContext(ctx, reader, f)
if err != nil {
return
}
if written == 0 {
err = fmt.Errorf("%w: no bytes were written", commonerrors.ErrEmpty)
return
}
err = f.Close()
return
}
func PathSeparator() rune {
return globalFileSystem.PathSeparator()
}
func (fs *VFS) PathSeparator() rune {
return os.PathSeparator
}
func Stat(name string) (os.FileInfo, error) {
return globalFileSystem.Stat(name)
}
func (fs *VFS) Stat(name string) (os.FileInfo, error) {
err := fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return nil, err
}
return fs.vfs.Stat(name)
}
func (fs *VFS) StatTimes(name string) (info FileTimeInfo, err error) {
stat, err := fs.Stat(name)
if err == nil || stat == nil {
return DetermineFileTimes(stat)
}
return
}
func TempDir(dir string, prefix string) (name string, err error) {
return globalFileSystem.TempDir(dir, prefix)
}
func (fs *VFS) TempDir(dir string, prefix string) (name string, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
return afero.TempDir(fs.vfs, dir, prefix)
}
func TempDirInTempDir(prefix string) (name string, err error) {
return globalFileSystem.TempDirInTempDir(prefix)
}
func (fs *VFS) TempDirInTempDir(prefix string) (name string, err error) {
return fs.TempDir("", prefix)
}
func TempFile(dir string, pattern string) (f File, err error) {
return globalFileSystem.TempFile(dir, pattern)
}
func (fs *VFS) TempFile(dir string, prefix string) (f File, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
file, err := afero.TempFile(fs.vfs, dir, prefix)
if err != nil {
return
}
return convertToExtendedFile(file, func() error { return nil })
}
// TouchTempFile creates an empty file in `dir` and returns it filename
func TouchTempFile(dir string, prefix string) (filename string, err error) {
return globalFileSystem.TouchTempFile(dir, prefix)
}
func (fs *VFS) TouchTempFile(dir string, prefix string) (filename string, err error) {
file, err := fs.TempFile(dir, prefix)
if file != nil {
_ = file.Close()
filename = file.Name()
}
return
}
func TempFileInTempDir(pattern string) (f File, err error) {
return globalFileSystem.TempFileInTempDir(pattern)
}
func (fs *VFS) TempFileInTempDir(prefix string) (f File, err error) {
return fs.TempFile("", prefix)
}
// TouchTempFileInTempDir creates an empty file in temp directory and returns it filename
func TouchTempFileInTempDir(prefix string) (filename string, err error) {
return globalFileSystem.TouchTempFileInTempDir(prefix)
}
func (fs *VFS) TouchTempFileInTempDir(prefix string) (filename string, err error) {
return fs.TouchTempFile("", prefix)
}
func CleanDir(dir string) (err error) {
return globalFileSystem.CleanDir(dir)
}
func (fs *VFS) CleanDir(dir string) error {
return fs.CleanDirWithContext(context.Background(), dir)
}
func (fs *VFS) CleanDirWithContext(ctx context.Context, dir string) error {
return fs.CleanDirWithContextAndExclusionPatterns(ctx, dir)
}
func (fs *VFS) CleanDirWithContextAndExclusionPatterns(ctx context.Context, dir string, exclusionPatterns ...string) (err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
err = parallelisation.DetermineContextError(ctx)
if err != nil {
return
}
if dir == "" || !fs.Exists(dir) {
return
}
empty, err := fs.IsEmpty(dir)
if empty || err != nil {
return
}
files, err := fs.LsWithExclusionPatterns(dir, exclusionPatterns...)
if err != nil {
return
}
for i := range files {
subErr := fs.removeFileWithContext(ctx, dir, files[i])
if subErr != nil {
err = subErr
return
}
}
return
}
func (fs *VFS) removeFileWithContext(ctx context.Context, dir, f string) (err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
err = parallelisation.DetermineContextError(ctx)
if err != nil {
return
}
err = fs.RemoveWithContext(ctx, filepath.Join(dir, f))
return
}
// Exists checks if a file or folder exists
func Exists(path string) bool {
return globalFileSystem.Exists(path)
}
func (fs *VFS) Exists(path string) bool {
fi, err := fs.Stat(path)
if err != nil {
if IsPathNotExist(err) {
return false
}
}
if fi == nil {
return false
}
// Double check for directories as it was seen on Docker that Stat would work on Docker even if path does not exist
if fi.IsDir() {
return fs.checkDirExists(path)
}
return true
}
func (fs *VFS) checkDirExists(path string) (exist bool) {
exist = false
f, err := fs.vfs.Open(path)
if err != nil {
return
}
defer func() { _ = f.Close() }()
_, err = f.Readdirnames(1)
if IsPathNotExist(err) {
exist = false
} else {
exist = true
}
_ = f.Close()
return
}
func Rm(dir string) error {
return globalFileSystem.Rm(dir)
}
func (fs *VFS) Rm(dir string) error {
return fs.RemoveWithContext(context.Background(), dir)
}
// RemoveWithPrivileges removes any directory (equivalent to `sudo rm -rf`)
func RemoveWithPrivileges(ctx context.Context, dir string) error {
return globalFileSystem.RemoveWithPrivileges(ctx, dir)
}
func (fs *VFS) RemoveWithPrivileges(ctx context.Context, dir string) (err error) {
err = fs.RemoveWithContext(ctx, dir)
if commonerrors.Any(err, nil, commonerrors.ErrTimeout, commonerrors.ErrCancelled) {
return
}
currentUser, subErr := user.Current()
if subErr != nil {
err = fmt.Errorf("%w: cannot retrieve information about current user: %v", commonerrors.ErrUnexpected, subErr.Error())
return
}
subErr = fs.ChangeOwnership(dir, currentUser)
if subErr == nil {
err = fs.RemoveWithContext(ctx, dir)
if commonerrors.Any(err, nil, commonerrors.ErrTimeout, commonerrors.ErrCancelled) {
return
}
}
if correctobj, ok := fs.vfs.(IForceRemover); ok {
err = correctobj.ForceRemoveIfPossible(dir)
}
return
}
func (fs *VFS) RemoveWithContext(ctx context.Context, dir string) error {
return fs.RemoveWithContextAndExclusionPatterns(ctx, dir)
}
func (fs *VFS) RemoveWithContextAndExclusionPatterns(ctx context.Context, dir string, exclusionPatterns ...string) (err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
if dir == "" {
return
}
if !fs.Exists(dir) {
return
}
isDir, err := fs.IsDir(dir)
if err != nil {
return
}
isEmpty, err := fs.IsEmpty(dir)
if err != nil {
return
}
if isDir && !isEmpty {
err = fs.CleanDirWithContextAndExclusionPatterns(ctx, dir, exclusionPatterns...)
}
if err != nil {
return
}
isEmpty, err = fs.IsEmpty(dir) // Checking again if empty as some files may have been ignored.
if err != nil {
return
}
if isDir && !isEmpty {
return
} // some files may have been ignored and so, the removal should stop
err = parallelisation.DetermineContextError(ctx)
if err != nil {
return
}
if IsPathExcludedFromPatterns(dir, fs.PathSeparator(), exclusionPatterns...) {
return
}
return fs.vfs.Remove(dir)
}
// IsFile states whether it is a file or not
func IsFile(path string) (result bool, err error) {
return globalFileSystem.IsFile(path)
}
func (fs *VFS) IsFile(path string) (result bool, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
if !fs.Exists(path) {
return
}
fi, err := fs.Stat(path)
if err != nil {
return
}
result = IsRegularFile(fi)
return
}
func IsRegularFile(fi os.FileInfo) bool {
if fi == nil {
return false
}
return fi.Mode().IsRegular()
}
func (fs *VFS) IsLink(path string) (result bool, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
if !fs.Exists(path) {
return
}
fi, err := fs.Lstat(path)
if err != nil {
return
}
result = IsSymLink(fi)
return
}
func IsSymLink(fi os.FileInfo) bool {
if fi == nil {
return false
}
return fi.Mode()&os.ModeType == os.ModeSymlink
}
// IsDir states whether it is a directory or not
func IsDir(path string) (result bool, err error) {
return globalFileSystem.IsDir(path)
}
func (fs *VFS) IsDir(path string) (result bool, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
if !fs.Exists(path) {
err = fmt.Errorf("%w: path [%v]", commonerrors.ErrNotFound, path)
return
}
fi, err := fs.Stat(path)
if err != nil {
return
}
result = IsDirectory(fi)
return
}
func IsDirectory(fi os.FileInfo) bool {
if fi == nil {
return false
}
return fi.IsDir()
}
// IsEmpty checks whether a path is empty or not
func IsEmpty(name string) (empty bool, err error) {
return globalFileSystem.IsEmpty(name)
}
func (fs *VFS) IsEmpty(name string) (empty bool, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
if !fs.Exists(name) {
empty = true
return
}
isFile, err := fs.IsFile(name)
if err != nil {
return
}
if isFile {
return fs.isFileEmpty(name)
}
return fs.isDirEmpty(name)
}
func (fs *VFS) isFileEmpty(name string) (empty bool, err error) {
fi, err := fs.Stat(name)
if err != nil {
return
}
empty = fi.Size() == 0
return
}
func (fs *VFS) isDirEmpty(name string) (empty bool, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
f, err := fs.vfs.Open(name)
if err != nil {
return
}
defer func() {
if f != nil {
_ = f.Close()
}
}()
_, err = f.Readdirnames(1)
if commonerrors.Any(err, io.EOF, commonerrors.ErrEOF) || IsPathNotExist(err) {
err = nil
empty = true
return
}
err = f.Close()
return
}
// MkDir makes directory (equivalent to mkdir -p)
func MkDir(dir string) (err error) {
return globalFileSystem.MkDir(dir)
}
func (fs *VFS) MkDir(dir string) (err error) {
return fs.MkDirAll(dir, 0755)
}
func (fs *VFS) MkDirAll(dir string, perm os.FileMode) (err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
if dir == "" {
return fmt.Errorf("missing path: %w", commonerrors.ErrUndefined)
}
if fs.Exists(dir) {
return
}
err = fs.vfs.MkdirAll(dir, perm)
// Directory was maybe created by a different process/thread
if err != nil && fs.Exists(dir) {
err = nil
}
return
}
// FindAll finds all the files with extensions
func FindAll(dir string, extensions ...string) (files []string, err error) {
return globalFileSystem.FindAll(dir, extensions...)
}
func (fs *VFS) FindAll(dir string, extensions ...string) (files []string, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
files = []string{}
if !fs.Exists(dir) {
return
}
for _, ext := range extensions {
foundFiles, err := fs.findAllOfExtension(dir, ext)
if err != nil {
return files, err
}
files = append(files, foundFiles...)
}
return
}
func (fs *VFS) findAllOfExtension(dir string, ext string) (files []string, err error) {
files, err = fs.Glob(filepath.Join(dir, "**", fmt.Sprintf("*.%v", strings.TrimPrefix(ext, "."))))
return
}
// Glob returns the names of all files matching pattern with support for "doublestar" (aka globstar: **) patterns
// You can find the children with patterns such as: **/child*, grandparent/**/child?, **/parent/*, or even just ** by itself (which will return all files and directories recursively).
func Glob(pattern string) ([]string, error) {
return GetGlobalFileSystem().Glob(pattern)
}
func (fs *VFS) Glob(pattern string) (matches []string, err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
matches, err = doublestar.GlobOS(fs, pattern)
if commonerrors.Any(err, doublestar.ErrBadPattern) {
err = fmt.Errorf("%w: %v", commonerrors.ErrInvalid, err.Error())
}
return
}
// Chmod changes the file mode of a filesystem item.
func Chmod(name string, mode os.FileMode) error {
return GetGlobalFileSystem().Chmod(name, mode)
}
func (fs *VFS) Chmod(name string, mode os.FileMode) (err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
err = fs.vfs.Chmod(name, mode)
return
}
func (fs *VFS) ChmodRecursively(ctx context.Context, path string, mode os.FileMode) (err error) {
err = parallelisation.DetermineContextError(ctx)
if err != nil {
return
}
if isFile, _ := fs.IsFile(path); isFile {
err = fs.Chmod(path, mode)
return
}
err = fs.WalkWithContext(ctx, path, func(subPath string, info os.FileInfo, subErr error) error {
if subErr != nil {
return subErr
}
return fs.Chmod(subPath, mode)
})
return
}
func (fs *VFS) Touch(path string) (err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
if fs.Exists(path) {
now := time.Now().UTC()
err = fs.Chtimes(path, now, now)
return
}
if strings.TrimSpace(path) == "" {
err = fmt.Errorf("%w: empty path", commonerrors.ErrUndefined)
return
}
if EndsWithPathSeparator(fs, path) {
err = fs.MkDir(path)
return
}
file, err := fs.CreateFile(path)
if file != nil {
_ = file.Close()
}
return
}
func (fs *VFS) Chtimes(name string, atime time.Time, mtime time.Time) (err error) {
err = fs.checkWhetherUnderlyingResourceIsClosed()
if err != nil {
return
}
err = fs.vfs.Chtimes(name, atime, mtime)
return
}
func (fs *VFS) ChangeOwnership(name string, owner *user.User) error {
if owner == nil {
return fmt.Errorf("%w: missing user definition", commonerrors.ErrUndefined)
}
uid, err := strconv.Atoi(owner.Uid)
if err != nil {
return fmt.Errorf("%w: cannot parse owner uid", commonerrors.ErrUnexpected)
}
gid, err := strconv.Atoi(owner.Gid)
if err != nil {
return fmt.Errorf("%w: cannot parse owner gid", commonerrors.ErrUnexpected)
}
return fs.Chown(name, uid, gid)
}
func (fs *VFS) ChangeOwnershipRecursively(ctx context.Context, path string, owner *user.User) (err error) {
err = parallelisation.DetermineContextError(ctx)
if err != nil {
return
}
if isFile, _ := fs.IsFile(path); isFile {
err = fs.ChangeOwnership(path, owner)
return
}
if owner == nil {
return fmt.Errorf("%w: missing user definition", commonerrors.ErrUndefined)
}
err = fs.WalkWithContext(ctx, path, func(subPath string, info os.FileInfo, subErr error) error {