blob: c3823307a42f854aaf46fe6c0750f82c983d9c02 [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 = [
64 'Name',
65 'Version',
66 'Description',
67 ]
68 setup_parse_map = {
69 'Url': 'Home-page',
70 'Classifiers': 'Classifier',
71 'Description': 'Summary',
72 }
73 setuparg_map = {
74 'Home-page': 'url',
75 'Classifier': 'classifiers',
76 'Summary': 'description',
77 'Description': 'long-description',
78 }
79 # Values which are lists, used by the setup.py argument based metadata
80 # extraction method, to determine how to process the setup.py output.
81 setuparg_list_fields = [
82 'Classifier',
83 'Requires',
84 'Provides',
85 'Obsoletes',
86 'Platform',
87 'Supported-Platform',
88 ]
89 setuparg_multi_line_values = ['Description']
90 replacements = [
91 ('License', r' ', '-'),
92 ('License', r'-License$', ''),
93 ('License', r'^UNKNOWN$', ''),
94
95 # Remove currently unhandled version numbers from these variables
96 ('Requires', r' *\([^)]*\)', ''),
97 ('Provides', r' *\([^)]*\)', ''),
98 ('Obsoletes', r' *\([^)]*\)', ''),
99 ('Install-requires', r'^([^><= ]+).*', r'\1'),
100 ('Extras-require', r'^([^><= ]+).*', r'\1'),
101 ('Tests-require', r'^([^><= ]+).*', r'\1'),
102
103 # Remove unhandled dependency on particular features (e.g. foo[PDF])
104 ('Install-requires', r'\[[^\]]+\]$', ''),
105 ]
106
107 classifier_license_map = {
108 'License :: OSI Approved :: Academic Free License (AFL)': 'AFL',
109 'License :: OSI Approved :: Apache Software License': 'Apache',
110 'License :: OSI Approved :: Apple Public Source License': 'APSL',
111 'License :: OSI Approved :: Artistic License': 'Artistic',
112 'License :: OSI Approved :: Attribution Assurance License': 'AAL',
113 'License :: OSI Approved :: BSD License': 'BSD',
114 'License :: OSI Approved :: Common Public License': 'CPL',
115 'License :: OSI Approved :: Eiffel Forum License': 'EFL',
116 'License :: OSI Approved :: European Union Public Licence 1.0 (EUPL 1.0)': 'EUPL-1.0',
117 'License :: OSI Approved :: European Union Public Licence 1.1 (EUPL 1.1)': 'EUPL-1.1',
118 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)': 'AGPL-3.0+',
119 'License :: OSI Approved :: GNU Affero General Public License v3': 'AGPL-3.0',
120 'License :: OSI Approved :: GNU Free Documentation License (FDL)': 'GFDL',
121 'License :: OSI Approved :: GNU General Public License (GPL)': 'GPL',
122 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)': 'GPL-2.0',
123 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)': 'GPL-2.0+',
124 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)': 'GPL-3.0',
125 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)': 'GPL-3.0+',
126 'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)': 'LGPL-2.0',
127 'License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)': 'LGPL-2.0+',
128 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)': 'LGPL-3.0',
129 'License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)': 'LGPL-3.0+',
130 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)': 'LGPL',
131 'License :: OSI Approved :: IBM Public License': 'IPL',
132 'License :: OSI Approved :: ISC License (ISCL)': 'ISC',
133 'License :: OSI Approved :: Intel Open Source License': 'Intel',
134 'License :: OSI Approved :: Jabber Open Source License': 'Jabber',
135 'License :: OSI Approved :: MIT License': 'MIT',
136 'License :: OSI Approved :: MITRE Collaborative Virtual Workspace License (CVW)': 'CVWL',
137 'License :: OSI Approved :: Motosoto License': 'Motosoto',
138 'License :: OSI Approved :: Mozilla Public License 1.0 (MPL)': 'MPL-1.0',
139 'License :: OSI Approved :: Mozilla Public License 1.1 (MPL 1.1)': 'MPL-1.1',
140 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)': 'MPL-2.0',
141 'License :: OSI Approved :: Nethack General Public License': 'NGPL',
142 'License :: OSI Approved :: Nokia Open Source License': 'Nokia',
143 'License :: OSI Approved :: Open Group Test Suite License': 'OGTSL',
144 'License :: OSI Approved :: Python License (CNRI Python License)': 'CNRI-Python',
145 'License :: OSI Approved :: Python Software Foundation License': 'PSF',
146 'License :: OSI Approved :: Qt Public License (QPL)': 'QPL',
147 'License :: OSI Approved :: Ricoh Source Code Public License': 'RSCPL',
148 'License :: OSI Approved :: Sleepycat License': 'Sleepycat',
149 'License :: OSI Approved :: Sun Industry Standards Source License (SISSL)': '-- Sun Industry Standards Source License (SISSL)',
150 'License :: OSI Approved :: Sun Public License': 'SPL',
151 'License :: OSI Approved :: University of Illinois/NCSA Open Source License': 'NCSA',
152 'License :: OSI Approved :: Vovida Software License 1.0': 'VSL-1.0',
153 'License :: OSI Approved :: W3C License': 'W3C',
154 'License :: OSI Approved :: X.Net License': 'Xnet',
155 'License :: OSI Approved :: Zope Public License': 'ZPL',
156 'License :: OSI Approved :: zlib/libpng License': 'Zlib',
157 }
158
159 def __init__(self):
160 pass
161
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500162 def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500163 if 'buildsystem' in handled:
164 return False
165
166 if not RecipeHandler.checkfiles(srctree, ['setup.py']):
167 return
168
169 # setup.py is always parsed to get at certain required information, such as
170 # distutils vs setuptools
171 #
172 # If egg info is available, we use it for both its PKG-INFO metadata
173 # and for its requires.txt for install_requires.
174 # If PKG-INFO is available but no egg info is, we use that for metadata in preference to
175 # the parsed setup.py, but use the install_requires info from the
176 # parsed setup.py.
177
178 setupscript = os.path.join(srctree, 'setup.py')
179 try:
180 setup_info, uses_setuptools, setup_non_literals, extensions = self.parse_setup_py(setupscript)
181 except Exception:
182 logger.exception("Failed to parse setup.py")
183 setup_info, uses_setuptools, setup_non_literals, extensions = {}, True, [], []
184
185 egginfo = glob.glob(os.path.join(srctree, '*.egg-info'))
186 if egginfo:
187 info = self.get_pkginfo(os.path.join(egginfo[0], 'PKG-INFO'))
188 requires_txt = os.path.join(egginfo[0], 'requires.txt')
189 if os.path.exists(requires_txt):
190 with codecs.open(requires_txt) as f:
191 inst_req = []
192 extras_req = collections.defaultdict(list)
193 current_feature = None
194 for line in f.readlines():
195 line = line.rstrip()
196 if not line:
197 continue
198
199 if line.startswith('['):
200 current_feature = line[1:-1]
201 elif current_feature:
202 extras_req[current_feature].append(line)
203 else:
204 inst_req.append(line)
205 info['Install-requires'] = inst_req
206 info['Extras-require'] = extras_req
207 elif RecipeHandler.checkfiles(srctree, ['PKG-INFO']):
208 info = self.get_pkginfo(os.path.join(srctree, 'PKG-INFO'))
209
210 if setup_info:
211 if 'Install-requires' in setup_info:
212 info['Install-requires'] = setup_info['Install-requires']
213 if 'Extras-require' in setup_info:
214 info['Extras-require'] = setup_info['Extras-require']
215 else:
216 if setup_info:
217 info = setup_info
218 else:
219 info = self.get_setup_args_info(setupscript)
220
221 self.apply_info_replacements(info)
222
223 if uses_setuptools:
224 classes.append('setuptools')
225 else:
226 classes.append('distutils')
227
228 if 'Classifier' in info:
229 licenses = []
230 for classifier in info['Classifier']:
231 if classifier in self.classifier_license_map:
232 license = self.classifier_license_map[classifier]
233 licenses.append(license)
234
235 if licenses:
236 info['License'] = ' & '.join(licenses)
237
238
239 # Map PKG-INFO & setup.py fields to bitbake variables
240 bbinfo = {}
241 for field, values in info.iteritems():
242 if field in self.excluded_fields:
243 continue
244
245 if field not in self.bbvar_map:
246 continue
247
248 if isinstance(values, basestring):
249 value = values
250 else:
251 value = ' '.join(str(v) for v in values if v)
252
253 bbvar = self.bbvar_map[field]
254 if bbvar not in bbinfo and value:
255 bbinfo[bbvar] = value
256
257 comment_lic_line = None
258 for pos, line in enumerate(list(lines_before)):
259 if line.startswith('#') and 'LICENSE' in line:
260 comment_lic_line = pos
261 elif line.startswith('LICENSE =') and 'LICENSE' in bbinfo:
262 if line in ('LICENSE = "Unknown"', 'LICENSE = "CLOSED"'):
263 lines_before[pos] = 'LICENSE = "{}"'.format(bbinfo['LICENSE'])
264 if line == 'LICENSE = "CLOSED"' and comment_lic_line:
265 lines_before[comment_lic_line:pos] = [
266 '# WARNING: the following LICENSE value is a best guess - it is your',
267 '# responsibility to verify that the value is complete and correct.'
268 ]
269 del bbinfo['LICENSE']
270
271 src_uri_line = None
272 for pos, line in enumerate(lines_before):
273 if line.startswith('SRC_URI ='):
274 src_uri_line = pos
275
276 if bbinfo:
277 mdinfo = ['']
278 for k in sorted(bbinfo):
279 v = bbinfo[k]
280 mdinfo.append('{} = "{}"'.format(k, v))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500281 if src_uri_line:
282 lines_before[src_uri_line-1:src_uri_line-1] = mdinfo
283 else:
284 lines_before.extend(mdinfo)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500285
286 mapped_deps, unmapped_deps = self.scan_setup_python_deps(srctree, setup_info, setup_non_literals)
287
288 extras_req = set()
289 if 'Extras-require' in info:
290 extras_req = info['Extras-require']
291 if extras_req:
292 lines_after.append('# The following configs & dependencies are from setuptools extras_require.')
293 lines_after.append('# These dependencies are optional, hence can be controlled via PACKAGECONFIG.')
294 lines_after.append('# The upstream names may not correspond exactly to bitbake package names.')
295 lines_after.append('#')
296 lines_after.append('# Uncomment this line to enable all the optional features.')
297 lines_after.append('#PACKAGECONFIG ?= "{}"'.format(' '.join(k.lower() for k in extras_req.iterkeys())))
298 for feature, feature_reqs in extras_req.iteritems():
299 unmapped_deps.difference_update(feature_reqs)
300
301 feature_req_deps = ('python-' + r.replace('.', '-').lower() for r in sorted(feature_reqs))
302 lines_after.append('PACKAGECONFIG[{}] = ",,,{}"'.format(feature.lower(), ' '.join(feature_req_deps)))
303
304 inst_reqs = set()
305 if 'Install-requires' in info:
306 if extras_req:
307 lines_after.append('')
308 inst_reqs = info['Install-requires']
309 if inst_reqs:
310 unmapped_deps.difference_update(inst_reqs)
311
312 inst_req_deps = ('python-' + r.replace('.', '-').lower() for r in sorted(inst_reqs))
313 lines_after.append('# WARNING: the following rdepends are from setuptools install_requires. These')
314 lines_after.append('# upstream names may not correspond exactly to bitbake package names.')
315 lines_after.append('RDEPENDS_${{PN}} += "{}"'.format(' '.join(inst_req_deps)))
316
317 if mapped_deps:
318 name = info.get('Name')
319 if name and name[0] in mapped_deps:
320 # Attempt to avoid self-reference
321 mapped_deps.remove(name[0])
322 mapped_deps -= set(self.excluded_pkgdeps)
323 if inst_reqs or extras_req:
324 lines_after.append('')
325 lines_after.append('# WARNING: the following rdepends are determined through basic analysis of the')
326 lines_after.append('# python sources, and might not be 100% accurate.')
327 lines_after.append('RDEPENDS_${{PN}} += "{}"'.format(' '.join(sorted(mapped_deps))))
328
329 unmapped_deps -= set(extensions)
330 unmapped_deps -= set(self.assume_provided)
331 if unmapped_deps:
332 if mapped_deps:
333 lines_after.append('')
334 lines_after.append('# WARNING: We were unable to map the following python package/module')
335 lines_after.append('# dependencies to the bitbake packages which include them:')
336 lines_after.extend('# {}'.format(d) for d in sorted(unmapped_deps))
337
338 handled.append('buildsystem')
339
340 def get_pkginfo(self, pkginfo_fn):
341 msg = email.message_from_file(open(pkginfo_fn, 'r'))
342 msginfo = {}
343 for field in msg.keys():
344 values = msg.get_all(field)
345 if len(values) == 1:
346 msginfo[field] = values[0]
347 else:
348 msginfo[field] = values
349 return msginfo
350
351 def parse_setup_py(self, setupscript='./setup.py'):
352 with codecs.open(setupscript) as f:
353 info, imported_modules, non_literals, extensions = gather_setup_info(f)
354
355 def _map(key):
356 key = key.replace('_', '-')
357 key = key[0].upper() + key[1:]
358 if key in self.setup_parse_map:
359 key = self.setup_parse_map[key]
360 return key
361
362 # Naive mapping of setup() arguments to PKG-INFO field names
363 for d in [info, non_literals]:
364 for key, value in d.items():
365 new_key = _map(key)
366 if new_key != key:
367 del d[key]
368 d[new_key] = value
369
370 return info, 'setuptools' in imported_modules, non_literals, extensions
371
372 def get_setup_args_info(self, setupscript='./setup.py'):
373 cmd = ['python', setupscript]
374 info = {}
375 keys = set(self.bbvar_map.keys())
376 keys |= set(self.setuparg_list_fields)
377 keys |= set(self.setuparg_multi_line_values)
378 grouped_keys = itertools.groupby(keys, lambda k: (k in self.setuparg_list_fields, k in self.setuparg_multi_line_values))
379 for index, keys in grouped_keys:
380 if index == (True, False):
381 # Splitlines output for each arg as a list value
382 for key in keys:
383 arg = self.setuparg_map.get(key, key.lower())
384 try:
385 arg_info = self.run_command(cmd + ['--' + arg], cwd=os.path.dirname(setupscript))
386 except (OSError, subprocess.CalledProcessError):
387 pass
388 else:
389 info[key] = [l.rstrip() for l in arg_info.splitlines()]
390 elif index == (False, True):
391 # Entire output for each arg
392 for key in keys:
393 arg = self.setuparg_map.get(key, key.lower())
394 try:
395 arg_info = self.run_command(cmd + ['--' + arg], cwd=os.path.dirname(setupscript))
396 except (OSError, subprocess.CalledProcessError):
397 pass
398 else:
399 info[key] = arg_info
400 else:
401 info.update(self.get_setup_byline(list(keys), setupscript))
402 return info
403
404 def get_setup_byline(self, fields, setupscript='./setup.py'):
405 info = {}
406
407 cmd = ['python', setupscript]
408 cmd.extend('--' + self.setuparg_map.get(f, f.lower()) for f in fields)
409 try:
410 info_lines = self.run_command(cmd, cwd=os.path.dirname(setupscript)).splitlines()
411 except (OSError, subprocess.CalledProcessError):
412 pass
413 else:
414 if len(fields) != len(info_lines):
415 logger.error('Mismatch between setup.py output lines and number of fields')
416 sys.exit(1)
417
418 for lineno, line in enumerate(info_lines):
419 line = line.rstrip()
420 info[fields[lineno]] = line
421 return info
422
423 def apply_info_replacements(self, info):
424 for variable, search, replace in self.replacements:
425 if variable not in info:
426 continue
427
428 def replace_value(search, replace, value):
429 if replace is None:
430 if re.search(search, value):
431 return None
432 else:
433 new_value = re.sub(search, replace, value)
434 if value != new_value:
435 return new_value
436 return value
437
438 value = info[variable]
439 if isinstance(value, basestring):
440 new_value = replace_value(search, replace, value)
441 if new_value is None:
442 del info[variable]
443 elif new_value != value:
444 info[variable] = new_value
445 elif hasattr(value, 'iteritems'):
446 for dkey, dvalue in value.iteritems():
447 new_list = []
448 for pos, a_value in enumerate(dvalue):
449 new_value = replace_value(search, replace, a_value)
450 if new_value is not None and new_value != value:
451 new_list.append(new_value)
452
453 if value != new_list:
454 value[dkey] = new_list
455 else:
456 new_list = []
457 for pos, a_value in enumerate(value):
458 new_value = replace_value(search, replace, a_value)
459 if new_value is not None and new_value != value:
460 new_list.append(new_value)
461
462 if value != new_list:
463 info[variable] = new_list
464
465 def scan_setup_python_deps(self, srctree, setup_info, setup_non_literals):
466 if 'Package-dir' in setup_info:
467 package_dir = setup_info['Package-dir']
468 else:
469 package_dir = {}
470
471 class PackageDir(distutils.command.build_py.build_py):
472 def __init__(self, package_dir):
473 self.package_dir = package_dir
474
475 pd = PackageDir(package_dir)
476 to_scan = []
477 if not any(v in setup_non_literals for v in ['Py-modules', 'Scripts', 'Packages']):
478 if 'Py-modules' in setup_info:
479 for module in setup_info['Py-modules']:
480 try:
481 package, module = module.rsplit('.', 1)
482 except ValueError:
483 package, module = '.', module
484 module_path = os.path.join(pd.get_package_dir(package), module + '.py')
485 to_scan.append(module_path)
486
487 if 'Packages' in setup_info:
488 for package in setup_info['Packages']:
489 to_scan.append(pd.get_package_dir(package))
490
491 if 'Scripts' in setup_info:
492 to_scan.extend(setup_info['Scripts'])
493 else:
494 logger.info("Scanning the entire source tree, as one or more of the following setup keywords are non-literal: py_modules, scripts, packages.")
495
496 if not to_scan:
497 to_scan = ['.']
498
499 logger.info("Scanning paths for packages & dependencies: %s", ', '.join(to_scan))
500
501 provided_packages = self.parse_pkgdata_for_python_packages()
502 scanned_deps = self.scan_python_dependencies([os.path.join(srctree, p) for p in to_scan])
503 mapped_deps, unmapped_deps = set(self.base_pkgdeps), set()
504 for dep in scanned_deps:
505 mapped = provided_packages.get(dep)
506 if mapped:
507 mapped_deps.add(mapped)
508 else:
509 unmapped_deps.add(dep)
510 return mapped_deps, unmapped_deps
511
512 def scan_python_dependencies(self, paths):
513 deps = set()
514 try:
515 dep_output = self.run_command(['pythondeps', '-d'] + paths)
516 except (OSError, subprocess.CalledProcessError):
517 pass
518 else:
519 for line in dep_output.splitlines():
520 line = line.rstrip()
521 dep, filename = line.split('\t', 1)
522 if filename.endswith('/setup.py'):
523 continue
524 deps.add(dep)
525
526 try:
527 provides_output = self.run_command(['pythondeps', '-p'] + paths)
528 except (OSError, subprocess.CalledProcessError):
529 pass
530 else:
531 provides_lines = (l.rstrip() for l in provides_output.splitlines())
532 provides = set(l for l in provides_lines if l and l != 'setup')
533 deps -= provides
534
535 return deps
536
537 def parse_pkgdata_for_python_packages(self):
538 suffixes = [t[0] for t in imp.get_suffixes()]
539 pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR', True)
540
541 ldata = tinfoil.config_data.createCopy()
542 bb.parse.handle('classes/python-dir.bbclass', ldata, True)
543 python_sitedir = ldata.getVar('PYTHON_SITEPACKAGES_DIR', True)
544
545 dynload_dir = os.path.join(os.path.dirname(python_sitedir), 'lib-dynload')
546 python_dirs = [python_sitedir + os.sep,
547 os.path.join(os.path.dirname(python_sitedir), 'dist-packages') + os.sep,
548 os.path.dirname(python_sitedir) + os.sep]
549 packages = {}
550 for pkgdatafile in glob.glob('{}/runtime/*'.format(pkgdata_dir)):
551 files_info = None
552 with open(pkgdatafile, 'r') as f:
553 for line in f.readlines():
554 field, value = line.split(': ', 1)
555 if field == 'FILES_INFO':
556 files_info = ast.literal_eval(value)
557 break
558 else:
559 continue
560
561 for fn in files_info.iterkeys():
562 for suffix in suffixes:
563 if fn.endswith(suffix):
564 break
565 else:
566 continue
567
568 if fn.startswith(dynload_dir + os.sep):
569 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:
596 return subprocess.check_output(cmd, **popenargs)
597 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 = {}, []
611 for key, value in visitor.keywords.items():
612 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
643 for k, v in self.keywords.iteritems():
644 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
709 elif isinstance(value, basestring):
710 return False
711 elif hasattr(value, 'itervalues'):
712 return any(has_non_literals(v) for v in value.itervalues())
713 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))