forked from zhanglimao/trivy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memfs.go
48 lines (41 loc) · 1.25 KB
/
memfs.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
package module
import (
"io"
"io/fs"
"path/filepath"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/zhyocean/trivy/pkg/mapfs"
)
// memFS is a wrapper of mapfs.FS and can change its underlying file system
// at runtime. This implements fs.FS.
type memFS struct {
current *mapfs.FS
}
// Open implements fs.FS.
func (m *memFS) Open(name string) (fs.File, error) {
if m.current == nil {
return nil, fs.ErrNotExist
}
return m.current.Open(name)
}
// initialize changes the underlying memory file system with the given file path and contents.
//
// Note: it is always to safe swap the underlying FS with this API since this is called only at the beginning of
// Analyze interface call, which is not concurrently called per module instance.
func (m *memFS) initialize(filePath string, content dio.ReadSeekerAt) error {
mfs := mapfs.New()
if err := mfs.MkdirAll(filepath.Dir(filePath), fs.ModePerm); err != nil {
return xerrors.Errorf("mapfs mkdir error: %w", err)
}
b, err := io.ReadAll(content)
if err != nil {
return xerrors.Errorf("read error: %w", err)
}
err = mfs.WriteVirtualFile(filePath, b, fs.ModePerm)
if err != nil {
return xerrors.Errorf("mapfs write error: %w", err)
}
m.current = mfs
return nil
}