-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
fs.go
122 lines (100 loc) · 2.52 KB
/
fs.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package fsutils
import (
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"golang.org/x/exp/slices"
"golang.org/x/xerrors"
"github.com/aquasecurity/trivy/pkg/log"
)
const (
xdgDataHome = "XDG_DATA_HOME"
)
var cacheDir string
// defaultCacheDir returns/creates the cache-dir to be used for trivy operations
func defaultCacheDir() string {
tmpDir, err := os.UserCacheDir()
if err != nil {
tmpDir = os.TempDir()
}
return filepath.Join(tmpDir, "trivy")
}
// CacheDir returns the directory used for caching
func CacheDir() string {
if cacheDir == "" {
return defaultCacheDir()
}
return cacheDir
}
// SetCacheDir sets the trivy cacheDir
func SetCacheDir(dir string) {
cacheDir = dir
}
func HomeDir() string {
dataHome := os.Getenv(xdgDataHome)
if dataHome != "" {
return dataHome
}
homeDir, _ := os.UserHomeDir()
return homeDir
}
// CopyFile copies the file content from scr to dst
func CopyFile(src, dst string) (int64, error) {
sourceFileStat, err := os.Stat(src)
if err != nil {
return 0, xerrors.Errorf("file (%s) stat error: %w", src, err)
}
if !sourceFileStat.Mode().IsRegular() {
return 0, fmt.Errorf("%s is not a regular file", src)
}
source, err := os.Open(src)
if err != nil {
return 0, err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return 0, err
}
defer destination.Close()
n, err := io.Copy(destination, source)
return n, err
}
func DirExists(path string) bool {
if f, err := os.Stat(path); os.IsNotExist(err) || !f.IsDir() {
return false
}
return true
}
type WalkDirRequiredFunc func(path string, d fs.DirEntry) bool
type WalkDirFunc func(path string, d fs.DirEntry, r io.Reader) error
func WalkDir(fsys fs.FS, root string, required WalkDirRequiredFunc, fn WalkDirFunc) error {
return fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
} else if !d.Type().IsRegular() || !required(path, d) {
return nil
}
f, err := fsys.Open(path)
if err != nil {
return xerrors.Errorf("file open error: %w", err)
}
defer f.Close()
if err = fn(path, d, f); err != nil {
log.Debug("Walk error", log.String("file_path", path), log.Err(err))
}
return nil
})
}
func RequiredExt(exts ...string) WalkDirRequiredFunc {
return func(filePath string, _ fs.DirEntry) bool {
return slices.Contains(exts, filepath.Ext(filePath))
}
}
func RequiredFile(fileNames ...string) WalkDirRequiredFunc {
return func(filePath string, _ fs.DirEntry) bool {
return slices.Contains(fileNames, filepath.Base(filePath))
}
}