-
Notifications
You must be signed in to change notification settings - Fork 8
/
files.go
1345 lines (1212 loc) · 32.7 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 (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/bmatcuk/doublestar/v3"
"github.com/shirou/gopsutil/v3/disk"
"github.com/spf13/afero"
"golang.org/x/text/encoding/unicode"
"github.com/ARM-software/golang-utils/utils/charset"
"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"
)
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 {
vfs afero.Fs
fsType int
pathConverter func(path string) string
}
func NewVirtualFileSystem(vfs afero.Fs, fsType int, pathConverter func(path string) string) FS {
return &VFS{
vfs: vfs,
fsType: fsType,
pathConverter: pathConverter,
}
}
func GetGlobalFileSystem() FS {
return globalFileSystem
}
func GetType() int {
return globalFileSystem.GetType()
}
// Walks https://golang.org/pkg/path/filepath/#WalkDir
func (fs *VFS) Walk(root string, fn filepath.WalkFunc) error {
info, err := fs.Lstat(root)
if err != nil {
err = fn(root, nil, err)
} else {
err = fs.walk(root, info, fn)
}
if commonerrors.Any(err, filepath.SkipDir) {
return nil
}
return err
}
// walks recursively descends path, calling fn.
func (fs *VFS) walk(path string, info os.FileInfo, fn filepath.WalkFunc) error {
if err := fn(path, info, nil); err != nil || !info.IsDir() {
if commonerrors.Any(err, filepath.SkipDir) && info.IsDir() {
err = nil
}
return err
}
items, err := fs.Ls(path)
if err != nil {
err = fn(path, info, err)
if err != nil {
return err
}
}
for _, name := range items {
filename := filepath.Join(path, name)
fileInfo, err := fs.Lstat(filename)
if err != nil {
if err := fn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
return err
}
} else {
err = fs.walk(filename, fileInfo, fn)
if err != nil {
if !fileInfo.IsDir() || err != filepath.SkipDir {
return err
}
}
}
}
return nil
}
func (fs *VFS) GetType() int {
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) {
return os.Getwd()
}
func Lstat(name string) (fileInfo os.FileInfo, err error) {
return globalFileSystem.Lstat(name)
}
func (fs *VFS) Lstat(name string) (fileInfo os.FileInfo, err error) {
if correctobj, ok := fs.vfs.(interface {
LstatIfPossible(string) (os.FileInfo, bool, error)
}); 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) {
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) {
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) {
return convertFile(func() (afero.File, error) { return fs.vfs.Create(name) }, func() error { return nil })
}
func ReadFile(name string) ([]byte, error) {
return globalFileSystem.ReadFile(name)
}
func (fs *VFS) NewRemoteLockFile(id string, dirToLock string) ILock {
return NewRemoteLockFile(fs, id, dirToLock)
}
func (fs *VFS) ReadFile(filename string) (content []byte, err error) {
// Really similar to afero iotutils Read file but using our utilities instead.
f, err := fs.GenericOpen(filename)
if err != nil {
return
}
defer func() { _ = f.Close() }()
var bufferCapacity int64 = bytes.MinRead
if fi, err := f.Stat(); err == nil {
// Don't preallocate a huge buffer, just in case.
if size := fi.Size(); size < 1e9 {
bufferCapacity += size
}
}
buf := bytes.NewBuffer(make([]byte, 0, bufferCapacity))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(f)
content = buf.Bytes()
return
}
func (fs *VFS) WriteFile(filename string, data []byte, perm os.FileMode) (err error) {
f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return
}
defer func() { _ = f.Close() }()
n, err := f.Write(data)
if err != nil {
return
}
if n < len(data) {
err = io.ErrShortWrite
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) {
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) {
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) {
file, err := afero.TempFile(fs.vfs, dir, prefix)
if err != nil {
return
}
return convertToExtendedFile(file, func() error { return nil })
}
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)
}
// Removes all the files in a directory (equivalent rm -rf .../*)
func CleanDir(dir string) (err error) {
return globalFileSystem.CleanDir(dir)
}
func (fs *VFS) CleanDir(dir string) (err error) {
if dir == "" || !fs.Exists(dir) {
return
}
empty, err := fs.IsEmpty(dir)
if empty || err != nil {
return
}
files, err := fs.Ls(dir)
if err != nil {
return
}
for _, f := range files {
err = fs.Rm(filepath.Join(dir, f))
if err != nil {
return
}
}
return
}
// 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
}
// Removes directory (equivalent to rm -r)
func Rm(dir string) (err error) {
return globalFileSystem.Rm(dir)
}
func (fs *VFS) Rm(dir string) (err error) {
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.CleanDir(dir)
}
if err != nil {
return
}
return fs.vfs.Remove(dir)
}
// 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) {
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) {
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
}
// 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) {
if !fs.Exists(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()
}
// 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) {
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) {
f, err := fs.vfs.Open(name)
if err != nil {
return
}
defer func() {
if f != nil {
_ = f.Close()
}
}()
_, err = f.Readdirnames(1)
if err == io.EOF || IsPathNotExist(err) {
err = nil
empty = true
return
}
err = f.Close()
return
}
// 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) {
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
}
// Excludes files
func ExcludeAll(files []string, exclusionPatterns ...string) ([]string, error) {
return globalFileSystem.ExcludeAll(files, exclusionPatterns...)
}
func (fs *VFS) ExcludeAll(files []string, exclusionPatterns ...string) ([]string, error) {
regexes := []*regexp.Regexp{}
patternsExtendedList := []string{}
for _, p := range exclusionPatterns {
if p != "" {
patternsExtendedList = append(patternsExtendedList, p, fmt.Sprintf(".*/%v/.*", p), fmt.Sprintf(".*%v%v%v.*", fs.PathSeparator(), p, fs.PathSeparator()))
}
}
for _, p := range patternsExtendedList {
r, err := regexp.Compile(p)
if err != nil {
return nil, err
}
regexes = append(regexes, r)
}
cleansedList := []string{}
for _, f := range files {
if !isExcluded(f, regexes...) {
cleansedList = append(cleansedList, f)
}
}
return cleansedList, nil
}
func isExcluded(path string, exclusionPatterns ...*regexp.Regexp) bool {
for _, p := range exclusionPatterns {
if p.MatchString(path) {
return true
}
}
return false
}
// 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) {
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) {
if strings.HasPrefix(ext, ".") {
ext = string(ext[1:])
}
return doublestar.GlobOS(fs, filepath.Join(dir, "**", "*."+ext))
}
func (fs *VFS) Chmod(name string, mode os.FileMode) error {
return fs.vfs.Chmod(name, mode)
}
func (fs *VFS) Chtimes(name string, atime time.Time, mtime time.Time) error {
return fs.vfs.Chtimes(name, atime, mtime)
}
func (fs *VFS) Chown(name string, uid, gid int) (err error) {
if correctobj, ok := fs.vfs.(interface {
ChownIfPossible(string, int, int) error
}); ok {
err = correctobj.ChownIfPossible(name, uid, gid)
return
}
err = commonerrors.ErrNotImplemented
return
}
func (fs *VFS) Link(oldname, newname string) (err error) {
if correctobj, ok := fs.vfs.(interface {
LinkIfPossible(string, string) error
}); ok {
err = correctobj.LinkIfPossible(oldname, newname)
return
}
err = commonerrors.ErrNotImplemented
return
}
func (fs *VFS) Readlink(name string) (value string, err error) {
if correctobj, ok := fs.vfs.(interface {
ReadlinkIfPossible(string) (string, error)
}); ok {
value, err = correctobj.ReadlinkIfPossible(name)
return
}
err = commonerrors.ErrNotImplemented
return
}
func (fs *VFS) Symlink(oldname string, newname string) (err error) {
if correctobj, ok := fs.vfs.(interface {
SymlinkIfPossible(string, string) error
}); ok {
err = correctobj.SymlinkIfPossible(oldname, newname)
return
}
err = commonerrors.ErrNotImplemented
return
}
func Ls(dir string) (files []string, err error) {
return globalFileSystem.Ls(dir)
}
func (fs *VFS) Ls(dir string) (names []string, err error) {
if isDir, err := fs.IsDir(dir); !isDir || err != nil {
err = fmt.Errorf("path [%v] is not a directory: %w", dir, commonerrors.ErrInvalid)
return nil, err
}
f, err := fs.GenericOpen(dir)
if err != nil {
return nil, err
}
names, err = fs.LsFromOpenedDirectory(f)
_ = f.Close()
return names, err
}
func (fs *VFS) LsFromOpenedDirectory(dir File) ([]string, error) {
if dir == nil {
return nil, fmt.Errorf("%w: nil directory", commonerrors.ErrUndefined)
}
return dir.Readdirnames(-1)
}
func (fs *VFS) Lls(dir string) (files []os.FileInfo, err error) {
if isDir, err := fs.IsDir(dir); !isDir || err != nil {
err = fmt.Errorf("path [%v] is not a directory: %w", dir, commonerrors.ErrInvalid)
return nil, err
}
f, err := fs.GenericOpen(dir)
if err != nil {
return nil, err
}
files, err = fs.LlsFromOpenedDirectory(f)
_ = f.Close()
return
}
func (fs *VFS) LlsFromOpenedDirectory(dir File) ([]os.FileInfo, error) {
if dir == nil {
return nil, fmt.Errorf("%w: nil directory", commonerrors.ErrUndefined)
}
return dir.Readdir(-1)
}
func (fs *VFS) ConvertToAbsolutePath(rootPath string, paths []string) ([]string, error) {
basepath := fs.ConvertFilePath(rootPath)
converted := make([]string, 0, len(paths))
for _, path := range paths {
var abs string
if filepath.IsAbs(path) {
abs = fs.ConvertFilePath(path)
} else {
abs = fs.ConvertFilePath(filepath.Join(basepath, path))
}
converted = append(converted, abs)
}
return converted, nil
}
func (fs *VFS) ConvertToRelativePath(rootPath string, paths []string) ([]string, error) {
basepath := fs.ConvertFilePath(rootPath)
converted := make([]string, 0, len(paths))
for _, path := range paths {
relPath, err := filepath.Rel(basepath, fs.ConvertFilePath(path))
if err != nil {
return nil, err
}
converted = append(converted, relPath)
}
return converted, nil
}
// Moves a file (equivalent to mv)
func Move(src string, dest string) (err error) {
return globalFileSystem.Move(src, dest)
}
func (fs *VFS) Move(src string, dest string) (err error) {
if src == dest {
return
}
if !fs.Exists(src) {
err = fmt.Errorf("path [%v] does not exist: %w", src, commonerrors.ErrNotFound)
return
}
err = fs.MkDir(filepath.Dir(dest))
if err != nil {
return
}
err = fs.vfs.Rename(src, dest)
if err == nil {
return
}
//os.Rename() give error "invalid cross-device link" for Docker container with Volumes.
isDir, err := fs.IsDir(src)
if err != nil {
return
}
if isDir {
err = fs.moveFolder(src, dest)
} else {
err = fs.moveFile(src, dest)
}
return
}
func (fs *VFS) moveFolder(src string, dest string) (err error) {
err = fs.MkDir(dest)
if err != nil {
return
}
empty, err := fs.IsEmpty(src)
if err != nil {
return
}
if !empty {
files, err := fs.Ls(src)
if err != nil {
if IsPathNotExist(err) {
return nil
}
return err
}
for _, f := range files {
err = fs.Move(filepath.Join(src, f), filepath.Join(dest, f))
if err != nil {
return err
}
}
}
err = fs.Rm(src)
return
}
func IsPathNotExist(err error) bool {
if err == nil {
return false
}
return os.IsNotExist(err) || commonerrors.Any(err, ErrPathNotExist)
}
func (fs *VFS) moveFile(src string, dest string) (err error) {
if src == dest {
return
}
err = copyFileBetweenFS(fs, src, fs, dest)
if err != nil {
return
}
err = fs.vfs.Remove(src)
if err != nil {
return
}
return
}
func (fs *VFS) FileHash(hashAlgo string, path string) (hash string, err error) {
hasher, err := NewFileHash(hashAlgo)
if err != nil {
return
}
hash, err = hasher.CalculateFile(fs, path)
return
}
func Copy(src string, dest string) (err error) {
return globalFileSystem.Copy(src, dest)
}
func (fs *VFS) Copy(src string, dest string) (err error) {
return CopyBetweenFS(fs, src, fs, dest)
}
func MoveBetweenFS(srcFs FS, src string, destFs FS, dest string) (err error) {
if srcFs == destFs && src == dest {
return
}
err = CopyBetweenFS(srcFs, src, destFs, dest)
if err != nil {
return
}
return srcFs.Rm(src)
}
func CopyBetweenFS(srcFs FS, src string, destFs FS, dest string) (err error) {
if srcFs == destFs && src == dest {
return
}
if !srcFs.Exists(src) {
err = fmt.Errorf("path [%v] does not exist: %w", src, commonerrors.ErrNotFound)
return
}
err = destFs.MkDir(dest)
if err != nil {
return
}
isDir, err := srcFs.IsDir(src)
if err != nil {
return
}
dst := filepath.Join(dest, filepath.Base(src))
if isDir {
err = copyFolderBetweenFS(srcFs, src, destFs, dst)
} else {
err = copyFileBetweenFS(srcFs, src, destFs, dst)
}
return
}
func copyFolderBetweenFS(srcFs FS, src string, destFs FS, dest string) (err error) {
err = destFs.MkDir(dest)
if err != nil {
return
}
empty, err := srcFs.IsEmpty(src)
if err != nil {
return
}
if !empty {
files, err := srcFs.Ls(src)
if err != nil {
return err
}
for _, f := range files {
srcPath := filepath.Join(src, f)
err = CopyBetweenFS(srcFs, srcPath, destFs, dest)
if err != nil {
return err
}
}
}
return
}
func copyFileBetweenFS(srcFs FS, src string, destFs FS, dest string) (err error) {
inputFile, err := srcFs.GenericOpen(src)
if err != nil {
return
}
defer func() { _ = inputFile.Close() }()
outputFile, err := destFs.CreateFile(dest)
if err != nil {
return
}
defer func() { _ = outputFile.Close() }()
_, err = io.Copy(outputFile, inputFile)
if err != nil {
return
}
err = inputFile.Close()
if err != nil {
return
}
err = outputFile.Close()
if err != nil {
return
}
return
}
func (fs *VFS) DiskUsage(name string) (usage DiskUsage, err error) {
realPath := fs.pathConverter(name)
du, err := disk.Usage(realPath)
if err != nil {
return
}
usage = &UsageStat{
Total: du.Total,
Free: du.Free,
Used: du.Used,
UsedPercent: du.UsedPercent,
InodesTotal: du.InodesTotal,
InodesUsed: du.InodesUsed,
InodesFree: du.InodesFree,
InodesUsedPercent: du.InodesUsedPercent,
}
return
}
func GetFileSize(name string) (size int64, err error) {
return globalFileSystem.GetFileSize(name)
}
func (fs *VFS) GetFileSize(name string) (size int64, err error) {
info, err := fs.Stat(name)
if err != nil {
return
}
size = info.Size()
return
}
func Zip(source string, destination string) error {
return globalFileSystem.Zip(source, destination)
}
func (fs *VFS) Zip(source, destination string) error {
file, err := fs.CreateFile(destination)
if err != nil {
return err
}
defer func() { _ = file.Close() }()
// create a new zip archive
w := zip.NewWriter(file)
defer func() { _ = w.Close() }()
walker := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Get the relative path
relPath, err := filepath.Rel(source, path)
if err != nil {
return err
}
// If directory
if info.IsDir() {
if path == source {
return nil
}
header := &zip.FileHeader{
Name: relPath + "/",
Method: zip.Deflate,
Modified: info.ModTime(),
}
_, err = w.CreateHeader(header)
return err
}
// if file
src, err := fs.GenericOpen(path)