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