-
-
Notifications
You must be signed in to change notification settings - Fork 796
Expand file tree
/
Copy pathbuild_gradle.py
More file actions
305 lines (252 loc) · 11.4 KB
/
Copy pathbuild_gradle.py
File metadata and controls
305 lines (252 loc) · 11.4 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
#
# 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 logging
from packageurl import PackageURL
from pygmars import Token
from pygmars.parse import Parser
from pygments import lex
from pygments.lexers import GroovyLexer
import attr
from packagedcode import models
from packagedcode.build import BaseBuildManifestPackage
TRACE = False
logger = logging.getLogger(__name__)
if TRACE:
import sys
logging.basicConfig(stream=sys.stdout)
logger.setLevel(logging.DEBUG)
grammar = """
LIT-STRING: {<LITERAL-STRING-SINGLE|LITERAL-STRING-DOUBLE>}
PACKAGE-IDENTIFIER: {<OPERATOR> <TEXT>? <NAME-LABEL> <TEXT>? <LIT-STRING>}
DEPENDENCY-1: {<PACKAGE-IDENTIFIER>{3} <OPERATOR>}
DEPENDENCY-2: {<NAME> <TEXT> <LIT-STRING> <TEXT>}
DEPENDENCY-3: {<NAME> <TEXT>? <OPERATOR> <LIT-STRING> <OPERATOR>}
DEPENDENCY-4: {<NAME> <TEXT> <NAME-LABEL> <TEXT> <LIT-STRING> <PACKAGE-IDENTIFIER> <PACKAGE-IDENTIFIER> <OPERATOR>? <TEXT>}
DEPENDENCY-5: {<NAME> <TEXT> <NAME> <OPERATOR> <NAME-ATTRIBUTE>}
NESTED-DEPENDENCY-1: {<NAME> <OPERATOR> <DEPENDENCY-1>+ }
"""
def get_tokens(contents):
for i, (token, value) in enumerate(lex(contents, GroovyLexer())):
yield i, token, value
def get_pygmar_tokens(contents):
tokens = Token.from_pygments_tokens(get_tokens(contents))
for token in tokens:
if token.label == 'NAME' and token.value == 'dependencies':
token.label = 'DEPENDENCIES-START'
yield token
def get_parse_tree(build_gradle_location):
# Open build.gradle and create a Pygmars parse tree from its contents
with open(build_gradle_location) as f:
contents = f.read()
parser = Parser(grammar, trace=0)
return parser.parse(list(get_pygmar_tokens(contents)))
def is_literal_string(string):
return string == 'LITERAL-STRING-SINGLE' or string == 'LITERAL-STRING-DOUBLE'
def remove_quotes(string):
"""
Remove starting and ending quotes from `string`.
If `string` has no starting or ending quotes, return `string`.
"""
quoted = lambda x: (x.startswith('"') and x.endswith('"')) or (x.startswith("'") and x.endswith("'"))
if quoted:
return string[1:-1]
else:
return string
def get_dependencies_from_parse_tree(parse_tree):
dependencies = []
in_dependency_block = False
brackets_counter = 0
first_bracket_seen = False
in_nested_dependency = False
nested_dependency_parenthesis_counter = 0
first_parenthesis_seen = False
for tree_node in parse_tree:
if tree_node.label == 'DEPENDENCIES-START':
in_dependency_block = True
continue
if in_dependency_block:
if tree_node.label == 'OPERATOR':
if tree_node.value == '{':
if not first_bracket_seen:
first_bracket_seen = True
brackets_counter += 1
elif tree_node.value == '}':
brackets_counter -= 1
if brackets_counter == 0 and first_bracket_seen:
break
# TODO: Find way to simplify logic with DEPENDENCY-1
if tree_node.label == 'NESTED-DEPENDENCY-1':
dependency = {}
in_nested_dependency = True
scope = None
last_key = None
for child_node in tree_node.leaves():
if child_node.label == 'NAME':
scope = child_node.value
if child_node.label == 'OPERATOR' and child_node.value == '(':
if not first_parenthesis_seen:
first_parenthesis_seen = True
nested_dependency_parenthesis_counter += 1
if child_node.label == 'NAME-LABEL':
value = child_node.value
if value == 'group:':
last_key = 'namespace'
if value == 'name:':
last_key = 'name'
if value == 'version:':
last_key = 'version'
if is_literal_string(child_node.label):
dependency[last_key] = remove_quotes(child_node.value)
if scope:
dependency['scope'] = scope
dependencies.append(dependency)
if in_nested_dependency:
if tree_node.label == 'OPERATOR' and tree_node.value == ')':
nested_dependency_parenthesis_counter -= 1
if nested_dependency_parenthesis_counter == 0 and first_parenthesis_seen:
in_nested_dependency = False
scope = None
if tree_node.label == 'DEPENDENCY-1':
name_label_to_dep_field_name = {
'group:': 'namespace',
'name:': 'name',
'version:': 'version'
}
dependency = {}
last_key = None
for child_node in tree_node.leaves():
value = child_node.value
if child_node.label == 'NAME-LABEL':
last_key = name_label_to_dep_field_name.get(value, '')
if is_literal_string(child_node.label):
if last_key:
dependency[last_key] = remove_quotes(value)
if in_nested_dependency and scope:
dependency['scope'] = scope
dependencies.append(dependency)
if tree_node.label == 'DEPENDENCY-2':
dependency = {}
for child_node in tree_node.leaves():
if child_node.label == 'NAME':
dependency['scope'] = child_node.value
if is_literal_string(child_node.label):
value = child_node.value
value = remove_quotes(value)
namespace = ''
name = ''
version = ''
split_value = value.split(':')
split_value_length = len(split_value)
if split_value_length == 4:
# We are assuming `value` is in the form of "namespace:name:version:module"
# We are currently not reporting down to the module level
namespace, name, version, _ = split_value
if split_value_length == 3:
# We are assuming `value` is in the form of "namespace:name:version"
namespace, name, version = split_value
if split_value_length == 2:
# We are assuming `value` is in the form of "namespace:name"
namespace, name = split_value
dependency['namespace'] = namespace
dependency['name'] = name
dependency['version'] = version
dependencies.append(dependency)
if tree_node.label == 'DEPENDENCY-3':
dependency = {}
for child_node in tree_node.leaves():
if child_node.label == 'NAME':
dependency['scope'] = child_node.value
if is_literal_string(child_node.label):
value = child_node.value
value = remove_quotes(value)
# We are assuming `value` is in the form of "namespace:name:version"
split_dependency_string = value.split(':')
if len(split_dependency_string) != 3:
break
namespace, name, version = split_dependency_string
dependency['namespace'] = namespace
dependency['name'] = name
dependency['version'] = version
dependencies.append(dependency)
# TODO: See if you can refactor logic with DEPENDENCY-1
if tree_node.label == 'DEPENDENCY-4':
dependency = {}
last_key = None
for child_node in tree_node.leaves():
if child_node.label == 'NAME':
dependency['scope'] = child_node.value
if child_node.label == 'NAME-LABEL':
value = child_node.value
if value == 'group:':
last_key = 'namespace'
if value == 'name:':
last_key = 'name'
if value == 'version:':
last_key = 'version'
if is_literal_string(child_node.label):
dependency[last_key] = remove_quotes(child_node.value)
dependencies.append(dependency)
if tree_node.label == 'DEPENDENCY-5':
dependency = {}
for child_node in tree_node.leaves():
if child_node.label == 'NAME':
dependency['scope'] = child_node.value
if child_node.label == 'NAME-ATTRIBUTE':
dependency['name'] = child_node.value
dependencies.append(dependency)
return dependencies
def get_dependencies(build_gradle_location):
parse_tree = get_parse_tree(build_gradle_location)
# Parse `parse_tree` for dependencies and print them
return get_dependencies_from_parse_tree(parse_tree)
def build_package(cls, dependencies):
package_dependencies = []
for dependency in dependencies:
# Ignore collected dependencies that do not have a name
name = dependency.get('name', '')
if not name:
continue
namespace = dependency.get('namespace', '')
version = dependency.get('version', '')
scope = dependency.get('scope', '')
is_runtime = True
is_optional = False
if 'test' in scope.lower():
is_runtime = False
is_optional = True
package_dependencies.append(
models.DependentPackage(
purl=PackageURL(
type='build.gradle',
namespace=namespace,
name=name,
version=version
).to_string(),
scope=scope,
requirement=version,
is_runtime=is_runtime,
is_optional=is_optional,
)
)
yield cls(
dependencies=package_dependencies,
)
@attr.s()
class BuildGradle(BaseBuildManifestPackage, models.PackageManifest):
file_patterns = ('build.gradle',)
extensions = ('.gradle',)
# TODO: Not sure what the default type should be, change this to something
# more appropriate later
default_type = 'build.gradle'
@classmethod
def recognize(cls, location):
if not cls.is_manifest(location):
return
dependencies = get_dependencies(location)
return build_package(cls, dependencies)