-
Notifications
You must be signed in to change notification settings - Fork 23
/
fake_file_system.go
977 lines (772 loc) · 21.3 KB
/
fake_file_system.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
package fakes
import (
"bytes"
"errors"
"fmt"
"io"
"os"
gopath "path"
"path/filepath"
"sort"
"strings"
"sync"
"syscall"
"time"
gouuid "github.com/nu7hatch/gouuid"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
type FakeFileType string
type removeAllFn func(path string) error
type globFn func(pattern string) ([]string, error)
const (
FakeFileTypeFile FakeFileType = "file"
FakeFileTypeSymlink FakeFileType = "symlink"
FakeFileTypeDir FakeFileType = "dir"
)
type FakeFileSystem struct {
fileRegistry *FakeFileStatsRegistry
filesLock sync.Mutex
HomeDirUsername string
HomeDirHomePath string
ExpandPathPath string
ExpandPathExpanded string
ExpandPathErr error
openFileRegistry *FakeFileRegistry
OpenFileErr error
ReadFileError error
ReadFileWithOptsCallCount int
readFileErrorByPath map[string]error
WriteFileError error
WriteFileErrors map[string]error
WriteFileCallCount int
WriteFileQuietlyCallCount int
SymlinkError error
MkdirAllError error
mkdirAllErrorByPath map[string]error
MkdirAllCallCount int
ChangeTempRootErr error
ChownErr error
ChownCallCount int
ChmodErr error
ChmodCallCount int
CopyFileError error
CopyFileCallCount int
CopyDirError error
RenameError error
RenameOldPaths []string
RenameNewPaths []string
RemoveAllStub removeAllFn
ReadAndFollowLinkError error
ReadlinkError error
StatWithOptsCallCount int
StatCallCount int
TempFileError error
TempFileErrorsByPrefix map[string]error
ReturnTempFile boshsys.File
ReturnTempFiles []boshsys.File
ReturnTempFilesByPrefix map[string]boshsys.File
TempDirDir string
TempDirDirs []string
TempDirError error
GlobErr error
GlobStub globFn
GlobErrs map[string]error
globsMap map[string][][]string
WalkErr error
TempRootPath string
strictTempRoot bool
}
type FakeFileStats struct {
FileType FakeFileType
FileMode os.FileMode
Flags int
Username string
Groupname string
ModTime time.Time
Open bool
SymlinkTarget string
Content []byte
}
func (stats FakeFileStats) StringContents() string {
return string(stats.Content)
}
type FakeFileInfo struct {
os.FileInfo
file FakeFile
}
func (fi FakeFileInfo) Mode() os.FileMode {
return fi.file.Stats.FileMode
}
func (fi FakeFileInfo) ModTime() time.Time {
return fi.file.Stats.ModTime
}
func (fi FakeFileInfo) Size() int64 {
return int64(len(fi.file.Contents))
}
func (fi FakeFileInfo) IsDir() bool {
return fi.file.Stats.FileType == FakeFileTypeDir
}
type FakeFile struct {
path string
fs *FakeFileSystem
Stats *FakeFileStats
WriteErr error
Contents []byte
ReadErr error
ReadAtErr error
readIndex int64
CloseErr error
StatErr error
}
func NewFakeFile(path string, fs *FakeFileSystem) *FakeFile {
fakeFile := &FakeFile{
path: path,
fs: fs,
}
me := fs.fileRegistry.Get(path)
if me != nil {
fakeFile.Contents = me.Content
fakeFile.Stats = me
fakeFile.Stats.Open = true
}
return fakeFile
}
func (f *FakeFile) Name() string {
return f.path
}
func (f *FakeFile) Write(contents []byte) (int, error) {
if f.WriteErr != nil {
return 0, f.WriteErr
}
f.fs.filesLock.Lock()
defer f.fs.filesLock.Unlock()
stats := f.fs.getOrCreateFile(f.path)
stats.Content = contents
f.Contents = contents
return len(contents), nil
}
func (f *FakeFile) Read(b []byte) (int, error) {
if f.readIndex >= int64(len(f.Contents)) {
return 0, io.EOF
}
copy(b, f.Contents)
f.readIndex = int64(len(f.Contents))
return len(f.Contents), f.ReadErr
}
func (f *FakeFile) ReadAt(b []byte, offset int64) (int, error) {
copy(b, f.Contents[offset:])
return len(f.Contents[offset:]), f.ReadAtErr
}
func (f *FakeFile) WriteAt(b []byte, offset int64) (int, error) {
return len(b), nil
}
func (f *FakeFile) Seek(int64, int) (int64, error) {
return 0, nil
}
func (f *FakeFile) Close() error {
if f.Stats != nil {
f.Stats.Open = false
}
return f.CloseErr
}
func (f FakeFile) Stat() (os.FileInfo, error) {
return FakeFileInfo{file: f}, f.StatErr
}
func NewFakeFileSystem() *FakeFileSystem {
return &FakeFileSystem{
fileRegistry: NewFakeFileStatsRegistry(),
openFileRegistry: NewFakeFileRegistry(),
GlobErrs: map[string]error{},
globsMap: map[string][][]string{},
readFileErrorByPath: map[string]error{},
mkdirAllErrorByPath: map[string]error{},
WriteFileErrors: map[string]error{},
TempFileErrorsByPrefix: map[string]error{},
}
}
func (fs *FakeFileSystem) GetFileTestStat(path string) *FakeFileStats {
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
return fs.fileRegistry.Get(path)
}
func (fs *FakeFileSystem) HomeDir(username string) (string, error) {
fs.HomeDirUsername = username
return fs.HomeDirHomePath, nil
}
func (fs *FakeFileSystem) ExpandPath(path string) (string, error) {
fs.ExpandPathPath = path
if fs.ExpandPathExpanded == "" {
return fs.ExpandPathPath, fs.ExpandPathErr
}
return fs.ExpandPathExpanded, fs.ExpandPathErr
}
func (fs *FakeFileSystem) RegisterMkdirAllError(path string, err error) {
path = gopath.Join(path)
if _, ok := fs.mkdirAllErrorByPath[path]; ok {
panic(fmt.Sprintf("MkdirAll error is already set for path: %s", path))
}
fs.mkdirAllErrorByPath[path] = err
}
func (fs *FakeFileSystem) MkdirAll(path string, perm os.FileMode) error {
fs.MkdirAllCallCount++
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
if fs.MkdirAllError != nil {
return fs.MkdirAllError
}
path = gopath.Join(path)
if fs.mkdirAllErrorByPath[path] != nil {
return fs.mkdirAllErrorByPath[path]
}
stats := fs.getOrCreateFile(path)
stats.FileMode = perm
stats.FileType = FakeFileTypeDir
fs.fileRegistry.Register(path, stats)
return nil
}
func (fs *FakeFileSystem) RegisterOpenFile(path string, file *FakeFile) {
path = gopath.Join(path)
fs.openFileRegistry.Register(path, file)
}
func (fs *FakeFileSystem) FindFileStats(path string) (*FakeFileStats, error) {
if stats := fs.fileRegistry.Get(path); stats != nil {
return stats, nil
}
return nil, fmt.Errorf("Path does not exist: %s", path)
}
func (fs *FakeFileSystem) OpenFile(path string, flag int, perm os.FileMode) (boshsys.File, error) {
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
if fs.OpenFileErr != nil {
return nil, fs.OpenFileErr
}
// Make sure to record a reference for FileExist, etc. to work
stats := fs.getOrCreateFile(path)
stats.FileMode = perm
stats.Flags = flag
stats.FileType = FakeFileTypeFile
openFile := fs.openFileRegistry.Get(path)
if openFile != nil {
return openFile, nil
}
file := NewFakeFile(path, fs)
fs.RegisterOpenFile(path, file)
return file, nil
}
func (fs *FakeFileSystem) Stat(path string) (os.FileInfo, error) {
fs.StatCallCount++
return fs.StatHelper(path)
}
func (fs *FakeFileSystem) StatWithOpts(path string, opts boshsys.StatOpts) (os.FileInfo, error) {
fs.StatWithOptsCallCount++
return fs.StatHelper(path)
}
func (fs *FakeFileSystem) StatHelper(path string) (os.FileInfo, error) {
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
openFile := fs.openFileRegistry.Get(path)
if openFile != nil {
return openFile.Stat()
}
stats := fs.fileRegistry.Get(path)
if stats == nil {
panic(fmt.Sprintf("Unexpected Stat call for path '%s' that does not exist", path))
}
if stats.FileType == FakeFileTypeSymlink {
targetStats := fs.fileRegistry.Get(stats.SymlinkTarget)
if targetStats == nil {
return nil, fmt.Errorf("stat: %s: no such file or directory", path)
}
stats = targetStats
}
return NewFakeFile(path, fs).Stat()
}
func (fs *FakeFileSystem) Readlink(path string) (string, error) {
if fs.ReadlinkError != nil {
return "", fs.ReadlinkError
}
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
stats := fs.fileRegistry.Get(path)
if stats == nil {
return "", errors.New(fmt.Sprintf("path '%s' does not exist", path))
}
if stats.FileType != FakeFileTypeSymlink {
return "", errors.New(fmt.Sprintf("cannot readlink of non-symlink"))
}
return stats.SymlinkTarget, nil
}
func (fs *FakeFileSystem) Lstat(path string) (os.FileInfo, error) {
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
openFile := fs.openFileRegistry.Get(path)
if openFile != nil {
return openFile.Stat()
}
stats := fs.fileRegistry.Get(path)
if stats == nil {
panic(fmt.Sprintf("Unexpected Stat call for path '%s' that does not exist", path))
}
return NewFakeFile(path, fs).Stat()
}
func (fs *FakeFileSystem) Chown(path, username string) error {
fs.ChownCallCount++
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
// check early to avoid requiring file presence
if fs.ChownErr != nil {
return fs.ChownErr
}
stats := fs.fileRegistry.Get(path)
if stats == nil {
return fmt.Errorf("Path does not exist: %s", path)
}
parts := strings.Split(username, ":")
stats.Username = parts[0]
stats.Groupname = parts[0]
if len(parts) > 1 {
stats.Groupname = parts[1]
}
return nil
}
func (fs *FakeFileSystem) Chmod(path string, perm os.FileMode) error {
fs.ChmodCallCount++
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
// check early to avoid requiring file presence
if fs.ChmodErr != nil {
return fs.ChmodErr
}
stats := fs.fileRegistry.Get(path)
if stats == nil {
return fmt.Errorf("Path does not exist: %s", path)
}
stats.FileMode = perm
return nil
}
func (fs *FakeFileSystem) WriteFileString(path, content string) error {
return fs.WriteFile(path, []byte(content))
}
func (fs *FakeFileSystem) WriteFileQuietly(path string, content []byte) error {
fs.WriteFileQuietlyCallCount++
return fs.writeFile(path, content)
}
func (fs *FakeFileSystem) WriteFile(path string, content []byte) error {
fs.WriteFileCallCount++
return fs.writeFile(path, content)
}
func (fs *FakeFileSystem) writeFile(path string, content []byte) error {
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
err := fs.WriteFileError
if err != nil {
return err
}
err = fs.WriteFileErrors[path]
if err != nil {
return err
}
path = fs.fileRegistry.UnifiedPath(path)
parent := gopath.Dir(path)
if parent != "." {
fs.writeDir(parent)
}
stats := fs.getOrCreateFile(path)
stats.FileType = FakeFileTypeFile
stats.Content = content
return nil
}
func (fs *FakeFileSystem) writeDir(path string) error {
parent := gopath.Dir(path)
grandparent := gopath.Dir(parent)
if grandparent != parent {
fs.writeDir(parent)
}
stats := fs.getOrCreateFile(path)
stats.FileType = FakeFileTypeDir
return nil
}
func (fs *FakeFileSystem) ConvergeFileContents(path string, content []byte, opts ...boshsys.ConvergeFileContentsOpts) (bool, error) {
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
if fs.WriteFileError != nil {
return false, fs.WriteFileError
}
err := fs.WriteFileErrors[path]
if err != nil {
return false, err
}
if len(opts) > 0 && opts[0].DryRun {
stats := fs.fileRegistry.Get(path)
if stats == nil {
return true, nil
}
return bytes.Compare(stats.Content, content) != 0, nil
}
stats := fs.getOrCreateFile(path)
stats.FileType = FakeFileTypeFile
if bytes.Compare(stats.Content, content) != 0 {
stats.Content = content
return true, nil
}
return false, nil
}
func (fs *FakeFileSystem) ReadFileString(path string) (string, error) {
bytes, err := fs.ReadFile(path)
if err != nil {
return "", err
}
return string(bytes), nil
}
func (fs *FakeFileSystem) RegisterReadFileError(path string, err error) {
if _, ok := fs.readFileErrorByPath[path]; ok {
panic(fmt.Sprintf("ReadFile error is already set for path: %s", path))
}
fs.readFileErrorByPath[path] = err
}
func (fs *FakeFileSystem) UnregisterReadFileError(path string) {
delete(fs.readFileErrorByPath, path)
}
func (fs *FakeFileSystem) ReadFileWithOpts(path string, opts boshsys.ReadOpts) ([]byte, error) {
fs.ReadFileWithOptsCallCount++
return fs.ReadFile(path)
}
func (fs *FakeFileSystem) ReadFile(path string) ([]byte, error) {
stats := fs.GetFileTestStat(path)
if stats != nil {
if fs.ReadFileError != nil {
return nil, fs.ReadFileError
}
if fs.readFileErrorByPath[path] != nil {
return nil, fs.readFileErrorByPath[path]
}
return stats.Content, nil
}
return nil, bosherr.ComplexError{
Err: bosherr.Error("Not found"),
Cause: &os.PathError{
Op: "open",
Path: path,
Err: syscall.ENOENT,
},
}
}
func (fs *FakeFileSystem) FileExists(path string) bool {
return fs.GetFileTestStat(path) != nil
}
func (fs *FakeFileSystem) Rename(oldPath, newPath string) error {
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
if fs.RenameError != nil {
return fs.RenameError
}
oldPath = fs.fileRegistry.UnifiedPath(oldPath)
newPath = fs.fileRegistry.UnifiedPath(newPath)
parentDir := gopath.Dir(newPath)
if parentDir != "." && fs.fileRegistry.Get(parentDir) == nil {
return errors.New("Parent directory does not exist")
}
stats := fs.fileRegistry.Get(oldPath)
if stats == nil {
return errors.New("Old path did not exist")
}
fs.RenameOldPaths = append(fs.RenameOldPaths, oldPath)
fs.RenameNewPaths = append(fs.RenameNewPaths, newPath)
newStats := fs.getOrCreateFile(newPath)
newStats.Content = stats.Content
newStats.FileMode = stats.FileMode
newStats.FileType = stats.FileType
newStats.Username = stats.Username
newStats.Groupname = stats.Groupname
newStats.Flags = stats.Flags
// Ignore error from RemoveAll
fs.removeAll(oldPath)
return nil
}
func (fs *FakeFileSystem) Symlink(oldPath, newPath string) (err error) {
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
if fs.SymlinkError == nil {
stats := fs.getOrCreateFile(newPath)
stats.FileMode |= os.ModeSymlink
stats.FileType = FakeFileTypeSymlink
stats.SymlinkTarget = fs.fileRegistry.UnifiedPath(oldPath)
return
}
err = fs.SymlinkError
return
}
func (fs *FakeFileSystem) ReadAndFollowLink(symlinkPath string) (string, error) {
if fs.ReadAndFollowLinkError != nil {
return "", fs.ReadAndFollowLinkError
}
if symlinkPath == "" ||
symlinkPath == "/" ||
symlinkPath == filepath.VolumeName(symlinkPath)+"\\" {
return symlinkPath, nil
}
if symlinkPath == "." {
return fs.fileRegistry.UnifiedPath("."), nil
}
symlinkPath = filepath.Join(symlinkPath)
stat := fs.GetFileTestStat(symlinkPath)
if stat == nil {
return "", os.ErrNotExist
}
if stat.FileType != FakeFileTypeSymlink {
dirPath, err := fs.ReadAndFollowLink(filepath.Dir(symlinkPath))
if err != nil {
return "", err
}
return filepath.Join(dirPath, filepath.Base(symlinkPath)), nil
}
if gopath.IsAbs(stat.SymlinkTarget) {
return fs.ReadAndFollowLink(stat.SymlinkTarget)
}
dirPath, err := fs.ReadAndFollowLink(filepath.Dir(symlinkPath))
if err != nil {
return "", err
}
return fs.ReadAndFollowLink(filepath.Join(dirPath, stat.SymlinkTarget))
}
func (fs *FakeFileSystem) CopyFile(srcPath, dstPath string) error {
fs.CopyFileCallCount++
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
if fs.CopyFileError != nil {
return fs.CopyFileError
}
srcFile := fs.fileRegistry.Get(srcPath)
if srcFile == nil {
return errors.New(fmt.Sprintf("%s doesn't exist", srcPath))
}
fs.fileRegistry.Register(dstPath, srcFile)
return nil
}
func (fs *FakeFileSystem) CopyDir(srcPath, dstPath string) error {
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
if fs.CopyDirError != nil {
return fs.CopyDirError
}
srcPath = fs.fileRegistry.UnifiedPath(srcPath) + "/"
dstPath = fs.fileRegistry.UnifiedPath(dstPath)
for filePath, fileStats := range fs.fileRegistry.GetAll() {
if strings.HasPrefix(filePath, srcPath) {
dstPath := gopath.Join(dstPath, filePath[len(srcPath)-1:])
fs.fileRegistry.Register(dstPath, fileStats)
}
}
return nil
}
func (fs *FakeFileSystem) ChangeTempRoot(tempRootPath string) error {
if fs.ChangeTempRootErr != nil {
return fs.ChangeTempRootErr
}
fs.TempRootPath = tempRootPath
return nil
}
func (fs *FakeFileSystem) EnableStrictTempRootBehavior() {
fs.strictTempRoot = true
}
func (fs *FakeFileSystem) TempFile(prefix string) (file boshsys.File, err error) {
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
if fs.TempFileError != nil {
return nil, fs.TempFileError
}
if fs.TempFileErrorsByPrefix[prefix] != nil {
return nil, fs.TempFileErrorsByPrefix[prefix]
}
if fs.strictTempRoot && fs.TempRootPath == "" {
return nil, errors.New("Temp file was requested without having set a temp root")
}
if fs.ReturnTempFilesByPrefix != nil {
file = fs.ReturnTempFilesByPrefix[prefix]
} else if fs.ReturnTempFile != nil {
file = fs.ReturnTempFile
} else if len(fs.ReturnTempFiles) != 0 {
file = fs.ReturnTempFiles[0]
fs.ReturnTempFiles = fs.ReturnTempFiles[1:]
} else {
file, err = os.Open(os.DevNull)
if err != nil {
err = bosherr.WrapError(err, fmt.Sprintf("Opening %s", os.DevNull))
return
}
}
// Make sure to record a reference for FileExist, etc. to work
stats := fs.getOrCreateFile(file.Name())
stats.FileType = FakeFileTypeFile
return
}
func (fs *FakeFileSystem) TempDir(prefix string) (string, error) {
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
if fs.TempDirError != nil {
return "", fs.TempDirError
}
if fs.strictTempRoot && fs.TempRootPath == "" {
return "", errors.New("Temp file was requested without having set a temp root")
}
var path string
if len(fs.TempDirDir) > 0 {
path = fs.TempDirDir
} else if fs.TempDirDirs != nil {
if len(fs.TempDirDirs) == 0 {
return "", errors.New("Failed to create new temp dir: TempDirDirs is empty")
}
path = fs.TempDirDirs[0]
fs.TempDirDirs = fs.TempDirDirs[1:]
} else {
uuid, err := gouuid.NewV4()
if err != nil {
return "", err
}
path = uuid.String()
}
// Make sure to record a reference for FileExist, etc. to work
stats := fs.getOrCreateFile(path)
stats.FileType = FakeFileTypeDir
return path, nil
}
func (fs *FakeFileSystem) RemoveAll(path string) error {
if path == "" {
panic("RemoveAll requires path")
}
if fs.RemoveAllStub != nil {
err := fs.RemoveAllStub(path)
if err != nil {
return err
}
}
fs.filesLock.Lock()
defer fs.filesLock.Unlock()
path = fs.fileRegistry.UnifiedPath(path)
return fs.removeAll(path)
}
func (fs *FakeFileSystem) removeAll(path string) error {
fileInfo := fs.fileRegistry.Get(path)
if fileInfo != nil {
fs.fileRegistry.Remove(path)
if fileInfo.FileType != FakeFileTypeDir {
return nil
}
}
// path must be a dir
path = path + "/"
filesToRemove := []string{}
for name := range fs.fileRegistry.GetAll() {
if strings.HasPrefix(name, path) {
filesToRemove = append(filesToRemove, name)
}
}
for _, name := range filesToRemove {
fs.fileRegistry.Remove(name)
}
return nil
}
func (fs *FakeFileSystem) Glob(pattern string) (matches []string, err error) {
if fs.GlobStub != nil {
matches, err = fs.GlobStub(pattern)
if err != nil {
return nil, err
} else {
return matches, nil
}
}
remainingMatches, found := fs.globsMap[pattern]
if found {
matches = remainingMatches[0]
if len(remainingMatches) > 1 {
fs.globsMap[pattern] = remainingMatches[1:]
}
} else {
matches = []string{}
}
if err, ok := fs.GlobErrs[pattern]; ok {
return matches, err
}
return matches, fs.GlobErr
}
func (fs *FakeFileSystem) RecursiveGlob(pattern string) (matches []string, err error) {
return fs.Glob(pattern)
}
func (fs *FakeFileSystem) Walk(root string, walkFunc filepath.WalkFunc) error {
if fs.WalkErr != nil {
return walkFunc("", nil, fs.WalkErr)
}
var paths []string
for path := range fs.fileRegistry.GetAll() {
paths = append(paths, path)
}
sort.Strings(paths)
root = gopath.Join(root) + "/"
for _, path := range paths {
fileStats := fs.fileRegistry.Get(path)
if strings.HasPrefix(path, root) {
fakeFile := NewFakeFile(path, fs)
fakeFile.Stats = fileStats
fileInfo, _ := fakeFile.Stat()
err := walkFunc(path, fileInfo, nil)
if err != nil {
return err
}
}
}
return nil
}
func (fs *FakeFileSystem) SetGlob(pattern string, matches ...[]string) {
fs.globsMap[pattern] = matches
}
func (fs *FakeFileSystem) getOrCreateFile(path string) *FakeFileStats {
stats := fs.fileRegistry.Get(path)
if stats == nil {
stats = new(FakeFileStats)
fs.fileRegistry.Register(path, stats)
}
return stats
}
type FakeFileStatsRegistry struct {
files map[string]*FakeFileStats
}
func NewFakeFileStatsRegistry() *FakeFileStatsRegistry {
return &FakeFileStatsRegistry{
files: map[string]*FakeFileStats{},
}
}
func (fsr *FakeFileStatsRegistry) Register(path string, stats *FakeFileStats) {
fsr.files[fsr.UnifiedPath(path)] = stats
}
func (fsr *FakeFileStatsRegistry) Get(path string) *FakeFileStats {
return fsr.files[fsr.UnifiedPath(path)]
}
func (fsr *FakeFileStatsRegistry) GetAll() map[string]*FakeFileStats {
return fsr.files
}
func (fsr *FakeFileStatsRegistry) Remove(path string) {
delete(fsr.files, fsr.UnifiedPath(path))
}
func (fsr *FakeFileStatsRegistry) UnifiedPath(path string) string {
path = strings.TrimPrefix(path, filepath.VolumeName(path))
return filepath.ToSlash(gopath.Join(path))
}
type FakeFileRegistry struct {
files map[string]*FakeFile
}
func NewFakeFileRegistry() *FakeFileRegistry {
return &FakeFileRegistry{
files: map[string]*FakeFile{},
}
}
func (ffr *FakeFileRegistry) Register(path string, file *FakeFile) {
ffr.files[ffr.UnifiedPath(path)] = file
}
func (ffr *FakeFileRegistry) Get(path string) *FakeFile {
return ffr.files[ffr.UnifiedPath(path)]
}
func (ffr *FakeFileRegistry) UnifiedPath(path string) string {
path = strings.TrimPrefix(path, filepath.VolumeName(path))
return filepath.ToSlash(gopath.Join(path))
}