Debian Codegraph @

memfs/memory.go

raw symbols SCIP
1 // Package memfs provides a billy filesystem backed by memory.
2 //
3 // Filesystems created by this package are ephemeral and process-local: data is
4 // not persisted and disappears when the filesystem is discarded or the process
5 // exits. memfs is useful for tests and temporary data, but is not a persistence
6 // layer.
7 package memfs // import "github.com/go-git/go-billy/v6/memfs"
8
9 import (
10 "errors"
11 "fmt"
12 gofs "io/fs"
13 "log"
14 "os"
15 "path/filepath"
16 "runtime"
17 "sort"
18 "strings"
19 "syscall"
20
21 "github.com/go-git/go-billy/v6"
22 "github.com/go-git/go-billy/v6/helper/chroot"
23 "github.com/go-git/go-billy/v6/util"
24 )
25
26 const (
27 separator = filepath.Separator
28 defaultUmask = 0o022
29 defaultDirMode = 0o777
30 defaultFileMode = 0o666
31 )
32
33 // Memory is a convenient filesystem based on memory files.
34 //
35 // All filesystem data is loaded into memory. Users should ensure enough memory
36 // is available for the data they intend to store.
37 type Memory struct {
38 s *storage
39 umask uint32
40 }
41
42 // New returns a new Memory filesystem.
43 //
44 // The returned value is a billy.Filesystem wrapped with the chroot helper, not
45 // the raw *Memory implementation.
46 func New(opts ...Option) billy.Filesystem {
47 o := &options{}
48 // Aligns default umask with general Windows behaviour.
49 if runtime.GOOS != "windows" {
50 o.umask = defaultUmask
51 }
52
53 for _, opt := range opts {
54 opt(o)
55 }
56
57 fs := &Memory{
58 s: newStorage(),
59 umask: o.umask,
60 }
61 _, err := fs.s.New("/", fs.applyUmask(defaultDirMode)|os.ModeDir, 0)
62 if err != nil {
63 log.Printf("failed to create root dir: %v", err)
64 }
65 return chroot.New(fs, string(separator))
66 }
67
68 func (fs *Memory) Create(filename string) (billy.File, error) {
69 return fs.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, defaultFileMode)
70 }
71
72 func (fs *Memory) Open(filename string) (billy.File, error) {
73 return fs.OpenFile(filename, os.O_RDONLY, 0)
74 }
75
76 func (fs *Memory) OpenFile(filename string, flag int, perm gofs.FileMode) (billy.File, error) {
77 f, has := fs.s.Get(filename)
78 if !has {
79 if !isCreate(flag) {
80 return nil, os.ErrNotExist
81 }
82
83 var err error
84 f, err = fs.s.New(filename, fs.applyUmask(perm), flag)
85 if err != nil {
86 return nil, err
87 }
88 } else {
89 if isExclusive(flag) {
90 return nil, os.ErrExist
91 }
92
93 if target, isLink := fs.resolveLink(filename, f); isLink {
94 if target != filename {
95 return fs.OpenFile(target, flag, perm)
96 }
97 }
98 }
99
100 if f.mode.IsDir() {
101 return nil, fmt.Errorf("cannot open directory: %s", filename)
102 }
103
104 return f.Duplicate(filename, perm, flag), nil
105 }
106
107 func (fs *Memory) resolveLink(fullpath string, f *file) (target string, isLink bool) {
108 if !isSymlink(f.mode) {
109 return fullpath, false
110 }
111
112 target = string(f.content.bytes)
113 if !isAbs(target) {
114 target = fs.Join(filepath.Dir(fullpath), target)
115 }
116
117 return target, true
118 }
119
120 // On Windows OS, IsAbs validates if a path is valid based on if stars with a
121 // unit (eg.: `C:\`) to assert that is absolute, but in this mem implementation
122 // any path starting by `separator` is also considered absolute.
123 func isAbs(path string) bool {
124 return filepath.IsAbs(path) || strings.HasPrefix(path, string(separator))
125 }
126
127 func (fs *Memory) Stat(filename string) (os.FileInfo, error) {
128 f, has := fs.s.Get(filename)
129 if !has {
130 return nil, os.ErrNotExist
131 }
132
133 fi, _ := f.Stat()
134
135 var err error
136 if target, isLink := fs.resolveLink(filename, f); isLink {
137 fi, err = fs.Stat(target)
138 if err != nil {
139 return nil, err
140 }
141 }
142
143 // the name of the file should always the name of the stated file, so we
144 // overwrite the Stat returned from the storage with it, since the
145 // filename may belong to a link.
146 if ffi, ok := fi.(*fileInfo); ok {
147 ffi.name = filepath.Base(filename)
148 }
149 return fi, nil
150 }
151
152 func (fs *Memory) Lstat(filename string) (os.FileInfo, error) {
153 f, has := fs.s.Get(filename)
154 if !has {
155 return nil, os.ErrNotExist
156 }
157
158 return f.Stat()
159 }
160
161 type ByName []gofs.DirEntry
162
163 func (a ByName) Len() int { return len(a) }
164 func (a ByName) Less(i, j int) bool { return a[i].Name() < a[j].Name() }
165 func (a ByName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
166
167 func (fs *Memory) ReadDir(path string) ([]gofs.DirEntry, error) {
168 if f, has := fs.s.Get(path); has {
169 if target, isLink := fs.resolveLink(path, f); isLink {
170 if target != path {
171 return fs.ReadDir(target)
172 }
173 }
174 } else {
175 return nil, &os.PathError{Op: "open", Path: path, Err: syscall.ENOENT}
176 }
177
178 var entries []gofs.DirEntry
179 for _, f := range fs.s.Children(path) {
180 fi, _ := f.Stat()
181 entries = append(entries, gofs.FileInfoToDirEntry(fi))
182 }
183
184 sort.Sort(ByName(entries))
185
186 return entries, nil
187 }
188
189 func (fs *Memory) MkdirAll(path string, perm gofs.FileMode) error {
190 _, err := fs.s.New(path, fs.applyUmask(perm)|os.ModeDir, 0)
191 return err
192 }
193
194 func (fs *Memory) TempFile(dir, prefix string) (billy.File, error) {
195 return util.TempFile(fs, dir, prefix)
196 }
197
198 func (fs *Memory) Rename(from, to string) error {
199 return fs.s.Rename(from, to)
200 }
201
202 func (fs *Memory) Remove(filename string) error {
203 return fs.s.Remove(filename)
204 }
205
206 func (fs *Memory) Chmod(path string, mode gofs.FileMode) error {
207 return fs.s.Chmod(path, mode)
208 }
209
210 // Falls back to Go's filepath.Join, which works differently depending on the
211 // OS where the code is being executed.
212 func (fs *Memory) Join(elem ...string) string {
213 return filepath.Join(elem...)
214 }
215
216 // Symlink creates link with target stored as provided. The target may point to
217 // a missing path.
218 func (fs *Memory) Symlink(target, link string) error {
219 _, err := fs.Lstat(link)
220 if err == nil {
221 return os.ErrExist
222 }
223
224 if !errors.Is(err, os.ErrNotExist) {
225 return err
226 }
227
228 return util.WriteFile(fs, link, []byte(target), 0o777|os.ModeSymlink)
229 }
230
231 // Readlink returns the target stored for link without resolving it.
232 func (fs *Memory) Readlink(link string) (string, error) {
233 f, has := fs.s.Get(link)
234 if !has {
235 return "", os.ErrNotExist
236 }
237
238 if !isSymlink(f.mode) {
239 return "", &os.PathError{
240 Op: "readlink",
241 Path: link,
242 Err: fmt.Errorf("not a symlink"),
243 }
244 }
245
246 return string(f.content.bytes), nil
247 }
248
249 // Capabilities implements the Capable interface.
250 func (fs *Memory) Capabilities() billy.Capability {
251 return billy.WriteCapability |
252 billy.ReadCapability |
253 billy.ReadAndWriteCapability |
254 billy.SeekCapability |
255 billy.TruncateCapability
256 }
257
258 // applyUmask applies the filesystem's umask to a mode by clearing the bits
259 // specified in the umask. For example, with umask 0o022, the mode 0o666
260 // becomes 0o644 (rw-r--r--).
261 func (fs *Memory) applyUmask(mode gofs.FileMode) gofs.FileMode {
262 return mode &^ gofs.FileMode(fs.umask)
263 }
264
265 func (c *content) Truncate() {
266 c.bytes = make([]byte, 0)
267 }
268
269 func (c *content) Len() int {
270 return len(c.bytes)
271 }
272
273 func isCreate(flag int) bool {
274 return flag&os.O_CREATE != 0
275 }
276
277 func isExclusive(flag int) bool {
278 return flag&os.O_EXCL != 0
279 }
280
281 func isAppend(flag int) bool {
282 return flag&os.O_APPEND != 0
283 }
284
285 func isTruncate(flag int) bool {
286 return flag&os.O_TRUNC != 0
287 }
288
289 func isReadAndWrite(flag int) bool {
290 return flag&os.O_RDWR != 0
291 }
292
293 func isReadOnly(flag int) bool {
294 return flag == os.O_RDONLY
295 }
296
297 func isWriteOnly(flag int) bool {
298 return flag&os.O_WRONLY != 0
299 }
300
301 func isSymlink(m gofs.FileMode) bool {
302 return m&os.ModeSymlink != 0
303 }