blob: 1a38bd0b14ef775fb6cb5b267f41dc04807b1dbf [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# Recipe creation tool - create build system handler for python
2#
3# Copyright (C) 2015 Mentor Graphics Corporation
4#
Brad Bishopc342db32019-05-15 21:57:59 -04005# SPDX-License-Identifier: GPL-2.0-only
Patrick Williamsc124f4f2015-09-15 14:41:29 -05006#
Patrick Williamsc124f4f2015-09-15 14:41:29 -05007
8import ast
9import codecs
10import collections
11import distutils.command.build_py
12import email
13import imp
14import glob
15import itertools
16import logging
17import os
18import re
19import sys
20import subprocess
21from recipetool.create import RecipeHandler
22
23logger = logging.getLogger('recipetool')
24
25tinfoil = None
26
27
28def tinfoil_init(instance):
29 global tinfoil
30 tinfoil = instance
31
32
33class PythonRecipeHandler(RecipeHandler):
34 base_pkgdeps = ['python-core']
35 excluded_pkgdeps = ['python-dbg']
36 # os.path is provided by python-core
37 assume_provided = ['builtins', 'os.path']
38 # Assumes that the host python builtin_module_names is sane for target too
39 assume_provided = assume_provided + list(sys.builtin_module_names)
40
41 bbvar_map = {
42 'Name': 'PN',
43 'Version': 'PV',
44 'Home-page': 'HOMEPAGE',
45 'Summary': 'SUMMARY',
46 'Description': 'DESCRIPTION',
47 'License': 'LICENSE',
48 'Requires': 'RDEPENDS_${PN}',
49 'Provides': 'RPROVIDES_${PN}',
50 'Obsoletes': 'RREPLACES_${PN}',
51 }
52 # PN/PV are already set by recipetool core & desc can be extremely long
53 excluded_fields = [
Patrick Williamsc124f4f2015-09-15 14:41:29 -050054 'Description',
55 ]
56 setup_parse_map = {
57 'Url': 'Home-page',
58 'Classifiers': 'Classifier',
59 'Description': 'Summary',
60 }
61 setuparg_map = {
62 'Home-page': 'url',
63 'Classifier': 'classifiers',
64 'Summary': 'description',
65 'Description': 'long-description',
66 }
67 # Values which are lists, used by the setup.py argument based metadata
68 # extraction method, to determine how to process the setup.py output.
69 setuparg_list_fields = [
70 'Classifier',
71 'Requires',
72 'Provides',
73 'Obsoletes',
74 'Platform',
75 'Supported-Platform',
76 ]
77 setuparg_multi_line_values = ['Description']
78 replacements = [
Patrick Williamsc0f7c042017-02-23 20:41:17 -060079 ('License', r' +$', ''),
80 ('License', r'^ +', ''),
Patrick Williamsc124f4f2015-09-15 14:41:29 -050081 ('License', r' ', '-'),
Patrick Williamsc0f7c042017-02-23 20:41:17 -060082 ('License', r'^GNU-', ''),
83 ('License', r'-[Ll]icen[cs]e(,?-[Vv]ersion)?', ''),
Patrick Williamsc124f4f2015-09-15 14:41:29 -050084 ('License', r'^UNKNOWN$', ''),
85
86 # Remove currently unhandled version numbers from these variables
87 ('Requires', r' *\([^)]*\)', ''),
88 ('Provides', r' *\([^)]*\)', ''),
89 ('Obsoletes', r' *\([^)]*\)', ''),
90 ('Install-requires', r'^([^><= ]+).*', r'\1'),
91 ('Extras-require', r'^([^><= ]+).*', r'\1'),
92 ('Tests-require', r'^([^><= ]+).*', r'\1'),
93
94 # Remove unhandled dependency on particular features (e.g. foo[PDF])
95 ('Install-requires', r'\[[^\]]+\]$', ''),
96 ]
97
98 classifier_license_map = {
99 'License :: OSI Approved :: Academic Free License (AFL)': 'AFL',
100 'License :: OSI Approved :: Apache Software License': 'Apache',
101 'License :: OSI Approved :: Apple Public Source License': 'APSL',
102 'License :: OSI Approved :: Artistic License': 'Artistic',
103 'License :: OSI Approved :: Attribution Assurance License': 'AAL',
104 'License :: OSI Approved :: BSD License': 'BSD',
105 'License :: OSI Approved :: Common Public License': 'CPL',
106 'License :: OSI Approved :: Eiffel Forum License': 'EFL',
107 'License :: OSI Approved :: European Union Public Licence 1.0 (EUPL 1.0)': 'EUPL-1.0',
108 'License :: OSI Approved :: European Union Public Licence 1.1 (EUPL 1.1)': 'EUPL-1.1',
109 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)': 'AGPL-3.0+',
110 'License :: OSI Approved :: GNU Affero General Public License v3': 'AGPL-3.0',
111 'License :: OSI Approved :: GNU Free Documentation License (FDL)': 'GFDL',
112 'License :: OSI Approved :: GNU General Public License (GPL)': 'GPL',
113 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)': 'GPL-2.0',
114 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)': 'GPL-2.0+',
115 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)': 'GPL-3.0',
116 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)': 'GPL-3.0+',
117 'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)': 'LGPL-2.0',
118 'License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)': 'LGPL-2.0+',
119 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)': 'LGPL-3.0',
120 'License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)': 'LGPL-3.0+',
121 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)': 'LGPL',
122 'License :: OSI Approved :: IBM Public License': 'IPL',
123 'License :: OSI Approved :: ISC License (ISCL)': 'ISC',
124 'License :: OSI Approved :: Intel Open Source License': 'Intel',
125 'License :: OSI Approved :: Jabber Open Source License': 'Jabber',
126 'License :: OSI Approved :: MIT License': 'MIT',
127 'License :: OSI Approved :: MITRE Collaborative Virtual Workspace License (CVW)': 'CVWL',
128 'License :: OSI Approved :: Motosoto License': 'Motosoto',
129 'License :: OSI Approved :: Mozilla Public License 1.0 (MPL)': 'MPL-1.0',
130 'License :: OSI Approved :: Mozilla Public License 1.1 (MPL 1.1)': 'MPL-1.1',
131 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)': 'MPL-2.0',
132 'License :: OSI Approved :: Nethack General Public License': 'NGPL',
133 'License :: OSI Approved :: Nokia Open Source License': 'Nokia',
134 'License :: OSI Approved :: Open Group Test Suite License': 'OGTSL',
135 'License :: OSI Approved :: Python License (CNRI Python License)': 'CNRI-Python',
136 'License :: OSI Approved :: Python Software Foundation License': 'PSF',
137 'License :: OSI Approved :: Qt Public License (QPL)': 'QPL',
138 'License :: OSI Approved :: Ricoh Source Code Public License': 'RSCPL',
139 'License :: OSI Approved :: Sleepycat License': 'Sleepycat',
140 'License :: OSI Approved :: Sun Industry Standards Source License (SISSL)': '-- Sun Industry Standards Source License (SISSL)',
141 'License :: OSI Approved :: Sun Public License': 'SPL',
142 'License :: OSI Approved :: University of Illinois/NCSA Open Source License': 'NCSA',
143 'License :: OSI Approved :: Vovida Software License 1.0': 'VSL-1.0',
144 'License :: OSI Approved :: W3C License': 'W3C',
145 'License :: OSI Approved :: X.Net License': 'Xnet',
146 'License :: OSI Approved :: Zope Public License': 'ZPL',
147 'License :: OSI Approved :: zlib/libpng License': 'Zlib',
148 }
149
150 def __init__(self):
151 pass
152
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500153 def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500154 if 'buildsystem' in handled:
155 return False
156
157 if not RecipeHandler.checkfiles(srctree, ['setup.py']):
158 return
159
160 # setup.py is always parsed to get at certain required information, such as
161 # distutils vs setuptools
162 #
163 # If egg info is available, we use it for both its PKG-INFO metadata
164 # and for its requires.txt for install_requires.
165 # If PKG-INFO is available but no egg info is, we use that for metadata in preference to
166 # the parsed setup.py, but use the install_requires info from the
167 # parsed setup.py.
168
169 setupscript = os.path.join(srctree, 'setup.py')
170 try:
171 setup_info, uses_setuptools, setup_non_literals, extensions = self.parse_setup_py(setupscript)
172 except Exception:
173 logger.exception("Failed to parse setup.py")
174 setup_info, uses_setuptools, setup_non_literals, extensions = {}, True, [], []
175
176 egginfo = glob.glob(os.path.join(srctree, '*.egg-info'))
177 if egginfo:
178 info = self.get_pkginfo(os.path.join(egginfo[0], 'PKG-INFO'))
179 requires_txt = os.path.join(egginfo[0], 'requires.txt')
180 if os.path.exists(requires_txt):
181 with codecs.open(requires_txt) as f:
182 inst_req = []
183 extras_req = collections.defaultdict(list)
184 current_feature = None
185 for line in f.readlines():
186 line = line.rstrip()
187 if not line:
188 continue
189
190 if line.startswith('['):
191 current_feature = line[1:-1]
192 elif current_feature:
193 extras_req[current_feature].append(line)
194 else:
195 inst_req.append(line)
196 info['Install-requires'] = inst_req
197 info['Extras-require'] = extras_req
198 elif RecipeHandler.checkfiles(srctree, ['PKG-INFO']):
199 info = self.get_pkginfo(os.path.join(srctree, 'PKG-INFO'))
200
201 if setup_info:
202 if 'Install-requires' in setup_info:
203 info['Install-requires'] = setup_info['Install-requires']
204 if 'Extras-require' in setup_info:
205 info['Extras-require'] = setup_info['Extras-require']
206 else:
207 if setup_info:
208 info = setup_info
209 else:
210 info = self.get_setup_args_info(setupscript)
211
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600212 # Grab the license value before applying replacements
213 license_str = info.get('License', '').strip()
214
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500215 self.apply_info_replacements(info)
216
217 if uses_setuptools:
218 classes.append('setuptools')
219 else:
220 classes.append('distutils')
221
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600222 if license_str:
223 for i, line in enumerate(lines_before):
224 if line.startswith('LICENSE = '):
225 lines_before.insert(i, '# NOTE: License in setup.py/PKGINFO is: %s' % license_str)
226 break
227
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500228 if 'Classifier' in info:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600229 existing_licenses = info.get('License', '')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500230 licenses = []
231 for classifier in info['Classifier']:
232 if classifier in self.classifier_license_map:
233 license = self.classifier_license_map[classifier]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600234 if license == 'Apache' and 'Apache-2.0' in existing_licenses:
235 license = 'Apache-2.0'
236 elif license == 'GPL':
237 if 'GPL-2.0' in existing_licenses or 'GPLv2' in existing_licenses:
238 license = 'GPL-2.0'
239 elif 'GPL-3.0' in existing_licenses or 'GPLv3' in existing_licenses:
240 license = 'GPL-3.0'
241 elif license == 'LGPL':
242 if 'LGPL-2.1' in existing_licenses or 'LGPLv2.1' in existing_licenses:
243 license = 'LGPL-2.1'
244 elif 'LGPL-2.0' in existing_licenses or 'LGPLv2' in existing_licenses:
245 license = 'LGPL-2.0'
246 elif 'LGPL-3.0' in existing_licenses or 'LGPLv3' in existing_licenses:
247 license = 'LGPL-3.0'
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500248 licenses.append(license)
249
250 if licenses:
251 info['License'] = ' & '.join(licenses)
252
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500253 # Map PKG-INFO & setup.py fields to bitbake variables
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600254 for field, values in info.items():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500255 if field in self.excluded_fields:
256 continue
257
258 if field not in self.bbvar_map:
259 continue
260
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600261 if isinstance(values, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500262 value = values
263 else:
264 value = ' '.join(str(v) for v in values if v)
265
266 bbvar = self.bbvar_map[field]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600267 if bbvar not in extravalues and value:
268 extravalues[bbvar] = value
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500269
270 mapped_deps, unmapped_deps = self.scan_setup_python_deps(srctree, setup_info, setup_non_literals)
271
272 extras_req = set()
273 if 'Extras-require' in info:
274 extras_req = info['Extras-require']
275 if extras_req:
276 lines_after.append('# The following configs & dependencies are from setuptools extras_require.')
277 lines_after.append('# These dependencies are optional, hence can be controlled via PACKAGECONFIG.')
278 lines_after.append('# The upstream names may not correspond exactly to bitbake package names.')
279 lines_after.append('#')
280 lines_after.append('# Uncomment this line to enable all the optional features.')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600281 lines_after.append('#PACKAGECONFIG ?= "{}"'.format(' '.join(k.lower() for k in extras_req)))
282 for feature, feature_reqs in extras_req.items():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500283 unmapped_deps.difference_update(feature_reqs)
284
285 feature_req_deps = ('python-' + r.replace('.', '-').lower() for r in sorted(feature_reqs))
286 lines_after.append('PACKAGECONFIG[{}] = ",,,{}"'.format(feature.lower(), ' '.join(feature_req_deps)))
287
288 inst_reqs = set()
289 if 'Install-requires' in info:
290 if extras_req:
291 lines_after.append('')
292 inst_reqs = info['Install-requires']
293 if inst_reqs:
294 unmapped_deps.difference_update(inst_reqs)
295
296 inst_req_deps = ('python-' + r.replace('.', '-').lower() for r in sorted(inst_reqs))
297 lines_after.append('# WARNING: the following rdepends are from setuptools install_requires. These')
298 lines_after.append('# upstream names may not correspond exactly to bitbake package names.')
299 lines_after.append('RDEPENDS_${{PN}} += "{}"'.format(' '.join(inst_req_deps)))
300
301 if mapped_deps:
302 name = info.get('Name')
303 if name and name[0] in mapped_deps:
304 # Attempt to avoid self-reference
305 mapped_deps.remove(name[0])
306 mapped_deps -= set(self.excluded_pkgdeps)
307 if inst_reqs or extras_req:
308 lines_after.append('')
309 lines_after.append('# WARNING: the following rdepends are determined through basic analysis of the')
310 lines_after.append('# python sources, and might not be 100% accurate.')
311 lines_after.append('RDEPENDS_${{PN}} += "{}"'.format(' '.join(sorted(mapped_deps))))
312
313 unmapped_deps -= set(extensions)
314 unmapped_deps -= set(self.assume_provided)
315 if unmapped_deps:
316 if mapped_deps:
317 lines_after.append('')
318 lines_after.append('# WARNING: We were unable to map the following python package/module')
319 lines_after.append('# dependencies to the bitbake packages which include them:')
320 lines_after.extend('# {}'.format(d) for d in sorted(unmapped_deps))
321
322 handled.append('buildsystem')
323
324 def get_pkginfo(self, pkginfo_fn):
325 msg = email.message_from_file(open(pkginfo_fn, 'r'))
326 msginfo = {}
327 for field in msg.keys():
328 values = msg.get_all(field)
329 if len(values) == 1:
330 msginfo[field] = values[0]
331 else:
332 msginfo[field] = values
333 return msginfo
334
335 def parse_setup_py(self, setupscript='./setup.py'):
336 with codecs.open(setupscript) as f:
337 info, imported_modules, non_literals, extensions = gather_setup_info(f)
338
339 def _map(key):
340 key = key.replace('_', '-')
341 key = key[0].upper() + key[1:]
342 if key in self.setup_parse_map:
343 key = self.setup_parse_map[key]
344 return key
345
346 # Naive mapping of setup() arguments to PKG-INFO field names
347 for d in [info, non_literals]:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600348 for key, value in list(d.items()):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500349 if key is None:
350 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500351 new_key = _map(key)
352 if new_key != key:
353 del d[key]
354 d[new_key] = value
355
356 return info, 'setuptools' in imported_modules, non_literals, extensions
357
358 def get_setup_args_info(self, setupscript='./setup.py'):
359 cmd = ['python', setupscript]
360 info = {}
361 keys = set(self.bbvar_map.keys())
362 keys |= set(self.setuparg_list_fields)
363 keys |= set(self.setuparg_multi_line_values)
364 grouped_keys = itertools.groupby(keys, lambda k: (k in self.setuparg_list_fields, k in self.setuparg_multi_line_values))
365 for index, keys in grouped_keys:
366 if index == (True, False):
367 # Splitlines output for each arg as a list value
368 for key in keys:
369 arg = self.setuparg_map.get(key, key.lower())
370 try:
371 arg_info = self.run_command(cmd + ['--' + arg], cwd=os.path.dirname(setupscript))
372 except (OSError, subprocess.CalledProcessError):
373 pass
374 else:
375 info[key] = [l.rstrip() for l in arg_info.splitlines()]
376 elif index == (False, True):
377 # Entire output for each arg
378 for key in keys:
379 arg = self.setuparg_map.get(key, key.lower())
380 try:
381 arg_info = self.run_command(cmd + ['--' + arg], cwd=os.path.dirname(setupscript))
382 except (OSError, subprocess.CalledProcessError):
383 pass
384 else:
385 info[key] = arg_info
386 else:
387 info.update(self.get_setup_byline(list(keys), setupscript))
388 return info
389
390 def get_setup_byline(self, fields, setupscript='./setup.py'):
391 info = {}
392
393 cmd = ['python', setupscript]
394 cmd.extend('--' + self.setuparg_map.get(f, f.lower()) for f in fields)
395 try:
396 info_lines = self.run_command(cmd, cwd=os.path.dirname(setupscript)).splitlines()
397 except (OSError, subprocess.CalledProcessError):
398 pass
399 else:
400 if len(fields) != len(info_lines):
401 logger.error('Mismatch between setup.py output lines and number of fields')
402 sys.exit(1)
403
404 for lineno, line in enumerate(info_lines):
405 line = line.rstrip()
406 info[fields[lineno]] = line
407 return info
408
409 def apply_info_replacements(self, info):
410 for variable, search, replace in self.replacements:
411 if variable not in info:
412 continue
413
414 def replace_value(search, replace, value):
415 if replace is None:
416 if re.search(search, value):
417 return None
418 else:
419 new_value = re.sub(search, replace, value)
420 if value != new_value:
421 return new_value
422 return value
423
424 value = info[variable]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600425 if isinstance(value, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500426 new_value = replace_value(search, replace, value)
427 if new_value is None:
428 del info[variable]
429 elif new_value != value:
430 info[variable] = new_value
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600431 elif hasattr(value, 'items'):
432 for dkey, dvalue in list(value.items()):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500433 new_list = []
434 for pos, a_value in enumerate(dvalue):
435 new_value = replace_value(search, replace, a_value)
436 if new_value is not None and new_value != value:
437 new_list.append(new_value)
438
439 if value != new_list:
440 value[dkey] = new_list
441 else:
442 new_list = []
443 for pos, a_value in enumerate(value):
444 new_value = replace_value(search, replace, a_value)
445 if new_value is not None and new_value != value:
446 new_list.append(new_value)
447
448 if value != new_list:
449 info[variable] = new_list
450
451 def scan_setup_python_deps(self, srctree, setup_info, setup_non_literals):
452 if 'Package-dir' in setup_info:
453 package_dir = setup_info['Package-dir']
454 else:
455 package_dir = {}
456
457 class PackageDir(distutils.command.build_py.build_py):
458 def __init__(self, package_dir):
459 self.package_dir = package_dir
460
461 pd = PackageDir(package_dir)
462 to_scan = []
463 if not any(v in setup_non_literals for v in ['Py-modules', 'Scripts', 'Packages']):
464 if 'Py-modules' in setup_info:
465 for module in setup_info['Py-modules']:
466 try:
467 package, module = module.rsplit('.', 1)
468 except ValueError:
469 package, module = '.', module
470 module_path = os.path.join(pd.get_package_dir(package), module + '.py')
471 to_scan.append(module_path)
472
473 if 'Packages' in setup_info:
474 for package in setup_info['Packages']:
475 to_scan.append(pd.get_package_dir(package))
476
477 if 'Scripts' in setup_info:
478 to_scan.extend(setup_info['Scripts'])
479 else:
480 logger.info("Scanning the entire source tree, as one or more of the following setup keywords are non-literal: py_modules, scripts, packages.")
481
482 if not to_scan:
483 to_scan = ['.']
484
485 logger.info("Scanning paths for packages & dependencies: %s", ', '.join(to_scan))
486
487 provided_packages = self.parse_pkgdata_for_python_packages()
488 scanned_deps = self.scan_python_dependencies([os.path.join(srctree, p) for p in to_scan])
489 mapped_deps, unmapped_deps = set(self.base_pkgdeps), set()
490 for dep in scanned_deps:
491 mapped = provided_packages.get(dep)
492 if mapped:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600493 logger.debug('Mapped %s to %s' % (dep, mapped))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500494 mapped_deps.add(mapped)
495 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600496 logger.debug('Could not map %s' % dep)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500497 unmapped_deps.add(dep)
498 return mapped_deps, unmapped_deps
499
500 def scan_python_dependencies(self, paths):
501 deps = set()
502 try:
503 dep_output = self.run_command(['pythondeps', '-d'] + paths)
504 except (OSError, subprocess.CalledProcessError):
505 pass
506 else:
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500507 for line in dep_output.splitlines():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500508 line = line.rstrip()
509 dep, filename = line.split('\t', 1)
510 if filename.endswith('/setup.py'):
511 continue
512 deps.add(dep)
513
514 try:
515 provides_output = self.run_command(['pythondeps', '-p'] + paths)
516 except (OSError, subprocess.CalledProcessError):
517 pass
518 else:
519 provides_lines = (l.rstrip() for l in provides_output.splitlines())
520 provides = set(l for l in provides_lines if l and l != 'setup')
521 deps -= provides
522
523 return deps
524
525 def parse_pkgdata_for_python_packages(self):
526 suffixes = [t[0] for t in imp.get_suffixes()]
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500527 pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500528
529 ldata = tinfoil.config_data.createCopy()
530 bb.parse.handle('classes/python-dir.bbclass', ldata, True)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500531 python_sitedir = ldata.getVar('PYTHON_SITEPACKAGES_DIR')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500532
533 dynload_dir = os.path.join(os.path.dirname(python_sitedir), 'lib-dynload')
534 python_dirs = [python_sitedir + os.sep,
535 os.path.join(os.path.dirname(python_sitedir), 'dist-packages') + os.sep,
536 os.path.dirname(python_sitedir) + os.sep]
537 packages = {}
538 for pkgdatafile in glob.glob('{}/runtime/*'.format(pkgdata_dir)):
539 files_info = None
540 with open(pkgdatafile, 'r') as f:
541 for line in f.readlines():
542 field, value = line.split(': ', 1)
543 if field == 'FILES_INFO':
544 files_info = ast.literal_eval(value)
545 break
546 else:
547 continue
548
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600549 for fn in files_info:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500550 for suffix in suffixes:
551 if fn.endswith(suffix):
552 break
553 else:
554 continue
555
556 if fn.startswith(dynload_dir + os.sep):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600557 if '/.debug/' in fn:
558 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500559 base = os.path.basename(fn)
560 provided = base.split('.', 1)[0]
561 packages[provided] = os.path.basename(pkgdatafile)
562 continue
563
564 for python_dir in python_dirs:
565 if fn.startswith(python_dir):
566 relpath = fn[len(python_dir):]
567 relstart, _, relremaining = relpath.partition(os.sep)
568 if relstart.endswith('.egg'):
569 relpath = relremaining
570 base, _ = os.path.splitext(relpath)
571
572 if '/.debug/' in base:
573 continue
574 if os.path.basename(base) == '__init__':
575 base = os.path.dirname(base)
576 base = base.replace(os.sep + os.sep, os.sep)
577 provided = base.replace(os.sep, '.')
578 packages[provided] = os.path.basename(pkgdatafile)
579 return packages
580
581 @classmethod
582 def run_command(cls, cmd, **popenargs):
583 if 'stderr' not in popenargs:
584 popenargs['stderr'] = subprocess.STDOUT
585 try:
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500586 return subprocess.check_output(cmd, **popenargs).decode('utf-8')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500587 except OSError as exc:
588 logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc)
589 raise
590 except subprocess.CalledProcessError as exc:
591 logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc.output)
592 raise
593
594
595def gather_setup_info(fileobj):
596 parsed = ast.parse(fileobj.read(), fileobj.name)
597 visitor = SetupScriptVisitor()
598 visitor.visit(parsed)
599
600 non_literals, extensions = {}, []
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600601 for key, value in list(visitor.keywords.items()):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500602 if key == 'ext_modules':
603 if isinstance(value, list):
604 for ext in value:
605 if (isinstance(ext, ast.Call) and
606 isinstance(ext.func, ast.Name) and
607 ext.func.id == 'Extension' and
608 not has_non_literals(ext.args)):
609 extensions.append(ext.args[0])
610 elif has_non_literals(value):
611 non_literals[key] = value
612 del visitor.keywords[key]
613
614 return visitor.keywords, visitor.imported_modules, non_literals, extensions
615
616
617class SetupScriptVisitor(ast.NodeVisitor):
618 def __init__(self):
619 ast.NodeVisitor.__init__(self)
620 self.keywords = {}
621 self.non_literals = []
622 self.imported_modules = set()
623
624 def visit_Expr(self, node):
625 if isinstance(node.value, ast.Call) and \
626 isinstance(node.value.func, ast.Name) and \
627 node.value.func.id == 'setup':
628 self.visit_setup(node.value)
629
630 def visit_setup(self, node):
631 call = LiteralAstTransform().visit(node)
632 self.keywords = call.keywords
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600633 for k, v in self.keywords.items():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500634 if has_non_literals(v):
635 self.non_literals.append(k)
636
637 def visit_Import(self, node):
638 for alias in node.names:
639 self.imported_modules.add(alias.name)
640
641 def visit_ImportFrom(self, node):
642 self.imported_modules.add(node.module)
643
644
645class LiteralAstTransform(ast.NodeTransformer):
646 """Simplify the ast through evaluation of literals."""
647 excluded_fields = ['ctx']
648
649 def visit(self, node):
650 if not isinstance(node, ast.AST):
651 return node
652 else:
653 return ast.NodeTransformer.visit(self, node)
654
655 def generic_visit(self, node):
656 try:
657 return ast.literal_eval(node)
658 except ValueError:
659 for field, value in ast.iter_fields(node):
660 if field in self.excluded_fields:
661 delattr(node, field)
662 if value is None:
663 continue
664
665 if isinstance(value, list):
666 if field in ('keywords', 'kwargs'):
667 new_value = dict((kw.arg, self.visit(kw.value)) for kw in value)
668 else:
669 new_value = [self.visit(i) for i in value]
670 else:
671 new_value = self.visit(value)
672 setattr(node, field, new_value)
673 return node
674
675 def visit_Name(self, node):
676 if hasattr('__builtins__', node.id):
677 return getattr(__builtins__, node.id)
678 else:
679 return self.generic_visit(node)
680
681 def visit_Tuple(self, node):
682 return tuple(self.visit(v) for v in node.elts)
683
684 def visit_List(self, node):
685 return [self.visit(v) for v in node.elts]
686
687 def visit_Set(self, node):
688 return set(self.visit(v) for v in node.elts)
689
690 def visit_Dict(self, node):
691 keys = (self.visit(k) for k in node.keys)
692 values = (self.visit(v) for v in node.values)
693 return dict(zip(keys, values))
694
695
696def has_non_literals(value):
697 if isinstance(value, ast.AST):
698 return True
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600699 elif isinstance(value, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500700 return False
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600701 elif hasattr(value, 'values'):
702 return any(has_non_literals(v) for v in value.values())
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500703 elif hasattr(value, '__iter__'):
704 return any(has_non_literals(v) for v in value)
705
706
707def register_recipe_handlers(handlers):
708 # We need to make sure this is ahead of the makefile fallback handler
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500709 handlers.append((PythonRecipeHandler(), 70))