Debian Codegraph @

txtar/fs.go

raw symbols SCIP
1 // Copyright 2024 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package txtar
6
7 import (
8 "errors"
9 "fmt"
10 "io"
11 "io/fs"
12 "path"
13 "slices"
14 "time"
15 )
16
17 // FS returns the file system form of an Archive.
18 // It returns an error if any of the file names in the archive
19 // are not valid file system names.
20 // The archive must not be modified while the FS is in use.
21 //
22 // If the file system detects that it has been modified, calls to the
23 // file system return an ErrModified error.
24 func FS(a *Archive) (fs.FS, error) {
25 // Create a filesystem with a root directory.
26 root := &node{fileinfo: fileinfo{path: ".", mode: readOnlyDir}}
27 fsys := &filesystem{a, map[string]*node{root.path: root}}
28
29 if err := initFiles(fsys); err != nil {
30 return nil, fmt.Errorf("cannot create fs.FS from txtar.Archive: %s", err)
31 }
32 return fsys, nil
33 }
34
35 const (
36 readOnly fs.FileMode = 0o444 // read only mode
37 readOnlyDir = readOnly | fs.ModeDir
38 )
39
40 // ErrModified indicates that file system returned by FS
41 // noticed that the underlying archive has been modified
42 // since the call to FS. Detection of modification is best effort,
43 // to help diagnose misuse of the API, and is not guaranteed.
44 var ErrModified error = errors.New("txtar.Archive has been modified during txtar.FS")
45
46 // A filesystem is a simple in-memory file system for txtar archives,
47 // represented as a map from valid path names to information about the
48 // files or directories they represent.
49 //
50 // File system operations are read only. Modifications to the underlying
51 // *Archive may race. To help prevent this, the filesystem tries
52 // to detect modification during Open and return ErrModified if it
53 // is able to detect a modification.
54 type filesystem struct {
55 ar *Archive
56 nodes map[string]*node
57 }
58
59 // node is a file or directory in the tree of a filesystem.
60 type node struct {
61 fileinfo // fs.FileInfo and fs.DirEntry implementation
62 idx int // index into ar.Files (for files)
63 entries []fs.DirEntry // subdirectories and files (for directories)
64 }
65
66 var _ fs.FS = (*filesystem)(nil)
67 var _ fs.DirEntry = (*node)(nil)
68
69 // initFiles initializes fsys from fsys.ar.Files. Returns an error if there are any
70 // invalid file names or collisions between file or directories.
71 func initFiles(fsys *filesystem) error {
72 for idx, file := range fsys.ar.Files {
73 name := file.Name
74 if !fs.ValidPath(name) {
75 return fmt.Errorf("file %q is an invalid path", name)
76 }
77
78 n := &node{idx: idx, fileinfo: fileinfo{path: name, size: len(file.Data), mode: readOnly}}
79 if err := insert(fsys, n); err != nil {
80 return err
81 }
82 }
83 return nil
84 }
85
86 // insert adds node n as an entry to its parent directory within the filesystem.
87 func insert(fsys *filesystem, n *node) error {
88 if m := fsys.nodes[n.path]; m != nil {
89 return fmt.Errorf("duplicate path %q", n.path)
90 }
91 fsys.nodes[n.path] = n
92
93 // fsys.nodes contains "." to prevent infinite loops.
94 parent, err := directory(fsys, path.Dir(n.path))
95 if err != nil {
96 return err
97 }
98 parent.entries = append(parent.entries, n)
99 return nil
100 }
101
102 // directory returns the directory node with the path dir and lazily-creates it
103 // if it does not exist.
104 func directory(fsys *filesystem, dir string) (*node, error) {
105 if m := fsys.nodes[dir]; m != nil && m.IsDir() {
106 return m, nil // pre-existing directory
107 }
108
109 n := &node{fileinfo: fileinfo{path: dir, mode: readOnlyDir}}
110 if err := insert(fsys, n); err != nil {
111 return nil, err
112 }
113 return n, nil
114 }
115
116 // dataOf returns the data associated with the file t.
117 // May return ErrModified if fsys.ar has been modified.
118 func dataOf(fsys *filesystem, n *node) ([]byte, error) {
119 if n.idx >= len(fsys.ar.Files) {
120 return nil, ErrModified
121 }
122
123 f := fsys.ar.Files[n.idx]
124 if f.Name != n.path || len(f.Data) != n.size {
125 return nil, ErrModified
126 }
127 return f.Data, nil
128 }
129
130 func (fsys *filesystem) Open(name string) (fs.File, error) {
131 if !fs.ValidPath(name) {
132 return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrInvalid}
133 }
134
135 n := fsys.nodes[name]
136 switch {
137 case n == nil:
138 return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist}
139 case n.IsDir():
140 return &openDir{fileinfo: n.fileinfo, entries: n.entries}, nil
141 default:
142 data, err := dataOf(fsys, n)
143 if err != nil {
144 return nil, err
145 }
146 return &openFile{fileinfo: n.fileinfo, data: data}, nil
147 }
148 }
149
150 func (fsys *filesystem) ReadFile(name string) ([]byte, error) {
151 file, err := fsys.Open(name)
152 if err != nil {
153 return nil, err
154 }
155 if file, ok := file.(*openFile); ok {
156 return slices.Clone(file.data), nil
157 }
158 return nil, &fs.PathError{Op: "read", Path: name, Err: fs.ErrInvalid}
159 }
160
161 // A fileinfo implements fs.FileInfo and fs.DirEntry for a given archive file.
162 type fileinfo struct {
163 path string // unique path to the file or directory within a filesystem
164 size int
165 mode fs.FileMode
166 }
167
168 var _ fs.FileInfo = (*fileinfo)(nil)
169 var _ fs.DirEntry = (*fileinfo)(nil)
170
171 func (i *fileinfo) Name() string { return path.Base(i.path) }
172 func (i *fileinfo) Size() int64 { return int64(i.size) }
173 func (i *fileinfo) Mode() fs.FileMode { return i.mode }
174 func (i *fileinfo) Type() fs.FileMode { return i.mode.Type() }
175 func (i *fileinfo) ModTime() time.Time { return time.Time{} }
176 func (i *fileinfo) IsDir() bool { return i.mode&fs.ModeDir != 0 }
177 func (i *fileinfo) Sys() any { return nil }
178 func (i *fileinfo) Info() (fs.FileInfo, error) { return i, nil }
179
180 // An openFile is a regular (non-directory) fs.File open for reading.
181 type openFile struct {
182 fileinfo
183 data []byte
184 offset int64
185 }
186
187 var _ fs.File = (*openFile)(nil)
188
189 func (f *openFile) Stat() (fs.FileInfo, error) { return &f.fileinfo, nil }
190 func (f *openFile) Close() error { return nil }
191 func (f *openFile) Read(b []byte) (int, error) {
192 if f.offset >= int64(len(f.data)) {
193 return 0, io.EOF
194 }
195 if f.offset < 0 {
196 return 0, &fs.PathError{Op: "read", Path: f.path, Err: fs.ErrInvalid}
197 }
198 n := copy(b, f.data[f.offset:])
199 f.offset += int64(n)
200 return n, nil
201 }
202
203 func (f *openFile) Seek(offset int64, whence int) (int64, error) {
204 switch whence {
205 case 0:
206 // offset += 0
207 case 1:
208 offset += f.offset
209 case 2:
210 offset += int64(len(f.data))
211 }
212 if offset < 0 || offset > int64(len(f.data)) {
213 return 0, &fs.PathError{Op: "seek", Path: f.path, Err: fs.ErrInvalid}
214 }
215 f.offset = offset
216 return offset, nil
217 }
218
219 func (f *openFile) ReadAt(b []byte, offset int64) (int, error) {
220 if offset < 0 || offset > int64(len(f.data)) {
221 return 0, &fs.PathError{Op: "read", Path: f.path, Err: fs.ErrInvalid}
222 }
223 n := copy(b, f.data[offset:])
224 if n < len(b) {
225 return n, io.EOF
226 }
227 return n, nil
228 }
229
230 // A openDir is a directory fs.File (so also an fs.ReadDirFile) open for reading.
231 type openDir struct {
232 fileinfo
233 entries []fs.DirEntry
234 offset int
235 }
236
237 var _ fs.ReadDirFile = (*openDir)(nil)
238
239 func (d *openDir) Stat() (fs.FileInfo, error) { return &d.fileinfo, nil }
240 func (d *openDir) Close() error { return nil }
241 func (d *openDir) Read(b []byte) (int, error) {
242 return 0, &fs.PathError{Op: "read", Path: d.path, Err: fs.ErrInvalid}
243 }
244
245 func (d *openDir) ReadDir(count int) ([]fs.DirEntry, error) {
246 n := len(d.entries) - d.offset
247 if n == 0 && count > 0 {
248 return nil, io.EOF
249 }
250 if count > 0 && n > count {
251 n = count
252 }
253 list := make([]fs.DirEntry, n)
254 copy(list, d.entries[d.offset:d.offset+n])
255 d.offset += n
256 return list, nil
257 }