forked from aboutcode-org/scancode-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.py
More file actions
433 lines (367 loc) · 15.8 KB
/
build.py
File metadata and controls
433 lines (367 loc) · 15.8 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#
# 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 os
import logging
import ast
from collections import defaultdict
from commoncode import fileutils
from licensedcode.cache import build_spdx_license_expression
from licensedcode.cache import get_cache
from licensedcode.tokenize import query_tokenizer
from licensedcode.detection import detect_licenses
from licensedcode.detection import get_unknown_license_detection
from packagedcode import models
from packagedcode.licensing import get_mapping_and_expression_from_detections
"""
Detect as Packages common build tools and environment such as Make, Autotools,
Buck, Bazel, Pants, etc.
"""
TRACE = os.environ.get('SCANCODE_DEBUG_PACKAGE', False)
def logger_debug(*args):
pass
logger = logging.getLogger(__name__)
if TRACE:
import sys
logging.basicConfig(stream=sys.stdout)
logger.setLevel(logging.DEBUG)
def logger_debug(*args):
return logger.debug(
' '.join(isinstance(a, str) and a or repr(a) for a in args)
)
class AutotoolsConfigureHandler(models.NonAssemblableDatafileHandler):
datasource_id = 'autotools_configure'
path_patterns = ('*/configure', '*/configure.ac',)
default_package_type = 'autotools'
description = 'Autotools configure script'
documentation_url = 'https://www.gnu.org/software/automake/'
@classmethod
def parse(cls, location, package_only=False):
# we use the parent directory as a package name
name = fileutils.file_name(fileutils.parent_directory(location))
# we could use checksums as version in the future
version = None
# there is an optional array of license file names in targets that we could use
# declared_license = None
# there are dependencies we could use
# dependencies = []
package_data = dict(
datasource_id=cls.datasource_id,
type=cls.default_package_type,
name=name,
version=version,
)
yield models.PackageData.from_data(package_data, package_only)
def check_rule_name_ending(rule_name, starlark_rule_types=('binary', 'library')):
"""
Return True if `rule_name` ends with a rule type from `starlark_rule_types`
Return False otherwise
"""
for rule_type in starlark_rule_types:
if rule_name.endswith(rule_type):
return True
return False
class BaseStarlarkManifestHandler(models.DatafileHandler):
"""
Common base class for Bazel and Buck that both use the Starlark syntax.
"""
@classmethod
def assemble(cls, package_data, resource, codebase, package_adder):
"""
Given a ``package_data`` PackageData found in the ``resource`` datafile
of the ``codebase``, assemble and yield a Package with its files and
dependencies from one or more datafiles.
"""
# do we have enough to create a package?
if package_data.purl:
package = models.Package.from_package_data(
package_data=package_data,
datafile_path=resource.path,
package_only=True,
)
if TRACE:
logger_debug(f"BaseStarlarkManifestHandler.assemble: package_data: {package_data.to_dict()}")
package.license_detections, package.declared_license_expression = \
get_license_detections_and_expression(
package=package_data,
resource=resource,
codebase=codebase,
)
if package.declared_license_expression:
package.declared_license_expression_spdx = str(build_spdx_license_expression(
license_expression=package.declared_license_expression,
licensing=get_cache().licensing,
))
cls.assign_package_to_resources(
package=package,
resource=resource,
codebase=codebase,
package_adder=package_adder
)
yield package
# we yield this as we do not want this further processed
yield resource
@classmethod
def parse(cls, location, package_only=False):
# Thanks to Starlark being a Python dialect, we can use `ast` to parse it
with open(location, 'rb') as f:
tree = ast.parse(f.read())
build_rules = defaultdict(list)
for statement in tree.body:
# We only care about function calls or assignments to functions whose
# names ends with one of the strings in `rule_types`
if (
isinstance(statement, ast.Expr)
or isinstance(statement, ast.Call)
or isinstance(statement, ast.Assign)
and isinstance(statement.value, ast.Call)
and isinstance(statement.value.func, ast.Name)
):
rule_name = statement.value.func.id
# Ensure that we are only creating packages from the proper
# build rules
if not check_rule_name_ending(rule_name):
continue
# Process the rule arguments
args = {}
for kw in statement.value.keywords:
arg_name = kw.arg
if isinstance(kw.value, ast.Str):
args[arg_name] = kw.value.s
if isinstance(kw.value, ast.List):
# We collect the elements of a list if the element is
# not a function call
args[arg_name] = [
elt.s for elt in kw.value.elts
if not isinstance(elt, ast.Call)
]
if args:
build_rules[rule_name].append(args)
if build_rules:
for rule_name, rule_instances_args in build_rules.items():
for args in rule_instances_args:
name = args.get('name')
# FIXME: we could still return partial package data
if not name:
continue
license_files = args.get('licenses')
if TRACE:
logger_debug(f"build: parse: license_files: {license_files}")
package_data = dict(
datasource_id=cls.datasource_id,
type=cls.default_package_type,
name=name,
extracted_license_statement=license_files,
)
# `package_only` is True as we do the license detection
# on assembly
yield models.PackageData.from_data(
package_data=package_data,
package_only=True,
)
else:
# If we don't find anything in the pkgdata file, we yield a Package
# with the parent directory as the name
package_data = dict(
datasource_id=cls.datasource_id,
type=cls.default_package_type,
name=fileutils.file_name(fileutils.parent_directory(location))
)
yield models.PackageData.from_data(package_data, package_only)
@classmethod
def assign_package_to_resources(cls, package, resource, codebase, package_adder, skip_name=None):
package_uid = package.package_uid
if not package_uid:
return
parent = resource.parent(codebase)
for res in walk_build(resource=parent, codebase=codebase, skip_name=skip_name):
package_adder(package_uid, res, codebase)
def walk_build(resource, codebase, skip_name):
"""
Walk the ``codebase`` starting at ``resource`` and stop when ``skip_name``
is found in a subdirectory. The idea is to avoid walking recursively sub-
directories that contain a build script such as a Bazel or BUCK file as they
define their own file tree.
"""
for child in resource.children(codebase):
yield child
if not child.is_dir:
continue
if not any(r.name == skip_name for r in child.children(codebase)):
for subchild in walk_build(child, codebase, skip_name=skip_name):
yield subchild
def get_license_detections_and_expression(package, resource, codebase):
"""
Return a normalized license expression string detected from a list of
declared license items.
"""
license_detections = []
declared_licenses = package.extracted_license_statement
if not declared_licenses:
return license_detections, None
if not isinstance(declared_licenses, str):
declared_licenses = repr(declared_licenses)
declared_licenses = list(query_tokenizer(declared_licenses))
declared_licenses = set(declared_licenses)
if TRACE:
logger_debug(
f"build: get_license_detections_and_expression:"
f"declared_licenses: {declared_licenses}"
)
logger_debug(
f"build: get_license_detections_and_expression:"
f"type(declared_licenses): {type(declared_licenses)}"
)
parent = resource.parent(codebase)
# FIXME: we should be able to get the path relatively to the ABOUT file resource
for child in parent.children(codebase):
if child.name.lower() in declared_licenses:
detections = detect_licenses(location=child.location)
if TRACE:
logger_debug(
f"build: get_license_detections_and_expression:"
f"detections: {detections}"
)
if not detections:
license_detections.append(
get_unknown_license_detection(declared_licenses)
)
else:
license_detections.extend(detections)
return get_mapping_and_expression_from_detections(
license_detections=license_detections
)
class BazelBuildHandler(BaseStarlarkManifestHandler):
datasource_id = 'bazel_build'
path_patterns = ('*/BUILD',)
default_package_type = 'bazel'
description = 'Bazel BUILD'
documentation_url = 'https://bazel.build/'
@classmethod
def assign_package_to_resources(cls, package, resource, codebase, package_adder, skip_name='BUILD'):
return super().assign_package_to_resources(
package=package,
resource=resource,
codebase=codebase,
package_adder=package_adder,
skip_name=skip_name,
)
class BuckPackageHandler(BaseStarlarkManifestHandler):
datasource_id = 'buck_file'
path_patterns = ('*/BUCK',)
default_package_type = 'buck'
description = 'Buck file'
documentation_url = 'https://buck.build/'
@classmethod
def assign_package_to_resources(cls, package, resource, codebase, package_adder, skip_name='BUCK'):
return super().assign_package_to_resources(
package=package,
resource=resource,
codebase=codebase,
package_adder=package_adder,
skip_name=skip_name,
)
class BuckMetadataBzlHandler(BaseStarlarkManifestHandler):
datasource_id = 'buck_metadata'
path_patterns = ('*/METADATA.bzl',)
default_package_type = 'buck'
description = 'Buck metadata file'
documentation_url = 'https://buck.build/'
@classmethod
def parse(cls, location, package_only=True):
with open(location, 'rb') as f:
tree = ast.parse(f.read())
metadata_fields = {}
for statement in tree.body:
if not (hasattr(statement, 'targets') and isinstance(statement, ast.Assign)):
continue
# We are looking for a dictionary assigned to the variable `METADATA`
for target in statement.targets:
if not (target.id == 'METADATA' and isinstance(statement.value, ast.Dict)):
continue
# Once we find the dictionary assignment, get and store its contents
statement_keys = statement.value.keys
statement_values = statement.value.values
for statement_k, statement_v in zip(statement_keys, statement_values):
if isinstance(statement_k, ast.Str):
key_name = statement_k.s
# The list values in a `METADATA.bzl` file seem to only contain strings
if isinstance(statement_v, ast.List):
value = []
for e in statement_v.elts:
if not isinstance(e, ast.Str):
continue
value.append(e.s)
if isinstance(statement_v, (ast.Str, ast.Constant)):
value = statement_v.s
metadata_fields[key_name] = value
parties = []
maintainers = metadata_fields.get('maintainers', []) or []
for maintainer in maintainers:
parties.append(
models.Party(
type=models.party_org,
name=maintainer,
role='maintainer',
)
)
if (
'upstream_type'
and 'name'
and 'version'
and 'licenses'
and 'upstream_address'
in metadata_fields
):
# TODO: Create function that determines package type from download URL,
# then create a package of that package type from the metadata info
package_data = dict(
datasource_id=cls.datasource_id,
type=metadata_fields.get('upstream_type', cls.default_package_type),
name=metadata_fields.get('name'),
version=metadata_fields.get('version'),
extracted_license_statement=metadata_fields.get('licenses', []),
parties=parties,
homepage_url=metadata_fields.get('upstream_address', ''),
# TODO: Store 'upstream_hash` somewhere
)
yield models.PackageData.from_data(package_data, package_only=True)
if (
'package_type'
and 'name'
and 'version'
and 'license_expression'
and 'homepage_url'
and 'download_url'
and 'vcs_url'
and 'download_archive_sha1'
and 'vcs_commit_hash'
in metadata_fields
):
package_data = dict(
datasource_id=cls.datasource_id,
type=metadata_fields.get('package_type', cls.default_package_type),
name=metadata_fields.get('name'),
version=metadata_fields.get('version'),
extracted_license_statement=metadata_fields.get('license_expression', ''),
parties=parties,
homepage_url=metadata_fields.get('homepage_url', ''),
download_url=metadata_fields.get('download_url', ''),
vcs_url=metadata_fields.get('vcs_url', ''),
sha1=metadata_fields.get('download_archive_sha1', ''),
extra_data=dict(vcs_commit_hash=metadata_fields.get('vcs_commit_hash', ''))
)
yield models.PackageData.from_data(package_data, package_only=True)
@classmethod
def assign_package_to_resources(cls, package, resource, codebase, package_adder):
models.DatafileHandler.assign_package_to_parent_tree(
package_=package,
resource=resource,
codebase=codebase,
package_adder=package_adder,
)