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