-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
io.go
51 lines (41 loc) · 1.26 KB
/
io.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
package scanner
import (
"fmt"
"os"
"regexp"
"runtime"
"golang.org/x/xerrors"
"gopkg.in/yaml.v3"
"github.com/aquasecurity/trivy-kubernetes/pkg/artifacts"
"github.com/aquasecurity/trivy/pkg/log"
)
var r = regexp.MustCompile("\\\\|/|:|\\*|\\?|<|>")
func createTempFile(artifact *artifacts.Artifact) (string, error) {
filename := fmt.Sprintf("%s-%s-%s-*.yaml", artifact.Namespace, artifact.Kind, artifact.Name)
if runtime.GOOS == "windows" {
// removes characters not permitted in file/directory names on Windows
filename = filenameWindowsFriendly(filename)
}
file, err := os.CreateTemp("", filename)
if err != nil {
return "", xerrors.Errorf("creating tmp file error: %w", err)
}
defer func() {
if err := file.Close(); err != nil {
log.Logger.Errorf("failed to close temp file %s: %s:", file.Name(), err)
}
}()
if err := yaml.NewEncoder(file).Encode(artifact.RawResource); err != nil {
removeFile(filename)
return "", xerrors.Errorf("marshaling resource error: %w", err)
}
return file.Name(), nil
}
func removeFile(filename string) {
if err := os.Remove(filename); err != nil {
log.Logger.Errorf("failed to remove temp file %s: %s:", filename, err)
}
}
func filenameWindowsFriendly(name string) string {
return r.ReplaceAllString(name, "_")
}