/
config.go
86 lines (74 loc) · 2.39 KB
/
config.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
package filecataloging
import (
"crypto"
"encoding/json"
"fmt"
"strings"
intFile "github.com/anchore/syft/internal/file"
"github.com/anchore/syft/internal/log"
"github.com/anchore/syft/syft/file"
"github.com/anchore/syft/syft/file/cataloger/executable"
"github.com/anchore/syft/syft/file/cataloger/filecontent"
)
type Config struct {
Selection file.Selection `yaml:"selection" json:"selection" mapstructure:"selection"`
Hashers []crypto.Hash `yaml:"hashers" json:"hashers" mapstructure:"hashers"`
Content filecontent.Config `yaml:"content" json:"content" mapstructure:"content"`
Executable executable.Config `yaml:"executable" json:"executable" mapstructure:"executable"`
}
type configMarshaledForm struct {
Selection file.Selection `yaml:"selection" json:"selection" mapstructure:"selection"`
Hashers []string `yaml:"hashers" json:"hashers" mapstructure:"hashers"`
Content filecontent.Config `yaml:"content" json:"content" mapstructure:"content"`
}
func DefaultConfig() Config {
hashers, err := intFile.Hashers("sha256")
if err != nil {
log.WithFields("error", err).Warn("unable to create file hashers")
}
return Config{
Selection: file.FilesOwnedByPackageSelection,
Hashers: hashers,
Content: filecontent.DefaultConfig(),
Executable: executable.DefaultConfig(),
}
}
func (cfg Config) MarshalJSON() ([]byte, error) {
marshaled := configMarshaledForm{
Selection: cfg.Selection,
Hashers: hashersToString(cfg.Hashers),
}
return json.Marshal(marshaled)
}
func hashersToString(hashers []crypto.Hash) []string {
var result []string
for _, h := range hashers {
result = append(result, strings.ToLower(h.String()))
}
return result
}
func (cfg *Config) UnmarshalJSON(data []byte) error {
var marshaled configMarshaledForm
if err := json.Unmarshal(data, &marshaled); err != nil {
return err
}
hashers, err := intFile.Hashers(marshaled.Hashers...)
if err != nil {
return fmt.Errorf("unable to parse configured hashers: %w", err)
}
cfg.Selection = marshaled.Selection
cfg.Hashers = hashers
return nil
}
func (cfg Config) WithSelection(selection file.Selection) Config {
cfg.Selection = selection
return cfg
}
func (cfg Config) WithHashers(hashers ...crypto.Hash) Config {
cfg.Hashers = intFile.NormalizeHashes(hashers)
return cfg
}
func (cfg Config) WithContentConfig(content filecontent.Config) Config {
cfg.Content = content
return cfg
}