blob: f4f51c88b4a61bc62cd81b570718f7ad301b13cb [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# Recipe creation tool - create build system handler for python
2#
3# Copyright (C) 2015 Mentor Graphics Corporation
4#
Brad Bishopc342db32019-05-15 21:57:59 -04005# SPDX-License-Identifier: GPL-2.0-only
Patrick Williamsc124f4f2015-09-15 14:41:29 -05006#
Patrick Williamsc124f4f2015-09-15 14:41:29 -05007
8import ast
9import codecs
10import collections
Andrew Geissler595f6302022-01-24 19:11:47 +000011import setuptools.command.build_py
Patrick Williamsc124f4f2015-09-15 14:41:29 -050012import email
13import imp
14import glob
15import itertools
16import logging
17import os
18import re
19import sys
20import subprocess
21from recipetool.create import RecipeHandler
22
23logger = logging.getLogger('recipetool')
24
25tinfoil = None
26
27
28def tinfoil_init(instance):
29 global tinfoil
30 tinfoil = instance
31
32
33class PythonRecipeHandler(RecipeHandler):
Brad Bishop15ae2502019-06-18 21:44:24 -040034 base_pkgdeps = ['python3-core']
35 excluded_pkgdeps = ['python3-dbg']
36 # os.path is provided by python3-core
Patrick Williamsc124f4f2015-09-15 14:41:29 -050037 assume_provided = ['builtins', 'os.path']
Brad Bishop15ae2502019-06-18 21:44:24 -040038 # Assumes that the host python3 builtin_module_names is sane for target too
Patrick Williamsc124f4f2015-09-15 14:41:29 -050039 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 Williams213cb262021-08-07 19:21:33 -050048 'Requires': 'RDEPENDS:${PN}',
49 'Provides': 'RPROVIDES:${PN}',
50 'Obsoletes': 'RREPLACES:${PN}',
Patrick Williamsc124f4f2015-09-15 14:41:29 -050051 }
52 # PN/PV are already set by recipetool core & desc can be extremely long
53 excluded_fields = [
Patrick Williamsc124f4f2015-09-15 14:41:29 -050054 '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 Williamsc0f7c042017-02-23 20:41:17 -060079 ('License', r' +$', ''),
80 ('License', r'^ +', ''),
Patrick Williamsc124f4f2015-09-15 14:41:29 -050081 ('License', r' ', '-'),
Patrick Williamsc0f7c042017-02-23 20:41:17 -060082 ('License', r'^GNU-', ''),
83 ('License', r'-[Ll]icen[cs]e(,?-[Vv]ersion)?', ''),
Patrick Williamsc124f4f2015-09-15 14:41:29 -050084 ('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 Geissler5199d832021-09-24 16:47:35 -0500104 'License :: OSI Approved :: BSD License': 'BSD-3-Clause',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000105 'License :: OSI Approved :: Boost Software License 1.0 (BSL-1.0)': 'BSL-1.0',
106 'License :: OSI Approved :: CEA CNRS Inria Logiciel Libre License, version 2.1 (CeCILL-2.1)': 'CECILL-2.1',
107 'License :: OSI Approved :: Common Development and Distribution License 1.0 (CDDL-1.0)': 'CDDL-1.0',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500108 'License :: OSI Approved :: Common Public License': 'CPL',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000109 'License :: OSI Approved :: Eclipse Public License 1.0 (EPL-1.0)': 'EPL-1.0',
110 'License :: OSI Approved :: Eclipse Public License 2.0 (EPL-2.0)': 'EPL-2.0',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500111 'License :: OSI Approved :: Eiffel Forum License': 'EFL',
112 'License :: OSI Approved :: European Union Public Licence 1.0 (EUPL 1.0)': 'EUPL-1.0',
113 'License :: OSI Approved :: European Union Public Licence 1.1 (EUPL 1.1)': 'EUPL-1.1',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000114 'License :: OSI Approved :: European Union Public Licence 1.2 (EUPL 1.2)': 'EUPL-1.2',
115 'License :: OSI Approved :: GNU Affero General Public License v3': 'AGPL-3.0-only',
116 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)': 'AGPL-3.0-or-later',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500117 'License :: OSI Approved :: GNU Free Documentation License (FDL)': 'GFDL',
118 'License :: OSI Approved :: GNU General Public License (GPL)': 'GPL',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000119 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)': 'GPL-2.0-only',
120 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)': 'GPL-2.0-or-later',
121 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)': 'GPL-3.0-only',
122 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)': 'GPL-3.0-or-later',
123 'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)': 'LGPL-2.0-only',
124 'License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)': 'LGPL-2.0-or-later',
125 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)': 'LGPL-3.0-only',
126 'License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)': 'LGPL-3.0-or-later',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500127 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)': 'LGPL',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000128 'License :: OSI Approved :: Historical Permission Notice and Disclaimer (HPND)': 'HPND',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500129 'License :: OSI Approved :: IBM Public License': 'IPL',
130 'License :: OSI Approved :: ISC License (ISCL)': 'ISC',
131 'License :: OSI Approved :: Intel Open Source License': 'Intel',
132 'License :: OSI Approved :: Jabber Open Source License': 'Jabber',
133 'License :: OSI Approved :: MIT License': 'MIT',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000134 'License :: OSI Approved :: MIT No Attribution License (MIT-0)': 'MIT-0',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500135 'License :: OSI Approved :: MITRE Collaborative Virtual Workspace License (CVW)': 'CVWL',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000136 'License :: OSI Approved :: MirOS License (MirOS)': 'MirOS',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500137 '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',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000144 'License :: OSI Approved :: Open Software License 3.0 (OSL-3.0)': 'OSL-3.0',
145 'License :: OSI Approved :: PostgreSQL License': 'PostgreSQL',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500146 'License :: OSI Approved :: Python License (CNRI Python License)': 'CNRI-Python',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000147 'License :: OSI Approved :: Python Software Foundation License': 'PSF-2.0',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500148 'License :: OSI Approved :: Qt Public License (QPL)': 'QPL',
149 'License :: OSI Approved :: Ricoh Source Code Public License': 'RSCPL',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000150 'License :: OSI Approved :: SIL Open Font License 1.1 (OFL-1.1)': 'OFL-1.1',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500151 'License :: OSI Approved :: Sleepycat License': 'Sleepycat',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000152 'License :: OSI Approved :: Sun Industry Standards Source License (SISSL)': 'SISSL',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500153 'License :: OSI Approved :: Sun Public License': 'SPL',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000154 'License :: OSI Approved :: The Unlicense (Unlicense)': 'Unlicense',
155 'License :: OSI Approved :: Universal Permissive License (UPL)': 'UPL-1.0',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500156 'License :: OSI Approved :: University of Illinois/NCSA Open Source License': 'NCSA',
157 'License :: OSI Approved :: Vovida Software License 1.0': 'VSL-1.0',
158 'License :: OSI Approved :: W3C License': 'W3C',
159 'License :: OSI Approved :: X.Net License': 'Xnet',
160 'License :: OSI Approved :: Zope Public License': 'ZPL',
161 'License :: OSI Approved :: zlib/libpng License': 'Zlib',
Andrew Geissler9aee5002022-03-30 16:27:02 +0000162 'License :: Other/Proprietary License': 'Proprietary',
163 'License :: Public Domain': 'PD',
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500164 }
165
166 def __init__(self):
167 pass
168
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500169 def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500170 if 'buildsystem' in handled:
171 return False
172
Brad Bishop96ff1982019-08-19 13:50:42 -0400173 # Check for non-zero size setup.py files
174 setupfiles = RecipeHandler.checkfiles(srctree, ['setup.py'])
175 for fn in setupfiles:
176 if os.path.getsize(fn):
177 break
178 else:
179 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500180
181 # setup.py is always parsed to get at certain required information, such as
182 # distutils vs setuptools
183 #
184 # If egg info is available, we use it for both its PKG-INFO metadata
185 # and for its requires.txt for install_requires.
186 # If PKG-INFO is available but no egg info is, we use that for metadata in preference to
187 # the parsed setup.py, but use the install_requires info from the
188 # parsed setup.py.
189
190 setupscript = os.path.join(srctree, 'setup.py')
191 try:
192 setup_info, uses_setuptools, setup_non_literals, extensions = self.parse_setup_py(setupscript)
193 except Exception:
194 logger.exception("Failed to parse setup.py")
195 setup_info, uses_setuptools, setup_non_literals, extensions = {}, True, [], []
196
197 egginfo = glob.glob(os.path.join(srctree, '*.egg-info'))
198 if egginfo:
199 info = self.get_pkginfo(os.path.join(egginfo[0], 'PKG-INFO'))
200 requires_txt = os.path.join(egginfo[0], 'requires.txt')
201 if os.path.exists(requires_txt):
202 with codecs.open(requires_txt) as f:
203 inst_req = []
204 extras_req = collections.defaultdict(list)
205 current_feature = None
206 for line in f.readlines():
207 line = line.rstrip()
208 if not line:
209 continue
210
211 if line.startswith('['):
212 current_feature = line[1:-1]
213 elif current_feature:
214 extras_req[current_feature].append(line)
215 else:
216 inst_req.append(line)
217 info['Install-requires'] = inst_req
218 info['Extras-require'] = extras_req
219 elif RecipeHandler.checkfiles(srctree, ['PKG-INFO']):
220 info = self.get_pkginfo(os.path.join(srctree, 'PKG-INFO'))
221
222 if setup_info:
223 if 'Install-requires' in setup_info:
224 info['Install-requires'] = setup_info['Install-requires']
225 if 'Extras-require' in setup_info:
226 info['Extras-require'] = setup_info['Extras-require']
227 else:
228 if setup_info:
229 info = setup_info
230 else:
231 info = self.get_setup_args_info(setupscript)
232
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600233 # Grab the license value before applying replacements
234 license_str = info.get('License', '').strip()
235
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500236 self.apply_info_replacements(info)
237
238 if uses_setuptools:
Brad Bishop15ae2502019-06-18 21:44:24 -0400239 classes.append('setuptools3')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500240 else:
Brad Bishop15ae2502019-06-18 21:44:24 -0400241 classes.append('distutils3')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500242
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600243 if license_str:
244 for i, line in enumerate(lines_before):
245 if line.startswith('LICENSE = '):
246 lines_before.insert(i, '# NOTE: License in setup.py/PKGINFO is: %s' % license_str)
247 break
248
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500249 if 'Classifier' in info:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600250 existing_licenses = info.get('License', '')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500251 licenses = []
252 for classifier in info['Classifier']:
253 if classifier in self.classifier_license_map:
254 license = self.classifier_license_map[classifier]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600255 if license == 'Apache' and 'Apache-2.0' in existing_licenses:
256 license = 'Apache-2.0'
257 elif license == 'GPL':
258 if 'GPL-2.0' in existing_licenses or 'GPLv2' in existing_licenses:
259 license = 'GPL-2.0'
260 elif 'GPL-3.0' in existing_licenses or 'GPLv3' in existing_licenses:
261 license = 'GPL-3.0'
262 elif license == 'LGPL':
263 if 'LGPL-2.1' in existing_licenses or 'LGPLv2.1' in existing_licenses:
264 license = 'LGPL-2.1'
265 elif 'LGPL-2.0' in existing_licenses or 'LGPLv2' in existing_licenses:
266 license = 'LGPL-2.0'
267 elif 'LGPL-3.0' in existing_licenses or 'LGPLv3' in existing_licenses:
268 license = 'LGPL-3.0'
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500269 licenses.append(license)
270
271 if licenses:
272 info['License'] = ' & '.join(licenses)
273
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500274 # Map PKG-INFO & setup.py fields to bitbake variables
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600275 for field, values in info.items():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500276 if field in self.excluded_fields:
277 continue
278
279 if field not in self.bbvar_map:
280 continue
281
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600282 if isinstance(values, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500283 value = values
284 else:
285 value = ' '.join(str(v) for v in values if v)
286
287 bbvar = self.bbvar_map[field]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600288 if bbvar not in extravalues and value:
289 extravalues[bbvar] = value
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500290
291 mapped_deps, unmapped_deps = self.scan_setup_python_deps(srctree, setup_info, setup_non_literals)
292
293 extras_req = set()
294 if 'Extras-require' in info:
295 extras_req = info['Extras-require']
296 if extras_req:
297 lines_after.append('# The following configs & dependencies are from setuptools extras_require.')
298 lines_after.append('# These dependencies are optional, hence can be controlled via PACKAGECONFIG.')
299 lines_after.append('# The upstream names may not correspond exactly to bitbake package names.')
300 lines_after.append('#')
301 lines_after.append('# Uncomment this line to enable all the optional features.')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600302 lines_after.append('#PACKAGECONFIG ?= "{}"'.format(' '.join(k.lower() for k in extras_req)))
303 for feature, feature_reqs in extras_req.items():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500304 unmapped_deps.difference_update(feature_reqs)
305
Brad Bishop15ae2502019-06-18 21:44:24 -0400306 feature_req_deps = ('python3-' + r.replace('.', '-').lower() for r in sorted(feature_reqs))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500307 lines_after.append('PACKAGECONFIG[{}] = ",,,{}"'.format(feature.lower(), ' '.join(feature_req_deps)))
308
309 inst_reqs = set()
310 if 'Install-requires' in info:
311 if extras_req:
312 lines_after.append('')
313 inst_reqs = info['Install-requires']
314 if inst_reqs:
315 unmapped_deps.difference_update(inst_reqs)
316
Brad Bishop15ae2502019-06-18 21:44:24 -0400317 inst_req_deps = ('python3-' + r.replace('.', '-').lower() for r in sorted(inst_reqs))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500318 lines_after.append('# WARNING: the following rdepends are from setuptools install_requires. These')
319 lines_after.append('# upstream names may not correspond exactly to bitbake package names.')
Patrick Williams213cb262021-08-07 19:21:33 -0500320 lines_after.append('RDEPENDS:${{PN}} += "{}"'.format(' '.join(inst_req_deps)))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500321
322 if mapped_deps:
323 name = info.get('Name')
324 if name and name[0] in mapped_deps:
325 # Attempt to avoid self-reference
326 mapped_deps.remove(name[0])
327 mapped_deps -= set(self.excluded_pkgdeps)
328 if inst_reqs or extras_req:
329 lines_after.append('')
330 lines_after.append('# WARNING: the following rdepends are determined through basic analysis of the')
331 lines_after.append('# python sources, and might not be 100% accurate.')
Patrick Williams213cb262021-08-07 19:21:33 -0500332 lines_after.append('RDEPENDS:${{PN}} += "{}"'.format(' '.join(sorted(mapped_deps))))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500333
334 unmapped_deps -= set(extensions)
335 unmapped_deps -= set(self.assume_provided)
336 if unmapped_deps:
337 if mapped_deps:
338 lines_after.append('')
339 lines_after.append('# WARNING: We were unable to map the following python package/module')
340 lines_after.append('# dependencies to the bitbake packages which include them:')
341 lines_after.extend('# {}'.format(d) for d in sorted(unmapped_deps))
342
343 handled.append('buildsystem')
344
345 def get_pkginfo(self, pkginfo_fn):
346 msg = email.message_from_file(open(pkginfo_fn, 'r'))
347 msginfo = {}
348 for field in msg.keys():
349 values = msg.get_all(field)
350 if len(values) == 1:
351 msginfo[field] = values[0]
352 else:
353 msginfo[field] = values
354 return msginfo
355
356 def parse_setup_py(self, setupscript='./setup.py'):
357 with codecs.open(setupscript) as f:
358 info, imported_modules, non_literals, extensions = gather_setup_info(f)
359
360 def _map(key):
361 key = key.replace('_', '-')
362 key = key[0].upper() + key[1:]
363 if key in self.setup_parse_map:
364 key = self.setup_parse_map[key]
365 return key
366
367 # Naive mapping of setup() arguments to PKG-INFO field names
368 for d in [info, non_literals]:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600369 for key, value in list(d.items()):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500370 if key is None:
371 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500372 new_key = _map(key)
373 if new_key != key:
374 del d[key]
375 d[new_key] = value
376
377 return info, 'setuptools' in imported_modules, non_literals, extensions
378
379 def get_setup_args_info(self, setupscript='./setup.py'):
Brad Bishop15ae2502019-06-18 21:44:24 -0400380 cmd = ['python3', setupscript]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500381 info = {}
382 keys = set(self.bbvar_map.keys())
383 keys |= set(self.setuparg_list_fields)
384 keys |= set(self.setuparg_multi_line_values)
385 grouped_keys = itertools.groupby(keys, lambda k: (k in self.setuparg_list_fields, k in self.setuparg_multi_line_values))
386 for index, keys in grouped_keys:
387 if index == (True, False):
388 # Splitlines output for each arg as a list value
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] = [l.rstrip() for l in arg_info.splitlines()]
397 elif index == (False, True):
398 # Entire output for each arg
399 for key in keys:
400 arg = self.setuparg_map.get(key, key.lower())
401 try:
402 arg_info = self.run_command(cmd + ['--' + arg], cwd=os.path.dirname(setupscript))
403 except (OSError, subprocess.CalledProcessError):
404 pass
405 else:
406 info[key] = arg_info
407 else:
408 info.update(self.get_setup_byline(list(keys), setupscript))
409 return info
410
411 def get_setup_byline(self, fields, setupscript='./setup.py'):
412 info = {}
413
Brad Bishop15ae2502019-06-18 21:44:24 -0400414 cmd = ['python3', setupscript]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500415 cmd.extend('--' + self.setuparg_map.get(f, f.lower()) for f in fields)
416 try:
417 info_lines = self.run_command(cmd, cwd=os.path.dirname(setupscript)).splitlines()
418 except (OSError, subprocess.CalledProcessError):
419 pass
420 else:
421 if len(fields) != len(info_lines):
422 logger.error('Mismatch between setup.py output lines and number of fields')
423 sys.exit(1)
424
425 for lineno, line in enumerate(info_lines):
426 line = line.rstrip()
427 info[fields[lineno]] = line
428 return info
429
430 def apply_info_replacements(self, info):
431 for variable, search, replace in self.replacements:
432 if variable not in info:
433 continue
434
435 def replace_value(search, replace, value):
436 if replace is None:
437 if re.search(search, value):
438 return None
439 else:
440 new_value = re.sub(search, replace, value)
441 if value != new_value:
442 return new_value
443 return value
444
445 value = info[variable]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600446 if isinstance(value, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500447 new_value = replace_value(search, replace, value)
448 if new_value is None:
449 del info[variable]
450 elif new_value != value:
451 info[variable] = new_value
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600452 elif hasattr(value, 'items'):
453 for dkey, dvalue in list(value.items()):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500454 new_list = []
455 for pos, a_value in enumerate(dvalue):
456 new_value = replace_value(search, replace, a_value)
457 if new_value is not None and new_value != value:
458 new_list.append(new_value)
459
460 if value != new_list:
461 value[dkey] = new_list
462 else:
463 new_list = []
464 for pos, a_value in enumerate(value):
465 new_value = replace_value(search, replace, a_value)
466 if new_value is not None and new_value != value:
467 new_list.append(new_value)
468
469 if value != new_list:
470 info[variable] = new_list
471
472 def scan_setup_python_deps(self, srctree, setup_info, setup_non_literals):
473 if 'Package-dir' in setup_info:
474 package_dir = setup_info['Package-dir']
475 else:
476 package_dir = {}
477
Andrew Geissler595f6302022-01-24 19:11:47 +0000478 dist = setuptools.Distribution()
479
480 class PackageDir(setuptools.command.build_py.build_py):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500481 def __init__(self, package_dir):
482 self.package_dir = package_dir
Andrew Geissler595f6302022-01-24 19:11:47 +0000483 self.dist = dist
484 super().__init__(self.dist)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500485
486 pd = PackageDir(package_dir)
487 to_scan = []
488 if not any(v in setup_non_literals for v in ['Py-modules', 'Scripts', 'Packages']):
489 if 'Py-modules' in setup_info:
490 for module in setup_info['Py-modules']:
491 try:
492 package, module = module.rsplit('.', 1)
493 except ValueError:
494 package, module = '.', module
495 module_path = os.path.join(pd.get_package_dir(package), module + '.py')
496 to_scan.append(module_path)
497
498 if 'Packages' in setup_info:
499 for package in setup_info['Packages']:
500 to_scan.append(pd.get_package_dir(package))
501
502 if 'Scripts' in setup_info:
503 to_scan.extend(setup_info['Scripts'])
504 else:
505 logger.info("Scanning the entire source tree, as one or more of the following setup keywords are non-literal: py_modules, scripts, packages.")
506
507 if not to_scan:
508 to_scan = ['.']
509
510 logger.info("Scanning paths for packages & dependencies: %s", ', '.join(to_scan))
511
512 provided_packages = self.parse_pkgdata_for_python_packages()
513 scanned_deps = self.scan_python_dependencies([os.path.join(srctree, p) for p in to_scan])
514 mapped_deps, unmapped_deps = set(self.base_pkgdeps), set()
515 for dep in scanned_deps:
516 mapped = provided_packages.get(dep)
517 if mapped:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600518 logger.debug('Mapped %s to %s' % (dep, mapped))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500519 mapped_deps.add(mapped)
520 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600521 logger.debug('Could not map %s' % dep)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500522 unmapped_deps.add(dep)
523 return mapped_deps, unmapped_deps
524
525 def scan_python_dependencies(self, paths):
526 deps = set()
527 try:
528 dep_output = self.run_command(['pythondeps', '-d'] + paths)
529 except (OSError, subprocess.CalledProcessError):
530 pass
531 else:
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500532 for line in dep_output.splitlines():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500533 line = line.rstrip()
534 dep, filename = line.split('\t', 1)
535 if filename.endswith('/setup.py'):
536 continue
537 deps.add(dep)
538
539 try:
540 provides_output = self.run_command(['pythondeps', '-p'] + paths)
541 except (OSError, subprocess.CalledProcessError):
542 pass
543 else:
544 provides_lines = (l.rstrip() for l in provides_output.splitlines())
545 provides = set(l for l in provides_lines if l and l != 'setup')
546 deps -= provides
547
548 return deps
549
550 def parse_pkgdata_for_python_packages(self):
551 suffixes = [t[0] for t in imp.get_suffixes()]
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500552 pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500553
554 ldata = tinfoil.config_data.createCopy()
Brad Bishop15ae2502019-06-18 21:44:24 -0400555 bb.parse.handle('classes/python3-dir.bbclass', ldata, True)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500556 python_sitedir = ldata.getVar('PYTHON_SITEPACKAGES_DIR')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500557
558 dynload_dir = os.path.join(os.path.dirname(python_sitedir), 'lib-dynload')
559 python_dirs = [python_sitedir + os.sep,
560 os.path.join(os.path.dirname(python_sitedir), 'dist-packages') + os.sep,
561 os.path.dirname(python_sitedir) + os.sep]
562 packages = {}
563 for pkgdatafile in glob.glob('{}/runtime/*'.format(pkgdata_dir)):
564 files_info = None
565 with open(pkgdatafile, 'r') as f:
566 for line in f.readlines():
567 field, value = line.split(': ', 1)
Andrew Geisslerd159c7f2021-09-02 21:05:58 -0500568 if field.startswith('FILES_INFO'):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500569 files_info = ast.literal_eval(value)
570 break
571 else:
572 continue
573
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600574 for fn in files_info:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500575 for suffix in suffixes:
576 if fn.endswith(suffix):
577 break
578 else:
579 continue
580
581 if fn.startswith(dynload_dir + os.sep):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600582 if '/.debug/' in fn:
583 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500584 base = os.path.basename(fn)
585 provided = base.split('.', 1)[0]
586 packages[provided] = os.path.basename(pkgdatafile)
587 continue
588
589 for python_dir in python_dirs:
590 if fn.startswith(python_dir):
591 relpath = fn[len(python_dir):]
592 relstart, _, relremaining = relpath.partition(os.sep)
593 if relstart.endswith('.egg'):
594 relpath = relremaining
595 base, _ = os.path.splitext(relpath)
596
597 if '/.debug/' in base:
598 continue
599 if os.path.basename(base) == '__init__':
600 base = os.path.dirname(base)
601 base = base.replace(os.sep + os.sep, os.sep)
602 provided = base.replace(os.sep, '.')
603 packages[provided] = os.path.basename(pkgdatafile)
604 return packages
605
606 @classmethod
607 def run_command(cls, cmd, **popenargs):
608 if 'stderr' not in popenargs:
609 popenargs['stderr'] = subprocess.STDOUT
610 try:
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500611 return subprocess.check_output(cmd, **popenargs).decode('utf-8')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500612 except OSError as exc:
613 logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc)
614 raise
615 except subprocess.CalledProcessError as exc:
616 logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc.output)
617 raise
618
619
620def gather_setup_info(fileobj):
621 parsed = ast.parse(fileobj.read(), fileobj.name)
622 visitor = SetupScriptVisitor()
623 visitor.visit(parsed)
624
625 non_literals, extensions = {}, []
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600626 for key, value in list(visitor.keywords.items()):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500627 if key == 'ext_modules':
628 if isinstance(value, list):
629 for ext in value:
630 if (isinstance(ext, ast.Call) and
631 isinstance(ext.func, ast.Name) and
632 ext.func.id == 'Extension' and
633 not has_non_literals(ext.args)):
634 extensions.append(ext.args[0])
635 elif has_non_literals(value):
636 non_literals[key] = value
637 del visitor.keywords[key]
638
639 return visitor.keywords, visitor.imported_modules, non_literals, extensions
640
641
642class SetupScriptVisitor(ast.NodeVisitor):
643 def __init__(self):
644 ast.NodeVisitor.__init__(self)
645 self.keywords = {}
646 self.non_literals = []
647 self.imported_modules = set()
648
649 def visit_Expr(self, node):
650 if isinstance(node.value, ast.Call) and \
651 isinstance(node.value.func, ast.Name) and \
652 node.value.func.id == 'setup':
653 self.visit_setup(node.value)
654
655 def visit_setup(self, node):
656 call = LiteralAstTransform().visit(node)
657 self.keywords = call.keywords
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600658 for k, v in self.keywords.items():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500659 if has_non_literals(v):
660 self.non_literals.append(k)
661
662 def visit_Import(self, node):
663 for alias in node.names:
664 self.imported_modules.add(alias.name)
665
666 def visit_ImportFrom(self, node):
667 self.imported_modules.add(node.module)
668
669
670class LiteralAstTransform(ast.NodeTransformer):
671 """Simplify the ast through evaluation of literals."""
672 excluded_fields = ['ctx']
673
674 def visit(self, node):
675 if not isinstance(node, ast.AST):
676 return node
677 else:
678 return ast.NodeTransformer.visit(self, node)
679
680 def generic_visit(self, node):
681 try:
682 return ast.literal_eval(node)
683 except ValueError:
684 for field, value in ast.iter_fields(node):
685 if field in self.excluded_fields:
686 delattr(node, field)
687 if value is None:
688 continue
689
690 if isinstance(value, list):
691 if field in ('keywords', 'kwargs'):
692 new_value = dict((kw.arg, self.visit(kw.value)) for kw in value)
693 else:
694 new_value = [self.visit(i) for i in value]
695 else:
696 new_value = self.visit(value)
697 setattr(node, field, new_value)
698 return node
699
700 def visit_Name(self, node):
701 if hasattr('__builtins__', node.id):
702 return getattr(__builtins__, node.id)
703 else:
704 return self.generic_visit(node)
705
706 def visit_Tuple(self, node):
707 return tuple(self.visit(v) for v in node.elts)
708
709 def visit_List(self, node):
710 return [self.visit(v) for v in node.elts]
711
712 def visit_Set(self, node):
713 return set(self.visit(v) for v in node.elts)
714
715 def visit_Dict(self, node):
716 keys = (self.visit(k) for k in node.keys)
717 values = (self.visit(v) for v in node.values)
718 return dict(zip(keys, values))
719
720
721def has_non_literals(value):
722 if isinstance(value, ast.AST):
723 return True
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600724 elif isinstance(value, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500725 return False
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600726 elif hasattr(value, 'values'):
727 return any(has_non_literals(v) for v in value.values())
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500728 elif hasattr(value, '__iter__'):
729 return any(has_non_literals(v) for v in value)
730
731
732def register_recipe_handlers(handlers):
733 # We need to make sure this is ahead of the makefile fallback handler
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500734 handlers.append((PythonRecipeHandler(), 70))