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 |
Andrew Geissler | 595f630 | 2022-01-24 19:11:47 +0000 | [diff] [blame^] | 11 | import setuptools.command.build_py |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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', |
Andrew Geissler | 5199d83 | 2021-09-24 16:47:35 -0500 | [diff] [blame] | 104 | 'License :: OSI Approved :: BSD License': 'BSD-3-Clause', |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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 | |
Andrew Geissler | 595f630 | 2022-01-24 19:11:47 +0000 | [diff] [blame^] | 462 | dist = setuptools.Distribution() |
| 463 | |
| 464 | class PackageDir(setuptools.command.build_py.build_py): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 465 | def __init__(self, package_dir): |
| 466 | self.package_dir = package_dir |
Andrew Geissler | 595f630 | 2022-01-24 19:11:47 +0000 | [diff] [blame^] | 467 | self.dist = dist |
| 468 | super().__init__(self.dist) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 469 | |
| 470 | pd = PackageDir(package_dir) |
| 471 | to_scan = [] |
| 472 | if not any(v in setup_non_literals for v in ['Py-modules', 'Scripts', 'Packages']): |
| 473 | if 'Py-modules' in setup_info: |
| 474 | for module in setup_info['Py-modules']: |
| 475 | try: |
| 476 | package, module = module.rsplit('.', 1) |
| 477 | except ValueError: |
| 478 | package, module = '.', module |
| 479 | module_path = os.path.join(pd.get_package_dir(package), module + '.py') |
| 480 | to_scan.append(module_path) |
| 481 | |
| 482 | if 'Packages' in setup_info: |
| 483 | for package in setup_info['Packages']: |
| 484 | to_scan.append(pd.get_package_dir(package)) |
| 485 | |
| 486 | if 'Scripts' in setup_info: |
| 487 | to_scan.extend(setup_info['Scripts']) |
| 488 | else: |
| 489 | logger.info("Scanning the entire source tree, as one or more of the following setup keywords are non-literal: py_modules, scripts, packages.") |
| 490 | |
| 491 | if not to_scan: |
| 492 | to_scan = ['.'] |
| 493 | |
| 494 | logger.info("Scanning paths for packages & dependencies: %s", ', '.join(to_scan)) |
| 495 | |
| 496 | provided_packages = self.parse_pkgdata_for_python_packages() |
| 497 | scanned_deps = self.scan_python_dependencies([os.path.join(srctree, p) for p in to_scan]) |
| 498 | mapped_deps, unmapped_deps = set(self.base_pkgdeps), set() |
| 499 | for dep in scanned_deps: |
| 500 | mapped = provided_packages.get(dep) |
| 501 | if mapped: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 502 | logger.debug('Mapped %s to %s' % (dep, mapped)) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 503 | mapped_deps.add(mapped) |
| 504 | else: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 505 | logger.debug('Could not map %s' % dep) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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: |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 516 | for line in dep_output.splitlines(): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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()] |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 536 | pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 537 | |
| 538 | ldata = tinfoil.config_data.createCopy() |
Brad Bishop | 15ae250 | 2019-06-18 21:44:24 -0400 | [diff] [blame] | 539 | bb.parse.handle('classes/python3-dir.bbclass', ldata, True) |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 540 | python_sitedir = ldata.getVar('PYTHON_SITEPACKAGES_DIR') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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) |
Andrew Geissler | d159c7f | 2021-09-02 21:05:58 -0500 | [diff] [blame] | 552 | if field.startswith('FILES_INFO'): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 553 | files_info = ast.literal_eval(value) |
| 554 | break |
| 555 | else: |
| 556 | continue |
| 557 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 558 | for fn in files_info: |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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): |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 566 | if '/.debug/' in fn: |
| 567 | continue |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 568 | base = os.path.basename(fn) |
| 569 | provided = base.split('.', 1)[0] |
| 570 | packages[provided] = os.path.basename(pkgdatafile) |
| 571 | continue |
| 572 | |
| 573 | for python_dir in python_dirs: |
| 574 | if fn.startswith(python_dir): |
| 575 | relpath = fn[len(python_dir):] |
| 576 | relstart, _, relremaining = relpath.partition(os.sep) |
| 577 | if relstart.endswith('.egg'): |
| 578 | relpath = relremaining |
| 579 | base, _ = os.path.splitext(relpath) |
| 580 | |
| 581 | if '/.debug/' in base: |
| 582 | continue |
| 583 | if os.path.basename(base) == '__init__': |
| 584 | base = os.path.dirname(base) |
| 585 | base = base.replace(os.sep + os.sep, os.sep) |
| 586 | provided = base.replace(os.sep, '.') |
| 587 | packages[provided] = os.path.basename(pkgdatafile) |
| 588 | return packages |
| 589 | |
| 590 | @classmethod |
| 591 | def run_command(cls, cmd, **popenargs): |
| 592 | if 'stderr' not in popenargs: |
| 593 | popenargs['stderr'] = subprocess.STDOUT |
| 594 | try: |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 595 | return subprocess.check_output(cmd, **popenargs).decode('utf-8') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 596 | except OSError as exc: |
| 597 | logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc) |
| 598 | raise |
| 599 | except subprocess.CalledProcessError as exc: |
| 600 | logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc.output) |
| 601 | raise |
| 602 | |
| 603 | |
| 604 | def gather_setup_info(fileobj): |
| 605 | parsed = ast.parse(fileobj.read(), fileobj.name) |
| 606 | visitor = SetupScriptVisitor() |
| 607 | visitor.visit(parsed) |
| 608 | |
| 609 | non_literals, extensions = {}, [] |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 610 | for key, value in list(visitor.keywords.items()): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 611 | if key == 'ext_modules': |
| 612 | if isinstance(value, list): |
| 613 | for ext in value: |
| 614 | if (isinstance(ext, ast.Call) and |
| 615 | isinstance(ext.func, ast.Name) and |
| 616 | ext.func.id == 'Extension' and |
| 617 | not has_non_literals(ext.args)): |
| 618 | extensions.append(ext.args[0]) |
| 619 | elif has_non_literals(value): |
| 620 | non_literals[key] = value |
| 621 | del visitor.keywords[key] |
| 622 | |
| 623 | return visitor.keywords, visitor.imported_modules, non_literals, extensions |
| 624 | |
| 625 | |
| 626 | class SetupScriptVisitor(ast.NodeVisitor): |
| 627 | def __init__(self): |
| 628 | ast.NodeVisitor.__init__(self) |
| 629 | self.keywords = {} |
| 630 | self.non_literals = [] |
| 631 | self.imported_modules = set() |
| 632 | |
| 633 | def visit_Expr(self, node): |
| 634 | if isinstance(node.value, ast.Call) and \ |
| 635 | isinstance(node.value.func, ast.Name) and \ |
| 636 | node.value.func.id == 'setup': |
| 637 | self.visit_setup(node.value) |
| 638 | |
| 639 | def visit_setup(self, node): |
| 640 | call = LiteralAstTransform().visit(node) |
| 641 | self.keywords = call.keywords |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 642 | for k, v in self.keywords.items(): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 643 | if has_non_literals(v): |
| 644 | self.non_literals.append(k) |
| 645 | |
| 646 | def visit_Import(self, node): |
| 647 | for alias in node.names: |
| 648 | self.imported_modules.add(alias.name) |
| 649 | |
| 650 | def visit_ImportFrom(self, node): |
| 651 | self.imported_modules.add(node.module) |
| 652 | |
| 653 | |
| 654 | class LiteralAstTransform(ast.NodeTransformer): |
| 655 | """Simplify the ast through evaluation of literals.""" |
| 656 | excluded_fields = ['ctx'] |
| 657 | |
| 658 | def visit(self, node): |
| 659 | if not isinstance(node, ast.AST): |
| 660 | return node |
| 661 | else: |
| 662 | return ast.NodeTransformer.visit(self, node) |
| 663 | |
| 664 | def generic_visit(self, node): |
| 665 | try: |
| 666 | return ast.literal_eval(node) |
| 667 | except ValueError: |
| 668 | for field, value in ast.iter_fields(node): |
| 669 | if field in self.excluded_fields: |
| 670 | delattr(node, field) |
| 671 | if value is None: |
| 672 | continue |
| 673 | |
| 674 | if isinstance(value, list): |
| 675 | if field in ('keywords', 'kwargs'): |
| 676 | new_value = dict((kw.arg, self.visit(kw.value)) for kw in value) |
| 677 | else: |
| 678 | new_value = [self.visit(i) for i in value] |
| 679 | else: |
| 680 | new_value = self.visit(value) |
| 681 | setattr(node, field, new_value) |
| 682 | return node |
| 683 | |
| 684 | def visit_Name(self, node): |
| 685 | if hasattr('__builtins__', node.id): |
| 686 | return getattr(__builtins__, node.id) |
| 687 | else: |
| 688 | return self.generic_visit(node) |
| 689 | |
| 690 | def visit_Tuple(self, node): |
| 691 | return tuple(self.visit(v) for v in node.elts) |
| 692 | |
| 693 | def visit_List(self, node): |
| 694 | return [self.visit(v) for v in node.elts] |
| 695 | |
| 696 | def visit_Set(self, node): |
| 697 | return set(self.visit(v) for v in node.elts) |
| 698 | |
| 699 | def visit_Dict(self, node): |
| 700 | keys = (self.visit(k) for k in node.keys) |
| 701 | values = (self.visit(v) for v in node.values) |
| 702 | return dict(zip(keys, values)) |
| 703 | |
| 704 | |
| 705 | def has_non_literals(value): |
| 706 | if isinstance(value, ast.AST): |
| 707 | return True |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 708 | elif isinstance(value, str): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 709 | return False |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 710 | elif hasattr(value, 'values'): |
| 711 | return any(has_non_literals(v) for v in value.values()) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 712 | elif hasattr(value, '__iter__'): |
| 713 | return any(has_non_literals(v) for v in value) |
| 714 | |
| 715 | |
| 716 | def register_recipe_handlers(handlers): |
| 717 | # 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] | 718 | handlers.append((PythonRecipeHandler(), 70)) |