-
Notifications
You must be signed in to change notification settings - Fork 619
/
Copy pathparse_copyright.go
65 lines (51 loc) · 1.65 KB
/
parse_copyright.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
package debian
import (
"bufio"
"io"
"regexp"
"sort"
"strings"
"github.com/scylladb/go-set/strset"
"github.com/anchore/syft/internal"
)
// For more information see: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/#license-syntax
var (
licensePattern = regexp.MustCompile(`^License: (?P<license>\S*)`)
commonLicensePathPattern = regexp.MustCompile(`/usr/share/common-licenses/(?P<license>[0-9A-Za-z_.\-]+)`)
)
func parseLicensesFromCopyright(reader io.Reader) []string {
findings := strset.New()
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
line := scanner.Text()
if value := findLicenseClause(licensePattern, "license", line); value != "" {
findings.Add(value)
}
if value := findLicenseClause(commonLicensePathPattern, "license", line); value != "" {
findings.Add(value)
}
}
results := findings.List()
sort.Strings(results)
return results
}
func findLicenseClause(pattern *regexp.Regexp, valueGroup, line string) string {
matchesByGroup := internal.MatchNamedCaptureGroups(pattern, line)
candidate, ok := matchesByGroup[valueGroup]
if !ok {
return ""
}
return ensureIsSingleLicense(candidate)
}
func ensureIsSingleLicense(candidate string) (license string) {
candidate = strings.TrimSpace(candidate)
if strings.Contains(candidate, " or ") || strings.Contains(candidate, " and ") {
// this is a multi-license summary, ignore this as other recurrent license lines should cover this
return
}
if candidate != "" && strings.ToLower(candidate) != "none" {
// the license may be at the end of a sentence, clean . characters
license = strings.TrimSuffix(candidate, ".")
}
return license
}