-
Notifications
You must be signed in to change notification settings - Fork 529
/
matches.go
77 lines (64 loc) · 1.45 KB
/
matches.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
package match
import (
"sort"
"github.com/anchore/grype/grype/pkg"
)
type Matches struct {
byPackage map[pkg.ID][]Match
}
func NewMatches() Matches {
return Matches{
byPackage: make(map[pkg.ID][]Match),
}
}
// GetByPkgID returns a slice of potential matches from an ID
func (r *Matches) GetByPkgID(id pkg.ID) []Match {
matches, ok := r.byPackage[id]
if !ok {
return nil
}
return matches
}
func (r *Matches) Merge(other Matches) {
// note: de-duplication of matches is an upstream concern (not here)
for pkgID, matches := range other.byPackage {
r.add(pkgID, matches...)
}
}
func (r *Matches) add(id pkg.ID, matches ...Match) {
if len(matches) == 0 {
// only packages with matches should be added
return
}
if _, ok := r.byPackage[id]; !ok {
r.byPackage[id] = make([]Match, 0)
}
r.byPackage[id] = append(r.byPackage[id], matches...)
}
func (r *Matches) Add(p pkg.Package, matches ...Match) {
r.add(p.ID, matches...)
}
func (r *Matches) Enumerate() <-chan Match {
channel := make(chan Match)
go func() {
defer close(channel)
for _, matches := range r.byPackage {
for _, m := range matches {
channel <- m
}
}
}()
return channel
}
func (r *Matches) Sorted() []Match {
matches := make([]Match, 0)
for m := range r.Enumerate() {
matches = append(matches, m)
}
sort.Sort(ByElements(matches))
return matches
}
// Count returns the total number of matches in a result
func (r *Matches) Count() int {
return len(r.byPackage)
}