forked from anchore/syft
/
license_set.go
88 lines (74 loc) · 1.98 KB
/
license_set.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
package pkg
import (
"fmt"
"sort"
"github.com/mitchellh/hashstructure/v2"
"github.com/gsoc2/syft/internal/log"
"github.com/gsoc2/syft/syft/artifact"
)
type LicenseSet struct {
set map[artifact.ID]License
}
func NewLicenseSet(licenses ...License) (s LicenseSet) {
for _, l := range licenses {
s.Add(l)
}
return s
}
func (s *LicenseSet) addToExisting(license License) (id artifact.ID, merged bool, err error) {
id, err = artifact.IDByHash(license)
if err != nil {
return id, false, fmt.Errorf("could not get the hash for a license: %w", err)
}
v, ok := s.set[id]
if !ok {
// doesn't exist safe to add
return id, false, nil
}
// we got the same id; we want to merge the URLs and Location data
// URLs/Location are not considered when taking the Hash
m, err := v.Merge(license)
if err != nil {
return id, false, fmt.Errorf("could not merge license into map: %w", err)
}
s.set[id] = *m
return id, true, nil
}
func (s *LicenseSet) Add(licenses ...License) {
if s.set == nil {
s.set = make(map[artifact.ID]License)
}
for _, l := range licenses {
// we only want to add licenses that have a value
// note, this check should be moved to the license constructor in the future
if l.Value != "" {
if id, merged, err := s.addToExisting(l); err == nil && !merged {
// doesn't exist, add it
s.set[id] = l
} else if err != nil {
log.Trace("license set failed to add license %#v: %+v", l, err)
}
}
}
}
func (s LicenseSet) ToSlice() []License {
if s.set == nil {
return nil
}
var licenses []License
for _, v := range s.set {
licenses = append(licenses, v)
}
sort.Sort(Licenses(licenses))
return licenses
}
func (s LicenseSet) Hash() (uint64, error) {
// access paths and filesystem IDs are not considered when hashing a license set, only the real paths
return hashstructure.Hash(s.ToSlice(), hashstructure.FormatV2, &hashstructure.HashOptions{
ZeroNil: true,
SlicesAsSets: true,
})
}
func (s LicenseSet) Empty() bool {
return len(s.set) < 1
}