-
Notifications
You must be signed in to change notification settings - Fork 18
/
memory.go
90 lines (74 loc) · 1.86 KB
/
memory.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
package memory
import (
"context"
"errors"
"github.com/cirruslabs/cirrus-cli/pkg/larker/fs"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-billy/v5/util"
"io"
"os"
"path"
"syscall"
)
type Memory struct {
fs billy.Filesystem
}
func New(fileContents map[string][]byte) (*Memory, error) {
memory := &Memory{
fs: memfs.New(),
}
for path, contents := range fileContents {
if err := util.WriteFile(memory.fs, path, contents, 0600); err != nil {
return nil, err
}
}
return memory, nil
}
func (memory *Memory) Stat(ctx context.Context, path string) (*fs.FileInfo, error) {
fileInfo, err := memory.fs.Stat(path)
if err != nil {
return nil, err
}
return &fs.FileInfo{IsDir: fileInfo.IsDir()}, nil
}
func (memory *Memory) Get(ctx context.Context, path string) ([]byte, error) {
// Work around github.com/go-git/go-billy quirks
// in regard to treatment of directories in memory FS
fileInfo, err := memory.fs.Stat(path)
if err == nil && fileInfo.IsDir() {
return nil, fs.ErrNormalizedIsADirectory
}
file, err := memory.fs.Open(path)
if err != nil {
return nil, err
}
fileBytes, err := io.ReadAll(file)
if err != nil {
return nil, err
}
return fileBytes, nil
}
func (memory *Memory) ReadDir(ctx context.Context, path string) ([]string, error) {
// Work around github.com/go-git/go-billy quirks
// in regard to treatment of directories in memory FS
fileInfo, err := memory.fs.Stat(path)
if err == nil && !fileInfo.IsDir() {
return nil, syscall.ENOTDIR
}
if errors.Is(err, os.ErrNotExist) {
return nil, err
}
fileInfos, err := memory.fs.ReadDir(path)
if err != nil {
return nil, err
}
var result []string
for _, fileInfo := range fileInfos {
result = append(result, fileInfo.Name())
}
return result, nil
}
func (memory *Memory) Join(elem ...string) string {
return path.Join(elem...)
}