-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmerge.go
124 lines (111 loc) · 2.41 KB
/
merge.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
package mergefs
import (
"errors"
"io/fs"
"os"
)
// Merge filesystems
func Merge(filesystems ...fs.FS) fs.FS {
if len(filesystems) == 0 {
return mergedFS{}
}
if len(filesystems) == 1 {
return filesystems[0]
}
mfs := mergedFS{filesystems: filesystems}
var (
supportsGlob = true
supportsReadFile = true
)
for _, wfs := range filesystems {
if _, ok := wfs.(globber); !ok {
supportsGlob = false
break
}
}
for _, wfs := range filesystems {
if _, ok := wfs.(fileReader); !ok {
supportsReadFile = false
break
}
}
switch {
case supportsGlob && supportsReadFile:
return struct {
mergedFS
globber
fileReader
}{
mfs,
&globFS{mfs},
&readFileFS{mfs},
}
case supportsGlob && !supportsReadFile:
return struct {
mergedFS
globber
}{
mfs,
&globFS{mfs},
}
case !supportsGlob && supportsReadFile:
return struct {
mergedFS
fileReader
}{
mfs,
&readFileFS{mfs},
}
case !supportsGlob && !supportsReadFile:
return mfs
}
return mfs
}
// mergedFS combines filesystems. Each filesystem can serve different paths. The first FS takes precedence
type mergedFS struct {
filesystems []fs.FS
}
// Open opens the named file.
func (mfs mergedFS) Open(name string) (fs.File, error) {
for _, fs := range mfs.filesystems {
file, err := fs.Open(name)
if err == nil { // TODO should we return early when it's not an os.ErrNotExist? Should we offer options to decide this behaviour?
return file, nil
}
}
return nil, os.ErrNotExist
}
// ReadDir reads from the directory, and produces a DirEntry array of different
// directories.
//
// It iterates through all different filesystems that exist in the mfs MergeFS
// filesystem slice and it identifies overlapping directories that exist in different
// filesystems
func (mfs mergedFS) ReadDir(name string) ([]fs.DirEntry, error) {
dirsMap := make(map[string]fs.DirEntry)
notExistCount := 0
for _, filesystem := range mfs.filesystems {
dir, err := fs.ReadDir(filesystem, name)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
notExistCount++
continue
}
return nil, err
}
for _, v := range dir {
if _, ok := dirsMap[v.Name()]; !ok {
dirsMap[v.Name()] = v
}
}
continue
}
if len(mfs.filesystems) == notExistCount {
return nil, fs.ErrNotExist
}
dirs := make([]fs.DirEntry, 0, len(dirsMap))
for _, value := range dirsMap {
dirs = append(dirs, value)
}
return dirs, nil
}