Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 1 | # 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 | |
| 18 | import ast |
| 19 | import codecs |
| 20 | import collections |
| 21 | import distutils.command.build_py |
| 22 | import email |
| 23 | import imp |
| 24 | import glob |
| 25 | import itertools |
| 26 | import logging |
| 27 | import os |
| 28 | import re |
| 29 | import sys |
| 30 | import subprocess |
| 31 | from recipetool.create import RecipeHandler |
| 32 | |
| 33 | logger = logging.getLogger('recipetool') |
| 34 | |
| 35 | tinfoil = None |
| 36 | |
| 37 | |
| 38 | def tinfoil_init(instance): |
| 39 | global tinfoil |
| 40 | tinfoil = instance |
| 41 | |
| 42 | |
| 43 | class 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 | |
| 162 | def process(self, srctree, classes, lines_before, lines_after, handled): |
| 163 | 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)) |
| 281 | lines_before[src_uri_line-1:src_uri_line-1] = mdinfo |
| 282 | |
| 283 | mapped_deps, unmapped_deps = self.scan_setup_python_deps(srctree, setup_info, setup_non_literals) |
| 284 | |
| 285 | extras_req = set() |
| 286 | if 'Extras-require' in info: |
| 287 | extras_req = info['Extras-require'] |
| 288 | if extras_req: |
| 289 | lines_after.append('# The following configs & dependencies are from setuptools extras_require.') |
| 290 | lines_after.append('# These dependencies are optional, hence can be controlled via PACKAGECONFIG.') |
| 291 | lines_after.append('# The upstream names may not correspond exactly to bitbake package names.') |
| 292 | lines_after.append('#') |
| 293 | lines_after.append('# Uncomment this line to enable all the optional features.') |
| 294 | lines_after.append('#PACKAGECONFIG ?= "{}"'.format(' '.join(k.lower() for k in extras_req.iterkeys()))) |
| 295 | for feature, feature_reqs in extras_req.iteritems(): |
| 296 | unmapped_deps.difference_update(feature_reqs) |
| 297 | |
| 298 | feature_req_deps = ('python-' + r.replace('.', '-').lower() for r in sorted(feature_reqs)) |
| 299 | lines_after.append('PACKAGECONFIG[{}] = ",,,{}"'.format(feature.lower(), ' '.join(feature_req_deps))) |
| 300 | |
| 301 | inst_reqs = set() |
| 302 | if 'Install-requires' in info: |
| 303 | if extras_req: |
| 304 | lines_after.append('') |
| 305 | inst_reqs = info['Install-requires'] |
| 306 | if inst_reqs: |
| 307 | unmapped_deps.difference_update(inst_reqs) |
| 308 | |
| 309 | inst_req_deps = ('python-' + r.replace('.', '-').lower() for r in sorted(inst_reqs)) |
| 310 | lines_after.append('# WARNING: the following rdepends are from setuptools install_requires. These') |
| 311 | lines_after.append('# upstream names may not correspond exactly to bitbake package names.') |
| 312 | lines_after.append('RDEPENDS_${{PN}} += "{}"'.format(' '.join(inst_req_deps))) |
| 313 | |
| 314 | if mapped_deps: |
| 315 | name = info.get('Name') |
| 316 | if name and name[0] in mapped_deps: |
| 317 | # Attempt to avoid self-reference |
| 318 | mapped_deps.remove(name[0]) |
| 319 | mapped_deps -= set(self.excluded_pkgdeps) |
| 320 | if inst_reqs or extras_req: |
| 321 | lines_after.append('') |
| 322 | lines_after.append('# WARNING: the following rdepends are determined through basic analysis of the') |
| 323 | lines_after.append('# python sources, and might not be 100% accurate.') |
| 324 | lines_after.append('RDEPENDS_${{PN}} += "{}"'.format(' '.join(sorted(mapped_deps)))) |
| 325 | |
| 326 | unmapped_deps -= set(extensions) |
| 327 | unmapped_deps -= set(self.assume_provided) |
| 328 | if unmapped_deps: |
| 329 | if mapped_deps: |
| 330 | lines_after.append('') |
| 331 | lines_after.append('# WARNING: We were unable to map the following python package/module') |
| 332 | lines_after.append('# dependencies to the bitbake packages which include them:') |
| 333 | lines_after.extend('# {}'.format(d) for d in sorted(unmapped_deps)) |
| 334 | |
| 335 | handled.append('buildsystem') |
| 336 | |
| 337 | def get_pkginfo(self, pkginfo_fn): |
| 338 | msg = email.message_from_file(open(pkginfo_fn, 'r')) |
| 339 | msginfo = {} |
| 340 | for field in msg.keys(): |
| 341 | values = msg.get_all(field) |
| 342 | if len(values) == 1: |
| 343 | msginfo[field] = values[0] |
| 344 | else: |
| 345 | msginfo[field] = values |
| 346 | return msginfo |
| 347 | |
| 348 | def parse_setup_py(self, setupscript='./setup.py'): |
| 349 | with codecs.open(setupscript) as f: |
| 350 | info, imported_modules, non_literals, extensions = gather_setup_info(f) |
| 351 | |
| 352 | def _map(key): |
| 353 | key = key.replace('_', '-') |
| 354 | key = key[0].upper() + key[1:] |
| 355 | if key in self.setup_parse_map: |
| 356 | key = self.setup_parse_map[key] |
| 357 | return key |
| 358 | |
| 359 | # Naive mapping of setup() arguments to PKG-INFO field names |
| 360 | for d in [info, non_literals]: |
| 361 | for key, value in d.items(): |
| 362 | new_key = _map(key) |
| 363 | if new_key != key: |
| 364 | del d[key] |
| 365 | d[new_key] = value |
| 366 | |
| 367 | return info, 'setuptools' in imported_modules, non_literals, extensions |
| 368 | |
| 369 | def get_setup_args_info(self, setupscript='./setup.py'): |
| 370 | cmd = ['python', setupscript] |
| 371 | info = {} |
| 372 | keys = set(self.bbvar_map.keys()) |
| 373 | keys |= set(self.setuparg_list_fields) |
| 374 | keys |= set(self.setuparg_multi_line_values) |
| 375 | grouped_keys = itertools.groupby(keys, lambda k: (k in self.setuparg_list_fields, k in self.setuparg_multi_line_values)) |
| 376 | for index, keys in grouped_keys: |
| 377 | if index == (True, False): |
| 378 | # Splitlines output for each arg as a list value |
| 379 | for key in keys: |
| 380 | arg = self.setuparg_map.get(key, key.lower()) |
| 381 | try: |
| 382 | arg_info = self.run_command(cmd + ['--' + arg], cwd=os.path.dirname(setupscript)) |
| 383 | except (OSError, subprocess.CalledProcessError): |
| 384 | pass |
| 385 | else: |
| 386 | info[key] = [l.rstrip() for l in arg_info.splitlines()] |
| 387 | elif index == (False, True): |
| 388 | # Entire output for each arg |
| 389 | for key in keys: |
| 390 | arg = self.setuparg_map.get(key, key.lower()) |
| 391 | try: |
| 392 | arg_info = self.run_command(cmd + ['--' + arg], cwd=os.path.dirname(setupscript)) |
| 393 | except (OSError, subprocess.CalledProcessError): |
| 394 | pass |
| 395 | else: |
| 396 | info[key] = arg_info |
| 397 | else: |
| 398 | info.update(self.get_setup_byline(list(keys), setupscript)) |
| 399 | return info |
| 400 | |
| 401 | def get_setup_byline(self, fields, setupscript='./setup.py'): |
| 402 | info = {} |
| 403 | |
| 404 | cmd = ['python', setupscript] |
| 405 | cmd.extend('--' + self.setuparg_map.get(f, f.lower()) for f in fields) |
| 406 | try: |
| 407 | info_lines = self.run_command(cmd, cwd=os.path.dirname(setupscript)).splitlines() |
| 408 | except (OSError, subprocess.CalledProcessError): |
| 409 | pass |
| 410 | else: |
| 411 | if len(fields) != len(info_lines): |
| 412 | logger.error('Mismatch between setup.py output lines and number of fields') |
| 413 | sys.exit(1) |
| 414 | |
| 415 | for lineno, line in enumerate(info_lines): |
| 416 | line = line.rstrip() |
| 417 | info[fields[lineno]] = line |
| 418 | return info |
| 419 | |
| 420 | def apply_info_replacements(self, info): |
| 421 | for variable, search, replace in self.replacements: |
| 422 | if variable not in info: |
| 423 | continue |
| 424 | |
| 425 | def replace_value(search, replace, value): |
| 426 | if replace is None: |
| 427 | if re.search(search, value): |
| 428 | return None |
| 429 | else: |
| 430 | new_value = re.sub(search, replace, value) |
| 431 | if value != new_value: |
| 432 | return new_value |
| 433 | return value |
| 434 | |
| 435 | value = info[variable] |
| 436 | if isinstance(value, basestring): |
| 437 | new_value = replace_value(search, replace, value) |
| 438 | if new_value is None: |
| 439 | del info[variable] |
| 440 | elif new_value != value: |
| 441 | info[variable] = new_value |
| 442 | elif hasattr(value, 'iteritems'): |
| 443 | for dkey, dvalue in value.iteritems(): |
| 444 | new_list = [] |
| 445 | for pos, a_value in enumerate(dvalue): |
| 446 | new_value = replace_value(search, replace, a_value) |
| 447 | if new_value is not None and new_value != value: |
| 448 | new_list.append(new_value) |
| 449 | |
| 450 | if value != new_list: |
| 451 | value[dkey] = new_list |
| 452 | else: |
| 453 | new_list = [] |
| 454 | for pos, a_value in enumerate(value): |
| 455 | new_value = replace_value(search, replace, a_value) |
| 456 | if new_value is not None and new_value != value: |
| 457 | new_list.append(new_value) |
| 458 | |
| 459 | if value != new_list: |
| 460 | info[variable] = new_list |
| 461 | |
| 462 | def scan_setup_python_deps(self, srctree, setup_info, setup_non_literals): |
| 463 | if 'Package-dir' in setup_info: |
| 464 | package_dir = setup_info['Package-dir'] |
| 465 | else: |
| 466 | package_dir = {} |
| 467 | |
| 468 | class PackageDir(distutils.command.build_py.build_py): |
| 469 | def __init__(self, package_dir): |
| 470 | self.package_dir = package_dir |
| 471 | |
| 472 | pd = PackageDir(package_dir) |
| 473 | to_scan = [] |
| 474 | if not any(v in setup_non_literals for v in ['Py-modules', 'Scripts', 'Packages']): |
| 475 | if 'Py-modules' in setup_info: |
| 476 | for module in setup_info['Py-modules']: |
| 477 | try: |
| 478 | package, module = module.rsplit('.', 1) |
| 479 | except ValueError: |
| 480 | package, module = '.', module |
| 481 | module_path = os.path.join(pd.get_package_dir(package), module + '.py') |
| 482 | to_scan.append(module_path) |
| 483 | |
| 484 | if 'Packages' in setup_info: |
| 485 | for package in setup_info['Packages']: |
| 486 | to_scan.append(pd.get_package_dir(package)) |
| 487 | |
| 488 | if 'Scripts' in setup_info: |
| 489 | to_scan.extend(setup_info['Scripts']) |
| 490 | else: |
| 491 | logger.info("Scanning the entire source tree, as one or more of the following setup keywords are non-literal: py_modules, scripts, packages.") |
| 492 | |
| 493 | if not to_scan: |
| 494 | to_scan = ['.'] |
| 495 | |
| 496 | logger.info("Scanning paths for packages & dependencies: %s", ', '.join(to_scan)) |
| 497 | |
| 498 | provided_packages = self.parse_pkgdata_for_python_packages() |
| 499 | scanned_deps = self.scan_python_dependencies([os.path.join(srctree, p) for p in to_scan]) |
| 500 | mapped_deps, unmapped_deps = set(self.base_pkgdeps), set() |
| 501 | for dep in scanned_deps: |
| 502 | mapped = provided_packages.get(dep) |
| 503 | if mapped: |
| 504 | mapped_deps.add(mapped) |
| 505 | else: |
| 506 | unmapped_deps.add(dep) |
| 507 | return mapped_deps, unmapped_deps |
| 508 | |
| 509 | def scan_python_dependencies(self, paths): |
| 510 | deps = set() |
| 511 | try: |
| 512 | dep_output = self.run_command(['pythondeps', '-d'] + paths) |
| 513 | except (OSError, subprocess.CalledProcessError): |
| 514 | pass |
| 515 | else: |
| 516 | for line in dep_output.splitlines(): |
| 517 | line = line.rstrip() |
| 518 | dep, filename = line.split('\t', 1) |
| 519 | if filename.endswith('/setup.py'): |
| 520 | continue |
| 521 | deps.add(dep) |
| 522 | |
| 523 | try: |
| 524 | provides_output = self.run_command(['pythondeps', '-p'] + paths) |
| 525 | except (OSError, subprocess.CalledProcessError): |
| 526 | pass |
| 527 | else: |
| 528 | provides_lines = (l.rstrip() for l in provides_output.splitlines()) |
| 529 | provides = set(l for l in provides_lines if l and l != 'setup') |
| 530 | deps -= provides |
| 531 | |
| 532 | return deps |
| 533 | |
| 534 | def parse_pkgdata_for_python_packages(self): |
| 535 | suffixes = [t[0] for t in imp.get_suffixes()] |
| 536 | pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR', True) |
| 537 | |
| 538 | ldata = tinfoil.config_data.createCopy() |
| 539 | bb.parse.handle('classes/python-dir.bbclass', ldata, True) |
| 540 | python_sitedir = ldata.getVar('PYTHON_SITEPACKAGES_DIR', True) |
| 541 | |
| 542 | dynload_dir = os.path.join(os.path.dirname(python_sitedir), 'lib-dynload') |
| 543 | python_dirs = [python_sitedir + os.sep, |
| 544 | os.path.join(os.path.dirname(python_sitedir), 'dist-packages') + os.sep, |
| 545 | os.path.dirname(python_sitedir) + os.sep] |
| 546 | packages = {} |
| 547 | for pkgdatafile in glob.glob('{}/runtime/*'.format(pkgdata_dir)): |
| 548 | files_info = None |
| 549 | with open(pkgdatafile, 'r') as f: |
| 550 | for line in f.readlines(): |
| 551 | field, value = line.split(': ', 1) |
| 552 | if field == 'FILES_INFO': |
| 553 | files_info = ast.literal_eval(value) |
| 554 | break |
| 555 | else: |
| 556 | continue |
| 557 | |
| 558 | for fn in files_info.iterkeys(): |
| 559 | for suffix in suffixes: |
| 560 | if fn.endswith(suffix): |
| 561 | break |
| 562 | else: |
| 563 | continue |
| 564 | |
| 565 | if fn.startswith(dynload_dir + os.sep): |
| 566 | base = os.path.basename(fn) |
| 567 | provided = base.split('.', 1)[0] |
| 568 | packages[provided] = os.path.basename(pkgdatafile) |
| 569 | continue |
| 570 | |
| 571 | for python_dir in python_dirs: |
| 572 | if fn.startswith(python_dir): |
| 573 | relpath = fn[len(python_dir):] |
| 574 | relstart, _, relremaining = relpath.partition(os.sep) |
| 575 | if relstart.endswith('.egg'): |
| 576 | relpath = relremaining |
| 577 | base, _ = os.path.splitext(relpath) |
| 578 | |
| 579 | if '/.debug/' in base: |
| 580 | continue |
| 581 | if os.path.basename(base) == '__init__': |
| 582 | base = os.path.dirname(base) |
| 583 | base = base.replace(os.sep + os.sep, os.sep) |
| 584 | provided = base.replace(os.sep, '.') |
| 585 | packages[provided] = os.path.basename(pkgdatafile) |
| 586 | return packages |
| 587 | |
| 588 | @classmethod |
| 589 | def run_command(cls, cmd, **popenargs): |
| 590 | if 'stderr' not in popenargs: |
| 591 | popenargs['stderr'] = subprocess.STDOUT |
| 592 | try: |
| 593 | return subprocess.check_output(cmd, **popenargs) |
| 594 | except OSError as exc: |
| 595 | logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc) |
| 596 | raise |
| 597 | except subprocess.CalledProcessError as exc: |
| 598 | logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc.output) |
| 599 | raise |
| 600 | |
| 601 | |
| 602 | def gather_setup_info(fileobj): |
| 603 | parsed = ast.parse(fileobj.read(), fileobj.name) |
| 604 | visitor = SetupScriptVisitor() |
| 605 | visitor.visit(parsed) |
| 606 | |
| 607 | non_literals, extensions = {}, [] |
| 608 | for key, value in visitor.keywords.items(): |
| 609 | if key == 'ext_modules': |
| 610 | if isinstance(value, list): |
| 611 | for ext in value: |
| 612 | if (isinstance(ext, ast.Call) and |
| 613 | isinstance(ext.func, ast.Name) and |
| 614 | ext.func.id == 'Extension' and |
| 615 | not has_non_literals(ext.args)): |
| 616 | extensions.append(ext.args[0]) |
| 617 | elif has_non_literals(value): |
| 618 | non_literals[key] = value |
| 619 | del visitor.keywords[key] |
| 620 | |
| 621 | return visitor.keywords, visitor.imported_modules, non_literals, extensions |
| 622 | |
| 623 | |
| 624 | class SetupScriptVisitor(ast.NodeVisitor): |
| 625 | def __init__(self): |
| 626 | ast.NodeVisitor.__init__(self) |
| 627 | self.keywords = {} |
| 628 | self.non_literals = [] |
| 629 | self.imported_modules = set() |
| 630 | |
| 631 | def visit_Expr(self, node): |
| 632 | if isinstance(node.value, ast.Call) and \ |
| 633 | isinstance(node.value.func, ast.Name) and \ |
| 634 | node.value.func.id == 'setup': |
| 635 | self.visit_setup(node.value) |
| 636 | |
| 637 | def visit_setup(self, node): |
| 638 | call = LiteralAstTransform().visit(node) |
| 639 | self.keywords = call.keywords |
| 640 | for k, v in self.keywords.iteritems(): |
| 641 | if has_non_literals(v): |
| 642 | self.non_literals.append(k) |
| 643 | |
| 644 | def visit_Import(self, node): |
| 645 | for alias in node.names: |
| 646 | self.imported_modules.add(alias.name) |
| 647 | |
| 648 | def visit_ImportFrom(self, node): |
| 649 | self.imported_modules.add(node.module) |
| 650 | |
| 651 | |
| 652 | class LiteralAstTransform(ast.NodeTransformer): |
| 653 | """Simplify the ast through evaluation of literals.""" |
| 654 | excluded_fields = ['ctx'] |
| 655 | |
| 656 | def visit(self, node): |
| 657 | if not isinstance(node, ast.AST): |
| 658 | return node |
| 659 | else: |
| 660 | return ast.NodeTransformer.visit(self, node) |
| 661 | |
| 662 | def generic_visit(self, node): |
| 663 | try: |
| 664 | return ast.literal_eval(node) |
| 665 | except ValueError: |
| 666 | for field, value in ast.iter_fields(node): |
| 667 | if field in self.excluded_fields: |
| 668 | delattr(node, field) |
| 669 | if value is None: |
| 670 | continue |
| 671 | |
| 672 | if isinstance(value, list): |
| 673 | if field in ('keywords', 'kwargs'): |
| 674 | new_value = dict((kw.arg, self.visit(kw.value)) for kw in value) |
| 675 | else: |
| 676 | new_value = [self.visit(i) for i in value] |
| 677 | else: |
| 678 | new_value = self.visit(value) |
| 679 | setattr(node, field, new_value) |
| 680 | return node |
| 681 | |
| 682 | def visit_Name(self, node): |
| 683 | if hasattr('__builtins__', node.id): |
| 684 | return getattr(__builtins__, node.id) |
| 685 | else: |
| 686 | return self.generic_visit(node) |
| 687 | |
| 688 | def visit_Tuple(self, node): |
| 689 | return tuple(self.visit(v) for v in node.elts) |
| 690 | |
| 691 | def visit_List(self, node): |
| 692 | return [self.visit(v) for v in node.elts] |
| 693 | |
| 694 | def visit_Set(self, node): |
| 695 | return set(self.visit(v) for v in node.elts) |
| 696 | |
| 697 | def visit_Dict(self, node): |
| 698 | keys = (self.visit(k) for k in node.keys) |
| 699 | values = (self.visit(v) for v in node.values) |
| 700 | return dict(zip(keys, values)) |
| 701 | |
| 702 | |
| 703 | def has_non_literals(value): |
| 704 | if isinstance(value, ast.AST): |
| 705 | return True |
| 706 | elif isinstance(value, basestring): |
| 707 | return False |
| 708 | elif hasattr(value, 'itervalues'): |
| 709 | return any(has_non_literals(v) for v in value.itervalues()) |
| 710 | elif hasattr(value, '__iter__'): |
| 711 | return any(has_non_literals(v) for v in value) |
| 712 | |
| 713 | |
| 714 | def register_recipe_handlers(handlers): |
| 715 | # We need to make sure this is ahead of the makefile fallback handler |
| 716 | handlers.insert(0, PythonRecipeHandler()) |