blob: e41d81a317bb64d8e3445685dd32f8bde8974d4e [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()):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500359 new_key = _map(key)
360 if new_key != key:
361 del d[key]
362 d[new_key] = value
363
364 return info, 'setuptools' in imported_modules, non_literals, extensions
365
366 def get_setup_args_info(self, setupscript='./setup.py'):
367 cmd = ['python', setupscript]
368 info = {}
369 keys = set(self.bbvar_map.keys())
370 keys |= set(self.setuparg_list_fields)
371 keys |= set(self.setuparg_multi_line_values)
372 grouped_keys = itertools.groupby(keys, lambda k: (k in self.setuparg_list_fields, k in self.setuparg_multi_line_values))
373 for index, keys in grouped_keys:
374 if index == (True, False):
375 # Splitlines output for each arg as a list value
376 for key in keys:
377 arg = self.setuparg_map.get(key, key.lower())
378 try:
379 arg_info = self.run_command(cmd + ['--' + arg], cwd=os.path.dirname(setupscript))
380 except (OSError, subprocess.CalledProcessError):
381 pass
382 else:
383 info[key] = [l.rstrip() for l in arg_info.splitlines()]
384 elif index == (False, True):
385 # Entire output for each arg
386 for key in keys:
387 arg = self.setuparg_map.get(key, key.lower())
388 try:
389 arg_info = self.run_command(cmd + ['--' + arg], cwd=os.path.dirname(setupscript))
390 except (OSError, subprocess.CalledProcessError):
391 pass
392 else:
393 info[key] = arg_info
394 else:
395 info.update(self.get_setup_byline(list(keys), setupscript))
396 return info
397
398 def get_setup_byline(self, fields, setupscript='./setup.py'):
399 info = {}
400
401 cmd = ['python', setupscript]
402 cmd.extend('--' + self.setuparg_map.get(f, f.lower()) for f in fields)
403 try:
404 info_lines = self.run_command(cmd, cwd=os.path.dirname(setupscript)).splitlines()
405 except (OSError, subprocess.CalledProcessError):
406 pass
407 else:
408 if len(fields) != len(info_lines):
409 logger.error('Mismatch between setup.py output lines and number of fields')
410 sys.exit(1)
411
412 for lineno, line in enumerate(info_lines):
413 line = line.rstrip()
414 info[fields[lineno]] = line
415 return info
416
417 def apply_info_replacements(self, info):
418 for variable, search, replace in self.replacements:
419 if variable not in info:
420 continue
421
422 def replace_value(search, replace, value):
423 if replace is None:
424 if re.search(search, value):
425 return None
426 else:
427 new_value = re.sub(search, replace, value)
428 if value != new_value:
429 return new_value
430 return value
431
432 value = info[variable]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600433 if isinstance(value, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500434 new_value = replace_value(search, replace, value)
435 if new_value is None:
436 del info[variable]
437 elif new_value != value:
438 info[variable] = new_value
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600439 elif hasattr(value, 'items'):
440 for dkey, dvalue in list(value.items()):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500441 new_list = []
442 for pos, a_value in enumerate(dvalue):
443 new_value = replace_value(search, replace, a_value)
444 if new_value is not None and new_value != value:
445 new_list.append(new_value)
446
447 if value != new_list:
448 value[dkey] = new_list
449 else:
450 new_list = []
451 for pos, a_value in enumerate(value):
452 new_value = replace_value(search, replace, a_value)
453 if new_value is not None and new_value != value:
454 new_list.append(new_value)
455
456 if value != new_list:
457 info[variable] = new_list
458
459 def scan_setup_python_deps(self, srctree, setup_info, setup_non_literals):
460 if 'Package-dir' in setup_info:
461 package_dir = setup_info['Package-dir']
462 else:
463 package_dir = {}
464
465 class PackageDir(distutils.command.build_py.build_py):
466 def __init__(self, package_dir):
467 self.package_dir = package_dir
468
469 pd = PackageDir(package_dir)
470 to_scan = []
471 if not any(v in setup_non_literals for v in ['Py-modules', 'Scripts', 'Packages']):
472 if 'Py-modules' in setup_info:
473 for module in setup_info['Py-modules']:
474 try:
475 package, module = module.rsplit('.', 1)
476 except ValueError:
477 package, module = '.', module
478 module_path = os.path.join(pd.get_package_dir(package), module + '.py')
479 to_scan.append(module_path)
480
481 if 'Packages' in setup_info:
482 for package in setup_info['Packages']:
483 to_scan.append(pd.get_package_dir(package))
484
485 if 'Scripts' in setup_info:
486 to_scan.extend(setup_info['Scripts'])
487 else:
488 logger.info("Scanning the entire source tree, as one or more of the following setup keywords are non-literal: py_modules, scripts, packages.")
489
490 if not to_scan:
491 to_scan = ['.']
492
493 logger.info("Scanning paths for packages & dependencies: %s", ', '.join(to_scan))
494
495 provided_packages = self.parse_pkgdata_for_python_packages()
496 scanned_deps = self.scan_python_dependencies([os.path.join(srctree, p) for p in to_scan])
497 mapped_deps, unmapped_deps = set(self.base_pkgdeps), set()
498 for dep in scanned_deps:
499 mapped = provided_packages.get(dep)
500 if mapped:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600501 logger.debug('Mapped %s to %s' % (dep, mapped))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500502 mapped_deps.add(mapped)
503 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600504 logger.debug('Could not map %s' % dep)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500505 unmapped_deps.add(dep)
506 return mapped_deps, unmapped_deps
507
508 def scan_python_dependencies(self, paths):
509 deps = set()
510 try:
511 dep_output = self.run_command(['pythondeps', '-d'] + paths)
512 except (OSError, subprocess.CalledProcessError):
513 pass
514 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600515 for line in dep_output.decode('utf-8').splitlines():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500516 line = line.rstrip()
517 dep, filename = line.split('\t', 1)
518 if filename.endswith('/setup.py'):
519 continue
520 deps.add(dep)
521
522 try:
523 provides_output = self.run_command(['pythondeps', '-p'] + paths)
524 except (OSError, subprocess.CalledProcessError):
525 pass
526 else:
527 provides_lines = (l.rstrip() for l in provides_output.splitlines())
528 provides = set(l for l in provides_lines if l and l != 'setup')
529 deps -= provides
530
531 return deps
532
533 def parse_pkgdata_for_python_packages(self):
534 suffixes = [t[0] for t in imp.get_suffixes()]
535 pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR', True)
536
537 ldata = tinfoil.config_data.createCopy()
538 bb.parse.handle('classes/python-dir.bbclass', ldata, True)
539 python_sitedir = ldata.getVar('PYTHON_SITEPACKAGES_DIR', True)
540
541 dynload_dir = os.path.join(os.path.dirname(python_sitedir), 'lib-dynload')
542 python_dirs = [python_sitedir + os.sep,
543 os.path.join(os.path.dirname(python_sitedir), 'dist-packages') + os.sep,
544 os.path.dirname(python_sitedir) + os.sep]
545 packages = {}
546 for pkgdatafile in glob.glob('{}/runtime/*'.format(pkgdata_dir)):
547 files_info = None
548 with open(pkgdatafile, 'r') as f:
549 for line in f.readlines():
550 field, value = line.split(': ', 1)
551 if field == 'FILES_INFO':
552 files_info = ast.literal_eval(value)
553 break
554 else:
555 continue
556
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600557 for fn in files_info:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500558 for suffix in suffixes:
559 if fn.endswith(suffix):
560 break
561 else:
562 continue
563
564 if fn.startswith(dynload_dir + os.sep):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600565 if '/.debug/' in fn:
566 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500567 base = os.path.basename(fn)
568 provided = base.split('.', 1)[0]
569 packages[provided] = os.path.basename(pkgdatafile)
570 continue
571
572 for python_dir in python_dirs:
573 if fn.startswith(python_dir):
574 relpath = fn[len(python_dir):]
575 relstart, _, relremaining = relpath.partition(os.sep)
576 if relstart.endswith('.egg'):
577 relpath = relremaining
578 base, _ = os.path.splitext(relpath)
579
580 if '/.debug/' in base:
581 continue
582 if os.path.basename(base) == '__init__':
583 base = os.path.dirname(base)
584 base = base.replace(os.sep + os.sep, os.sep)
585 provided = base.replace(os.sep, '.')
586 packages[provided] = os.path.basename(pkgdatafile)
587 return packages
588
589 @classmethod
590 def run_command(cls, cmd, **popenargs):
591 if 'stderr' not in popenargs:
592 popenargs['stderr'] = subprocess.STDOUT
593 try:
594 return subprocess.check_output(cmd, **popenargs)
595 except OSError as exc:
596 logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc)
597 raise
598 except subprocess.CalledProcessError as exc:
599 logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc.output)
600 raise
601
602
603def gather_setup_info(fileobj):
604 parsed = ast.parse(fileobj.read(), fileobj.name)
605 visitor = SetupScriptVisitor()
606 visitor.visit(parsed)
607
608 non_literals, extensions = {}, []
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600609 for key, value in list(visitor.keywords.items()):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500610 if key == 'ext_modules':
611 if isinstance(value, list):
612 for ext in value:
613 if (isinstance(ext, ast.Call) and
614 isinstance(ext.func, ast.Name) and
615 ext.func.id == 'Extension' and
616 not has_non_literals(ext.args)):
617 extensions.append(ext.args[0])
618 elif has_non_literals(value):
619 non_literals[key] = value
620 del visitor.keywords[key]
621
622 return visitor.keywords, visitor.imported_modules, non_literals, extensions
623
624
625class SetupScriptVisitor(ast.NodeVisitor):
626 def __init__(self):
627 ast.NodeVisitor.__init__(self)
628 self.keywords = {}
629 self.non_literals = []
630 self.imported_modules = set()
631
632 def visit_Expr(self, node):
633 if isinstance(node.value, ast.Call) and \
634 isinstance(node.value.func, ast.Name) and \
635 node.value.func.id == 'setup':
636 self.visit_setup(node.value)
637
638 def visit_setup(self, node):
639 call = LiteralAstTransform().visit(node)
640 self.keywords = call.keywords
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600641 for k, v in self.keywords.items():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500642 if has_non_literals(v):
643 self.non_literals.append(k)
644
645 def visit_Import(self, node):
646 for alias in node.names:
647 self.imported_modules.add(alias.name)
648
649 def visit_ImportFrom(self, node):
650 self.imported_modules.add(node.module)
651
652
653class LiteralAstTransform(ast.NodeTransformer):
654 """Simplify the ast through evaluation of literals."""
655 excluded_fields = ['ctx']
656
657 def visit(self, node):
658 if not isinstance(node, ast.AST):
659 return node
660 else:
661 return ast.NodeTransformer.visit(self, node)
662
663 def generic_visit(self, node):
664 try:
665 return ast.literal_eval(node)
666 except ValueError:
667 for field, value in ast.iter_fields(node):
668 if field in self.excluded_fields:
669 delattr(node, field)
670 if value is None:
671 continue
672
673 if isinstance(value, list):
674 if field in ('keywords', 'kwargs'):
675 new_value = dict((kw.arg, self.visit(kw.value)) for kw in value)
676 else:
677 new_value = [self.visit(i) for i in value]
678 else:
679 new_value = self.visit(value)
680 setattr(node, field, new_value)
681 return node
682
683 def visit_Name(self, node):
684 if hasattr('__builtins__', node.id):
685 return getattr(__builtins__, node.id)
686 else:
687 return self.generic_visit(node)
688
689 def visit_Tuple(self, node):
690 return tuple(self.visit(v) for v in node.elts)
691
692 def visit_List(self, node):
693 return [self.visit(v) for v in node.elts]
694
695 def visit_Set(self, node):
696 return set(self.visit(v) for v in node.elts)
697
698 def visit_Dict(self, node):
699 keys = (self.visit(k) for k in node.keys)
700 values = (self.visit(v) for v in node.values)
701 return dict(zip(keys, values))
702
703
704def has_non_literals(value):
705 if isinstance(value, ast.AST):
706 return True
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600707 elif isinstance(value, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500708 return False
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600709 elif hasattr(value, 'values'):
710 return any(has_non_literals(v) for v in value.values())
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500711 elif hasattr(value, '__iter__'):
712 return any(has_non_literals(v) for v in value)
713
714
715def register_recipe_handlers(handlers):
716 # We need to make sure this is ahead of the makefile fallback handler
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500717 handlers.append((PythonRecipeHandler(), 70))