-
-
Notifications
You must be signed in to change notification settings - Fork 720
Expand file tree
/
Copy pathgo_mod.py
More file actions
366 lines (293 loc) · 10.7 KB
/
go_mod.py
File metadata and controls
366 lines (293 loc) · 10.7 KB
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#
import io
import re
import attr
from packageurl import PackageURL
@attr.s()
class GoWorkspace(object):
"""
Represents a parsed go.work file for a Go workspace.
A workspace is a collection of multiple Go modules that can be edited together.
See https://go.dev/ref/mod#go-work-files for details.
"""
go_version = attr.ib(default=None)
use = attr.ib(default=attr.Factory(list))
require = attr.ib(default=attr.Factory(list))
@attr.s()
class GoModule(object):
namespace = attr.ib(default=None)
name = attr.ib(default=None)
version = attr.ib(default=None)
module = attr.ib(default=None)
require = attr.ib(default=None)
exclude = attr.ib(default=None)
def purl(self, include_version=True):
version = None
if include_version:
version = self.version
return PackageURL(
type='golang',
namespace=self.namespace,
name=self.name,
version=version
).to_string()
# Regex expressions to parse different types of go.mod file dependency
parse_module = re.compile(
r'(?P<type>[^\s]+)'
r'(\s)+'
r'(?P<ns_name>[^\s]+)'
r'\s?'
r'(?P<version>(.*))'
).match
parse_dep_link = re.compile(
r'.*?'
r'(?P<ns_name>[^\s]+)'
r'\s+'
r'(?P<version>(.*))'
).match
def preprocess(line):
"""
Return line string after removing commented portion and excess spaces.
"""
if "//" in line:
line = line[:line.index('//')]
line = line.strip()
return line
def parse_gomod(location):
"""
Return a dictionary containing all the important go.mod file data.
Handle go.mod files from Go.
See https://golang.org/ref/mod#go.mod-files for details
For example:
module example.com/my/thing
go 1.12
require example.com/other/thing v1.0.2
require example.com/new/thing v2.3.4
exclude example.com/old/thing v1.2.3
require (
example.com/new/thing v2.3.4
example.com/old/thing v1.2.3
)
require (
example.com/new/thing v2.3.4
example.com/old/thing v1.2.3
)
Each module line is in the form
require github.com/davecgh/go-spew v1.1.1
or
exclude github.com/davecgh/go-spew v1.1.1
or
module github.com/alecthomas/participle
For example::
>>> p = parse_module('module github.com/alecthomas/participle')
>>> assert p.group('type') == ('module')
>>> assert p.group('ns_name') == ('github.com/alecthomas/participle')
>>> p = parse_module('require github.com/davecgh/go-spew v1.1.1')
>>> assert p.group('type') == ('require')
>>> assert p.group('ns_name') == ('github.com/davecgh/go-spew')
>>> assert p.group('version') == ('v1.1.1')
A line for require or exclude can be in the form:
github.com/davecgh/go-spew v1.1.1
For example::
>>> p = parse_dep_link('github.com/davecgh/go-spew v1.1.1')
>>> assert p.group('ns_name') == ('github.com/davecgh/go-spew')
>>> assert p.group('version') == ('v1.1.1')
"""
with io.open(location, encoding='utf-8', closefd=True) as data:
lines = data.readlines()
gomods = GoModule()
require = []
exclude = []
for i, line in enumerate(lines):
line = preprocess(line)
if 'require' in line and '(' in line:
for req in lines[i + 1:]:
req = preprocess(req)
if ')' in req:
break
parsed_dep_link = parse_dep_link(req)
ns_name = parsed_dep_link.group('ns_name')
namespace, _, name = ns_name.rpartition('/')
if parsed_dep_link:
require.append(GoModule(
namespace=namespace,
name=name,
version=parsed_dep_link.group('version')
)
)
continue
if 'exclude' in line and '(' in line:
for exc in lines[i + 1:]:
exc = preprocess(exc)
if ')' in exc:
break
parsed_dep_link = parse_dep_link(exc)
ns_name = parsed_dep_link.group('ns_name')
namespace, _, name = ns_name.rpartition('/')
if parsed_dep_link:
exclude.append(GoModule(
namespace=namespace,
name=name,
version=parsed_dep_link.group('version')
)
)
continue
parsed_module_name = parse_module(line)
if parsed_module_name:
ns_name = parsed_module_name.group('ns_name')
namespace, _, name = ns_name.rpartition('/')
if 'module' in line:
gomods.namespace = namespace
gomods.name = name
continue
if 'require' in line:
require.append(GoModule(
namespace=namespace,
name=name,
version=parsed_module_name.group('version')
)
)
continue
if 'exclude' in line:
exclude.append(GoModule(
namespace=namespace,
name=name,
version=parsed_module_name.group('version')
)
)
continue
gomods.require = require
gomods.exclude = exclude
return gomods
# Regex expressions to parse go.sum file dependency
# dep example: github.com/BurntSushi/toml v0.3.1 h1:WXkYY....
get_dependency = re.compile(
r'(?P<ns_name>[^\s]+)'
r'\s+'
r'(?P<version>[^\s]+)'
r'\s+'
r'h1:(?P<checksum>[^\s]*)'
).match
def parse_gosum(location):
"""
Return a list of GoSum from parsing the go.sum file at `location`.
Handles go.sum file from Go.
See https://blog.golang.org/using-go-modules for details
A go.sum file contains pinned Go modules checksums of two styles:
For example::
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
... where the line with /go.mod is for a check of that go.mod file
and the other line contains a dirhash for that path as documented as
https://pkg.go.dev/golang.org/x/mod/sumdb/dirhash
For example::
>>> p = get_dependency('github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=')
>>> assert p.group('ns_name') == ('github.com/BurntSushi/toml')
>>> assert p.group('version') == ('v0.3.1')
>>> assert p.group('checksum') == ('WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=')
"""
with io.open(location, encoding='utf-8', closefd=True) as data:
lines = data.readlines()
gosums = []
for line in lines:
line = line.replace('/go.mod', '')
parsed_dep = get_dependency(line)
ns_name = parsed_dep.group('ns_name')
namespace, _, name = ns_name.rpartition('/')
dep = GoModule(
namespace=namespace,
name=name,
version=parsed_dep.group('version')
)
if dep in gosums:
continue
gosums.append(dep)
return gosums
def parse_gowork(location):
"""
Return a GoWorkspace parsed from a go.work file at ``location``.
Handle go.work files from Go workspaces introduced in Go 1.18.
See https://go.dev/ref/mod#go-work-files for details.
A go.work file specifies a workspace containing multiple modules with:
- ``go`` directive: Go version
- ``use`` directives: paths to local modules in the workspace
- ``require`` directives: external module requirements (like go.mod)
For example::
go 1.18
use (
./mymodule
./tools
)
require (
github.com/some/dep v1.2.3
)
"""
with io.open(location, encoding='utf-8', closefd=True) as data:
lines = data.readlines()
workspace = GoWorkspace()
use_dirs = []
require = []
for i, line in enumerate(lines):
line = preprocess(line)
if not line:
continue
# Parse 'go <version>' directive
if line.startswith('go '):
workspace.go_version = line[3:].strip()
continue
# Parse multi-line 'use ( ... )' block
if line == 'use (' or line.startswith('use ('):
for use_line in lines[i + 1:]:
use_line = preprocess(use_line)
if ')' in use_line:
break
if use_line:
use_dirs.append(use_line)
continue
# Parse inline 'use ./path'
if line.startswith('use ') and '(' not in line:
path = line[4:].strip()
if path:
use_dirs.append(path)
continue
# Parse multi-line 'require ( ... )' block
if line == 'require (' or (line.startswith('require') and '(' in line):
for req_line in lines[i + 1:]:
req_line = preprocess(req_line)
if ')' in req_line:
break
if not req_line:
continue
parsed_dep = parse_dep_link(req_line)
if parsed_dep:
ns_name = parsed_dep.group('ns_name')
namespace, _, name = ns_name.rpartition('/')
version = parsed_dep.group('version')
require.append(GoModule(
namespace=namespace,
name=name,
version=version,
))
continue
# Parse inline 'require module version'
if line.startswith('require ') and '(' not in line:
parsed = parse_module(line)
if parsed:
ns_name = parsed.group('ns_name')
namespace, _, name = ns_name.rpartition('/')
version = parsed.group('version').strip()
require.append(GoModule(
namespace=namespace,
name=name,
version=version,
))
continue
workspace.use = use_dirs
workspace.require = require
return workspace