/
parse-requirements-txt.go
166 lines (128 loc) · 4.15 KB
/
parse-requirements-txt.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package lockfile
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/g-rath/osv-detector/internal/cachedregexp"
)
const PipEcosystem Ecosystem = "PyPI"
// todo: expand this to support more things, e.g.
//
// https://pip.pypa.io/en/stable/reference/requirements-file-format/#example
func parseLine(line string) PackageDetails {
var constraint string
name := line
version := "0.0.0"
if strings.Contains(line, "==") {
constraint = "=="
}
if strings.Contains(line, ">=") {
constraint = ">="
}
if strings.Contains(line, "~=") {
constraint = "~="
}
if strings.Contains(line, "!=") {
constraint = "!="
}
if constraint != "" {
unprocessedName, unprocessedVersion, _ := strings.Cut(line, constraint)
name = strings.TrimSpace(unprocessedName)
if constraint != "!=" {
version, _, _ = strings.Cut(strings.TrimSpace(unprocessedVersion), " ")
}
}
return PackageDetails{
Name: normalizedRequirementName(name),
Version: version,
Ecosystem: PipEcosystem,
CompareAs: PipEcosystem,
}
}
// normalizedName ensures that the package name is normalized per PEP-0503
// and then removing "added support" syntax if present.
//
// This is done to ensure we don't miss any advisories, as while the OSV
// specification says that the normalized name should be used for advisories,
// that's not the case currently in our databases, _and_ Pip itself supports
// non-normalized names in the requirements.txt, so we need to normalize
// on both sides to ensure we don't have false negatives.
//
// It's possible that this will cause some false positives, but that is better
// than false negatives, and can be dealt with when/if it actually happens.
func normalizedRequirementName(name string) string {
// per https://www.python.org/dev/peps/pep-0503/#normalized-names
name = cachedregexp.MustCompile(`[-_.]+`).ReplaceAllString(name, "-")
name = strings.ToLower(name)
name, _, _ = strings.Cut(name, "[")
return name
}
func removeComments(line string) string {
var re = cachedregexp.MustCompile(`(^|\s+)#.*$`)
return strings.TrimSpace(re.ReplaceAllString(line, ""))
}
func isNotRequirementLine(line string) bool {
return line == "" ||
// flags are not supported
strings.HasPrefix(line, "-") ||
// file urls
strings.HasPrefix(line, "https://") ||
strings.HasPrefix(line, "http://") ||
// file paths are not supported (relative or absolute)
strings.HasPrefix(line, ".") ||
strings.HasPrefix(line, "/")
}
func isLineContinuation(line string) bool {
// checks that the line ends with an odd number of backslashes,
// meaning the last one isn't escaped
var re = cachedregexp.MustCompile(`([^\\]|^)(\\{2})*\\$`)
return re.MatchString(line)
}
func ParseRequirementsTxt(pathToLockfile string) ([]PackageDetails, error) {
return parseRequirementsTxt(pathToLockfile, map[string]struct{}{})
}
func parseRequirementsTxt(pathToLockfile string, requiredAlready map[string]struct{}) ([]PackageDetails, error) {
packages := map[string]PackageDetails{}
file, err := os.Open(pathToLockfile)
if err != nil {
return []PackageDetails{}, fmt.Errorf("could not open %s: %w", pathToLockfile, err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
for isLineContinuation(line) {
line = strings.TrimSuffix(line, "\\")
if scanner.Scan() {
line += scanner.Text()
}
}
line = removeComments(line)
if ar := strings.TrimPrefix(line, "-r "); ar != line {
ar = filepath.Join(filepath.Dir(pathToLockfile), ar)
if _, ok := requiredAlready[ar]; ok {
continue
}
requiredAlready[ar] = struct{}{}
details, err := parseRequirementsTxt(ar, requiredAlready)
if err != nil {
return []PackageDetails{}, fmt.Errorf("failed to include %s: %w", line, err)
}
for _, detail := range details {
packages[detail.Name+"@"+detail.Version] = detail
}
continue
}
if isNotRequirementLine(line) {
continue
}
detail := parseLine(line)
packages[detail.Name+"@"+detail.Version] = detail
}
if err := scanner.Err(); err != nil {
return []PackageDetails{}, fmt.Errorf("error while scanning %s: %w", pathToLockfile, err)
}
return pkgDetailsMapToSlice(packages), nil
}