-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmapfs.go
49 lines (45 loc) · 1.01 KB
/
mapfs.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
// Package mapfs takes in a description of a filesystem as a map[string]string
// and writes it to a temp directory so that it may be used as an io/fs.FS.
package mapfs
import (
"errors"
"fmt"
"io/fs"
"os"
"path"
)
type FS struct {
dir string
fs.FS
}
func New(m map[string]string) (*FS, error) {
tempDir, err := os.MkdirTemp("", "mapfs-*")
if err != nil {
return nil, fmt.Errorf("failed to create root mapfs dir: %w", err)
}
for p, s := range m {
p = path.Join(tempDir, p)
err = os.MkdirAll(path.Dir(p), 0755)
if err != nil {
return nil, fmt.Errorf("failed to create mapfs dir %q: %w", path.Dir(p), err)
}
err = os.WriteFile(p, []byte(s), 0644)
if err != nil {
return nil, fmt.Errorf("failed to write mapfs file %q: %w", p, err)
}
}
return &FS{
dir: tempDir,
FS: os.DirFS(tempDir),
}, nil
}
func (fs *FS) Close() error {
err := os.RemoveAll(fs.dir)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("failed to close mapfs.FS: %w", err)
}
return nil
}