-
Notifications
You must be signed in to change notification settings - Fork 1
/
unionfs.go
125 lines (106 loc) · 2.37 KB
/
unionfs.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
package main
import (
"io/fs"
"os"
)
type MergedFS struct {
priorityFs, defFs fs.FS
}
func NewMergedFS(a, b fs.FS) *MergedFS {
return &MergedFS{
priorityFs: a,
defFs: b,
}
}
type Filesystem interface {
fs.FS
fs.ReadDirFS
fs.ReadFileFS
}
func (m *MergedFS) Open(name string) (fs.File, error) {
f, e := m.priorityFs.Open(name)
if e != nil && os.IsNotExist(e) {
return m.defFs.Open(name)
}
return f, e
}
func (m *MergedFS) ReadDir(name string) ([]fs.DirEntry, error) {
results := make([]fs.DirEntry, 0)
var err error
if dirFs, ok := m.priorityFs.(fs.ReadDirFS); ok {
results, err = dirFs.ReadDir(name)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
err = nil
}
if dirFs, ok := m.defFs.(fs.ReadDirFS); ok {
secondary, err := dirFs.ReadDir(name)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
for _, v := range secondary {
inPrimary := false
for _, z := range results {
if v.Name() == z.Name() {
inPrimary = true
}
}
if !inPrimary {
results = append(results, v)
}
}
}
return results, nil
}
func (m *MergedFS) ReadFile(name string) (data []byte, err error) {
var primaryFile, secondaryFile fs.File
if readFs, ok := m.priorityFs.(fs.ReadFileFS); ok {
data, err = readFs.ReadFile(name)
if err == nil || !os.IsNotExist(err) {
return
}
} else {
//primary FS does not expose the read file endpoint. We must read it directly
primaryFile, err = m.priorityFs.Open(name)
if err != nil && !os.IsNotExist(err) {
return
}
defer primaryFile.Close()
if err == nil {
//to get the buffer... we have to make it the right size
var fi fs.FileInfo
fi, err = primaryFile.Stat()
if err != nil {
return
}
data = make([]byte, fi.Size())
_, err = primaryFile.Read(data)
return
}
}
//if we got here, primary could not fulfill request. We must do it through the default
if readFs, ok := m.defFs.(fs.ReadFileFS); ok {
data, err = readFs.ReadFile(name)
if err == nil || !os.IsNotExist(err) {
return
}
} else {
secondaryFile, err = m.defFs.Open(name)
if err != nil && !os.IsNotExist(err) {
return
}
defer secondaryFile.Close()
if err == nil {
var fi fs.FileInfo
fi, err = secondaryFile.Stat()
if err != nil {
return
}
data = make([]byte, fi.Size())
_, err = secondaryFile.Read(data)
return
}
}
return nil, os.ErrNotExist
}