Skip to contentSkip to conversation

recipetool: add python buildsystem support

PATCH Superseded Christopher Larson 2 participants 6 messages Jan 8, 2015 – Jan 14, 2015

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover recipetool: add python buildsystem support

- Handles distutils & setuptools.
- Supports pulling metadata from PKG-INFO, .egg-info, & setup.py (via two different mechanisms).
- Doesn't handle python 3 yet.
- Optional dependencies via extra_requires are not currently handled.
- Implements scanning for dependencies by using the python ast to determine what modules/packages are being imported by the python code in question

See https://gist.github.com/kergoth/6cca6caa4e9b22a21f75 for the projects I used to test this against, and
https://gist.github.com/kergoth/7fea9494e3cf60b382ff which is the result of running recipetool create against every recipe that inherits distutils or setuptools in my build environment.

https://gist.github.com/kergoth/7ad4b5102b2a5fe3a956 has my current TODO for this feature.

Christopher Larson (2):
recipetool: add python buildsystem support
recipetool: add python dependency scanning support

 scripts/lib/recipetool/create_buildsys_python.py | 567 +++++++++++++++++++++++
 scripts/pythondeps                               | 250 ++++++++++
 2 files changed, 817 insertions(+)
 create mode 100644 scripts/lib/recipetool/create_buildsys_python.py
 create mode 100755 scripts/pythondeps
Signature · 1 line
1.8.3.4
#1 lore raw

PATCH 1/2 recipetool: add python buildsystem support

- Handles distutils & setuptools.
- Supports pulling metadata from PKG-INFO, .egg-info, & setup.py (via two different mechanisms).
- Doesn't handle python 3 yet.
- Optional dependencies via extra_requires are not currently handled.

---
 scripts/lib/recipetool/create_buildsys_python.py | 420 +++++++++++++++++++++++
 1 file changed, 420 insertions(+)
 create mode 100644 scripts/lib/recipetool/create_buildsys_python.py
scripts/lib/recipetool/create_buildsys_python.py new file +420 -0
new file mode 100644
index 0000000..3cdcafd
@@ -0,0 +1,420 @@
+# Recipe creation tool - create build system handler for python
+#
+# Copyright (C) 2015 Mentor Graphics Corporation
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+import ast
+import codecs
+import distutils.command.build_py
+import email
+import imp
+import glob
+import itertools
+import logging
+import os
+import re
+import sys
+import subprocess
+from recipetool.create import RecipeHandler
+
+logger = logging.getLogger('recipetool')
+
+tinfoil = None
+
+
+def tinfoil_init(instance):
+    global tinfoil
+    tinfoil = instance
+
+
+class PythonRecipeHandler(RecipeHandler):
+    bbvar_map = {
+        'Name': 'PN',
+        'Version': 'PV',
+        'Home-page': 'HOMEPAGE',
+        'Summary': 'SUMMARY',
+        'Description': 'DESCRIPTION',
+        'License': 'LICENSE',
+        'Requires': 'RDEPENDS_${PN}',
+        'Provides': 'RPROVIDES_${PN}',
+        'Obsoletes': 'RREPLACES_${PN}',
+    }
+    # PN/PV are already set by recipetool core & desc can be extremely long
+    excluded_fields = [
+        'Name',
+        'Version',
+        'Description',
+    ]
+    setup_parse_map = {
+        'Url': 'Home-page',
+        'Classifiers': 'Classifier',
+        'Description': 'Summary',
+    }
+    setuparg_map = {
+        'Home-page': 'url',
+        'Classifier': 'classifiers',
+        'Summary': 'description',
+        'Description': 'long-description',
+    }
+    # Values which are lists, used by the setup.py argument based metadata
+    # extraction method, to determine how to process the setup.py output.
+    setuparg_list_fields = [
+        'Classifier',
+        'Requires',
+        'Provides',
+        'Obsoletes',
+        'Platform',
+        'Supported-Platform',
+    ]
+    setuparg_multi_line_values = ['Description']
+    replacements = [
+        ('License', r' ', '-'),
+        ('License', r'-License$', ''),
+
+        # Remove currently unhandled version numbers from these variables
+        ('Requires', r' *\([^)]*\)', ''),
+        ('Provides', r' *\([^)]*\)', ''),
+        ('Obsoletes', r' *\([^)]*\)', ''),
+        ('Install-requires', r'^([^><= ]+).*', r'\1'),
+        ('Tests-require', r'^([^><= ]+).*', r'\1'),
+    ]
+
+    # Operations to adjust non-list variable values based on the list
+    # contents, e.g. set License based on the license classifiers
+    list_entry_ops = [
+        # Field to search, value to search for, bb var to set, bb value to set
+        ('Classifier', 'License :: OSI Approved :: Academic Free License (AFL)', 'License', 'AFL'),
+        ('Classifier', 'License :: OSI Approved :: Apache Software License', 'License', 'Apache'),
+        ('Classifier', 'License :: OSI Approved :: Apple Public Source License', 'License', 'APSL'),
+        ('Classifier', 'License :: OSI Approved :: Artistic License', 'License', 'Artistic'),
+        ('Classifier', 'License :: OSI Approved :: Attribution Assurance License', 'License', 'AAL'),
+        ('Classifier', 'License :: OSI Approved :: BSD License', 'License', 'BSD'),
+        ('Classifier', 'License :: OSI Approved :: Common Public License', 'License', 'CPL'),
+        ('Classifier', 'License :: OSI Approved :: Eiffel Forum License', 'License', 'EFL'),
+        ('Classifier', 'License :: OSI Approved :: European Union Public Licence 1.0 (EUPL 1.0)', 'License', 'EUPL-1.0'),
+        ('Classifier', 'License :: OSI Approved :: European Union Public Licence 1.1 (EUPL 1.1)', 'License', 'EUPL-1.1'),
+        ('Classifier', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'License', 'AGPL-3.0+'),
+        ('Classifier', 'License :: OSI Approved :: GNU Affero General Public License v3', 'License', 'AGPL-3.0'),
+        ('Classifier', 'License :: OSI Approved :: GNU Free Documentation License (FDL)', 'License', 'GFDL'),
+        ('Classifier', 'License :: OSI Approved :: GNU General Public License (GPL)', 'License', 'GPL-1.0'),
+        ('Classifier', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'License', 'GPL-2.0'),
+        ('Classifier', 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', 'License', 'GPL-2.0+'),
+        ('Classifier', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'License', 'GPL-3.0'),
+        ('Classifier', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'License', 'GPL-3.0+'),
+        ('Classifier', 'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)', 'License', 'LGPL-2.0'),
+        ('Classifier', 'License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)', 'License', 'LGPL-2.0+'),
+        ('Classifier', 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', 'License', 'LGPL-3.0'),
+        ('Classifier', 'License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)', 'License', 'LGPL-3.0+'),
+        ('Classifier', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'License', 'LGPL-1.0'),
+        ('Classifier', 'License :: OSI Approved :: IBM Public License', 'License', 'IPL'),
+        ('Classifier', 'License :: OSI Approved :: ISC License (ISCL)', 'License', 'ISC'),
+        ('Classifier', 'License :: OSI Approved :: Intel Open Source License', 'License', 'Intel'),
+        ('Classifier', 'License :: OSI Approved :: Jabber Open Source License', 'License', 'Jabber'),
+        ('Classifier', 'License :: OSI Approved :: MIT License', 'License', 'MIT'),
+        ('Classifier', 'License :: OSI Approved :: MITRE Collaborative Virtual Workspace License (CVW)', 'License', 'CVWL'),
+        ('Classifier', 'License :: OSI Approved :: Motosoto License', 'License', 'Motosoto'),
+        ('Classifier', 'License :: OSI Approved :: Mozilla Public License 1.0 (MPL)', 'License', 'MPL-1.0'),
+        ('Classifier', 'License :: OSI Approved :: Mozilla Public License 1.1 (MPL 1.1)', 'License', 'MPL-1.1'),
+        ('Classifier', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'License', 'MPL-2.0'),
+        ('Classifier', 'License :: OSI Approved :: Nethack General Public License', 'License', 'NGPL'),
+        ('Classifier', 'License :: OSI Approved :: Nokia Open Source License', 'License', 'Nokia'),
+        ('Classifier', 'License :: OSI Approved :: Open Group Test Suite License', 'License', 'OGTSL'),
+        ('Classifier', 'License :: OSI Approved :: Python License (CNRI Python License)', 'License', 'CNRI-Python'),
+        ('Classifier', 'License :: OSI Approved :: Python Software Foundation License', 'License', 'PSF'),
+        ('Classifier', 'License :: OSI Approved :: Qt Public License (QPL)', 'License', 'QPL'),
+        ('Classifier', 'License :: OSI Approved :: Ricoh Source Code Public License', 'License', 'RSCPL'),
+        ('Classifier', 'License :: OSI Approved :: Sleepycat License', 'License', 'Sleepycat'),
+        ('Classifier', 'License :: OSI Approved :: Sun Industry Standards Source License (SISSL)', 'License', '--  Sun Industry Standards Source License (SISSL)'),
+        ('Classifier', 'License :: OSI Approved :: Sun Public License', 'License', 'SPL'),
+        ('Classifier', 'License :: OSI Approved :: University of Illinois/NCSA Open Source License', 'License', 'NCSA'),
+        ('Classifier', 'License :: OSI Approved :: Vovida Software License 1.0', 'License', 'VSL-1.0'),
+        ('Classifier', 'License :: OSI Approved :: W3C License', 'License', 'W3C'),
+        ('Classifier', 'License :: OSI Approved :: X.Net License', 'License', 'Xnet'),
+        ('Classifier', 'License :: OSI Approved :: Zope Public License', 'License', 'ZPL'),
+        ('Classifier', 'License :: OSI Approved :: zlib/libpng License', 'License', 'Zlib'),
+    ]
+
+    def __init__(self):
+        pass
+
+    def process(self, srctree, classes, lines_before, lines_after, handled):
+        if 'buildsystem' in handled:
+            return False
+
+        if not RecipeHandler.checkfiles(srctree, ['setup.py']):
+            return
+
+        # setup.py is always parsed, at a minimum to get the paths to the
+        # python packages/modules/scripts to avoid dep scanning the entire
+        # tree.
+        #
+        # If egg info is available, we use it for both its PKG-INFO metadata
+        # and for its requires.txt for install_requires.
+        # If PKG-INFO is available but no egg info is, we use that for metadata in preference to
+        # the parsed setup.py, but use the install_requires info from the
+        # parsed setup.py.
+
+        setupscript = os.path.join(srctree, 'setup.py')
+        try:
+            setup_info, uses_setuptools, setup_non_literals = self.parse_setup_py(setupscript)
+        except Exception:
+            logger.exception("Failed to parse setup.py")
+            setup_info, uses_setuptools, setup_non_literals = {}, True, []
+
+        egginfo = glob.glob(os.path.join(srctree, '*.egg-info'))
+        if egginfo:
+            info = self.get_pkginfo(os.path.join(egginfo[0], 'PKG-INFO'))
+            requires_txt = os.path.join(egginfo[0], 'requires.txt')
+            if os.path.exists(requires_txt):
+                with codecs.open(requires_txt) as f:
+                    inst_req = []
+                    for line in f.readlines():
+                        line = line.rstrip()
+                        if not line:
+                            continue
+
+                        # We don't currently support sections for optional deps
+                        if line.startswith('['):
+                            break
+                        inst_req.append(line)
+                    info['Install-requires'] = inst_req
+        elif RecipeHandler.checkfiles(srctree, ['PKG-INFO']):
+            info = self.get_pkginfo(os.path.join(srctree, 'PKG-INFO'))
+
+            if setup_info and 'Install-requires' in setup_info:
+                    info['Install-requires'] = setup_info['Install-requires']
+        else:
+            if setup_info:
+                info = setup_info
+            else:
+                info = self.get_setup_args_info(setupscript)
+
+        self.apply_info_replacements(info)
+
+        if uses_setuptools:
+            classes.append('setuptools')
+        else:
+            classes.append('distutils')
+
+        # Map PKG-INFO & setup.py fields to bitbake variables
+        bbinfo = {}
+        for field, values in info.iteritems():
+            if field in self.excluded_fields:
+                continue
+
+            if isinstance(values, basestring):
+                value = values
+            elif field not in self.bbvar_map:
+                for checkfield, search, newvar, value in self.list_entry_ops:
+                    if checkfield == field and search in values:
+                        if newvar in self.bbvar_map:
+                            newvar = self.bbvar_map[newvar]
+                        bbinfo[newvar] = value
+                continue
+            else:
+                value = ' '.join(v for v in values if v)
+
+            if field in self.bbvar_map:
+                bbvar = self.bbvar_map[field]
+                if bbvar not in bbinfo:
+                    bbinfo[bbvar] = value
+
+        for k in sorted(bbinfo):
+            v = bbinfo[k]
+            if not v:
+                continue
+            else:
+                lines_before.append('{} = "{}"'.format(k, v))
+        if bbinfo:
+            lines_before.append('')
+
+        inst_reqs = set()
+        if 'Install-requires' in info:
+            inst_reqs |= set(info['Install-requires'])
+            if inst_reqs:
+                lines_after.append('# WARNING: the following rdepends are from setuptools install_requires. These')
+                lines_after.append('# upstream names may not correspond exactly to bitbake package names.')
+                lines_after.append('RDEPENDS_${{PN}} += "{}"'.format(' '.join(r.lower() for r in sorted(inst_reqs))))
+
+        handled.append('buildsystem')
+
+    def get_pkginfo(self, pkginfo_fn):
+        msg = email.message_from_file(open(pkginfo_fn, 'r'))
+        msginfo = {}
+        for field in msg.keys():
+            values = msg.get_all(field)
+            if len(values) == 1:
+                msginfo[field] = values[0]
+            else:
+                msginfo[field] = values
+        return msginfo
+
+    def parse_setup_py(self, setupscript='./setup.py'):
+        setup_ast = self.parse_ast(setupscript)
+        visitor = SetupScriptVisitor()
+        visitor.visit(setup_ast)
+        info = visitor.setup_data
+        # Naive mapping of setup() arguments to PKG-INFO field names
+        for key, value in info.items():
+            del info[key]
+            key = key.replace('_', '-')
+            key = key[0].upper() + key[1:]
+            if key in self.setup_parse_map:
+                key = self.setup_parse_map[key]
+            info[key] = value
+        return info, 'setuptools' in visitor.imported_modules, visitor.non_literals
+
+    @staticmethod
+    def parse_ast(filename):
+        with codecs.open(filename, 'r') as f:
+            source = f.read()
+        return ast.parse(source, filename)
+
+    def get_setup_args_info(self, setupscript='./setup.py'):
+        cmd = ['python', setupscript]
+        info = {}
+        keys = set(self.bbvar_map.keys())
+        keys |= set(self.setuparg_list_fields)
+        keys |= set(self.setuparg_multi_line_values)
+        grouped_keys = itertools.groupby(keys, lambda k: (k in self.setuparg_list_fields, k in self.setuparg_multi_line_values))
+        for index, keys in grouped_keys:
+            if index == (True, False):
+                # Splitlines output for each arg as a list value
+                for key in keys:
+                    arg = self.setuparg_map.get(key, key.lower())
+                    try:
+                        arg_info = self.run_command(cmd + ['--' + arg], cwd=os.path.dirname(setupscript))
+                    except (OSError, subprocess.CalledProcessError):
+                        pass
+                    else:
+                        info[key] = [l.rstrip() for l in arg_info.splitlines()]
+            elif index == (False, True):
+                # Entire output for each arg
+                for key in keys:
+                    arg = self.setuparg_map.get(key, key.lower())
+                    try:
+                        arg_info = self.run_command(cmd + ['--' + arg], cwd=os.path.dirname(setupscript))
+                    except (OSError, subprocess.CalledProcessError):
+                        pass
+                    else:
+                        info[key] = arg_info
+            else:
+                info.update(self.get_setup_byline(list(keys), setupscript))
+        return info
+
+    def get_setup_byline(self, fields, setupscript='./setup.py'):
+        info = {}
+
+        cmd = ['python', setupscript]
+        cmd.extend('--' + self.setuparg_map.get(f, f.lower()) for f in fields)
+        try:
+            info_lines = self.run_command(cmd, cwd=os.path.dirname(setupscript)).splitlines()
+        except (OSError, subprocess.CalledProcessError):
+            pass
+        else:
+            if len(fields) != len(info_lines):
+                logger.error('Mismatch between setup.py output lines and number of fields')
+                sys.exit(1)
+
+            for lineno, line in enumerate(info_lines):
+                line = line.rstrip()
+                info[fields[lineno]] = line
+        return info
+
+    def apply_info_replacements(self, info):
+        for variable, search, replace in self.replacements:
+            if variable not in info:
+                continue
+
+            def replace_value(search, replace, value):
+                if replace is None:
+                    if re.search(search, value):
+                        return None
+                else:
+                    new_value = re.sub(search, replace, value)
+                    if value != new_value:
+                        return new_value
+                return value
+
+            value = info[variable]
+            if isinstance(value, basestring):
+                new_value = replace_value(search, replace, value)
+                if new_value is None:
+                    del info[variable]
+                elif new_value != value:
+                    info[variable] = new_value
+            else:
+                new_list = []
+                for pos, a_value in enumerate(value):
+                    new_value = replace_value(search, replace, a_value)
+                    if new_value is not None and new_value != value:
+                        new_list.append(new_value)
+
+                if value != new_list:
+                    info[variable] = new_list
+
+    @classmethod
+    def run_command(cls, cmd, **popenargs):
+        if 'stderr' not in popenargs:
+            popenargs['stderr'] = subprocess.STDOUT
+        try:
+            return subprocess.check_output(cmd, **popenargs)
+        except OSError as exc:
+            logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc)
+            raise
+        except subprocess.CalledProcessError as exc:
+            logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc.output)
+            raise
+
+
+class SetupScriptVisitor(ast.NodeVisitor):
+    def __init__(self):
+        ast.NodeVisitor.__init__(self)
+        self.non_literals = []
+        self.setup_data = {}
+        self.imported_modules = set()
+
+    def visit_Import(self, node):
+        for alias in node.names:
+            self.imported_modules.add(alias.name)
+
+    def visit_ImportFrom(self, node):
+        self.imported_modules.add(node.module)
+
+    def visit_Expr(self, node):
+        if isinstance(node.value, ast.Call) and \
+           isinstance(node.value.func, ast.Name) and \
+           node.value.func.id == 'setup':
+            self.visit_setup(node.value)
+            self.generic_visit(node.value)
+
+    def visit_setup(self, node):
+        for keyword in node.keywords:
+            name = keyword.arg
+            try:
+                value = ast.literal_eval(keyword.value)
+            except ValueError:
+                self.non_literals.append(name)
+            else:
+                self.setup_data[name] = value
+
+
+def plugin_init(pluginlist):
+    pass
+
+
+def register_recipe_handlers(handlers):
+    # We need to make sure this is ahead of the makefile fallback handler
+    handlers.insert(0, PythonRecipeHandler())
Signature · 1 line
1.8.3.4
#2 lore raw

PATCH 2/2 recipetool: add python dependency scanning support

In reply to Christopher Larson

This uses a standalone python script named pythondeps which now lives in scripts. It supports scanning for provided packages and imported modules/packages, the latter via the python ast. It's not perfect, and obviously conditional imports and try/except import blocks are handled naively, listing all the imports even if they aren't all used at once, but it gives the user a solid starting point for the recipe.

---
 scripts/lib/recipetool/create_buildsys_python.py | 147 +++++++++++++
 scripts/pythondeps                               | 250 +++++++++++++++++++++++
 2 files changed, 397 insertions(+)
 create mode 100755 scripts/pythondeps
scripts/lib/recipetool/create_buildsys_python.py +147 -0
index 3cdcafd..d651749 100644
@@ -40,6 +40,11 @@ def tinfoil_init(instance):
 
 
 class PythonRecipeHandler(RecipeHandler):
+    base_pkgdeps = ['python-core']
+    excluded_pkgdeps = ['python-dbg']
+    # os.path is provided by python-core
+    excluded_modules = ['builtins', 'os.path']
+
     bbvar_map = {
         'Name': 'PN',
         'Version': 'PV',
@@ -240,14 +245,41 @@ class PythonRecipeHandler(RecipeHandler):
         if bbinfo:
             lines_before.append('')
 
+        mapped_deps, unmapped_deps = self.scan_setup_python_deps(srctree, setup_info, setup_non_literals)
+
         inst_reqs = set()
         if 'Install-requires' in info:
             inst_reqs |= set(info['Install-requires'])
             if inst_reqs:
+                # Naive attempt to avoid listing things in unmapped deps which
+                # are already in install_requires. Only of any use if the
+                # python package name matches the project name.
+                unmapped_deps.difference_update(inst_reqs)
+
                 lines_after.append('# WARNING: the following rdepends are from setuptools install_requires. These')
                 lines_after.append('# upstream names may not correspond exactly to bitbake package names.')
                 lines_after.append('RDEPENDS_${{PN}} += "{}"'.format(' '.join(r.lower() for r in sorted(inst_reqs))))
 
+        if mapped_deps:
+            name = info.get('Name')
+            if name and name[0] in mapped_deps:
+                # Attempt to avoid self-reference
+                mapped_deps.remove(name[0])
+            mapped_deps -= set(self.excluded_pkgdeps)
+            if inst_reqs:
+                lines_after.append('')
+            lines_after.append('# WARNING: the following rdepends are determined through basic analysis of the')
+            lines_after.append('# python sources, and might not be 100% accurate. It is your responsibility to')
+            lines_after.append('# verify that the values are complete and correct.')
+            lines_after.append('RDEPENDS_${{PN}} += "{}"'.format(' '.join(sorted(mapped_deps))))
+
+        if unmapped_deps:
+            if mapped_deps:
+                lines_after.append('')
+            lines_after.append('# WARNING: We were unable to map the following python package/module')
+            lines_after.append('# dependencies to the bitbake packages which include them:')
+            lines_after.extend('#    {}'.format(d) for d in sorted(unmapped_deps))
+
         handled.append('buildsystem')
 
     def get_pkginfo(self, pkginfo_fn):
@@ -333,6 +365,70 @@ class PythonRecipeHandler(RecipeHandler):
                 info[fields[lineno]] = line
         return info
 
+    def scan_setup_python_deps(self, srctree, setup_info, setup_non_literals):
+        if 'package_dir' in setup_info:
+            package_dir = setup_info['Package-dir']
+        else:
+            package_dir = {}
+
+        class PackageDir(distutils.command.build_py.build_py):
+            def __init__(self, package_dir):
+                self.package_dir = package_dir
+
+        pd = PackageDir(package_dir)
+        to_scan = []
+        if not any(v in setup_non_literals for v in ['Py-modules', 'Scripts', 'Packages']):
+            if 'Py-modules' in setup_info:
+                for module in setup_info['Py-modules']:
+                    to_scan.append(pd.get_package_dir(module) + '.py')
+
+            if 'Packages' in setup_info:
+                for package in setup_info['Packages']:
+                    to_scan.append(pd.get_package_dir(package))
+
+            if 'Scripts' in setup_info:
+                to_scan.extend(setup_info['Scripts'])
+
+        if not to_scan:
+            to_scan = ['.']
+
+        provided_packages = self.parse_pkgdata_for_python_packages()
+        scanned_deps = self.scan_python_dependencies([os.path.join(srctree, p) for p in to_scan])
+        scanned_deps -= set(self.excluded_modules)
+        mapped_deps, unmapped_deps = set(self.base_pkgdeps), set()
+        for dep in scanned_deps:
+            mapped = provided_packages.get(dep)
+            if mapped:
+                mapped_deps.add(mapped)
+            else:
+                unmapped_deps.add(dep)
+        return mapped_deps, unmapped_deps
+
+    def scan_python_dependencies(self, paths):
+        deps = set()
+        try:
+            dep_output = self.run_command(['pythondeps', '-d'] + paths)
+        except (OSError, subprocess.CalledProcessError):
+            pass
+        else:
+            for line in dep_output.splitlines():
+                line = line.rstrip()
+                dep, filename = line.split('\t', 1)
+                if filename.endswith('/setup.py'):
+                    continue
+                deps.add(dep)
+
+        try:
+            provides_output = self.run_command(['pythondeps', '-p'] + paths)
+        except (OSError, subprocess.CalledProcessError):
+            pass
+        else:
+            provides_lines = (l.rstrip() for l in provides_output.splitlines())
+            provides = set(l for l in provides_lines if l and l != 'setup')
+            deps -= provides
+
+        return deps
+
     def apply_info_replacements(self, info):
         for variable, search, replace in self.replacements:
             if variable not in info:
@@ -365,6 +461,57 @@ class PythonRecipeHandler(RecipeHandler):
                 if value != new_list:
                     info[variable] = new_list
 
+    def parse_pkgdata_for_python_packages(self):
+        suffixes = [t[0] for t in imp.get_suffixes()]
+        pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR', True)
+
+        ldata = tinfoil.config_data.createCopy()
+        bb.parse.handle('classes/python-dir.bbclass', ldata, True)
+        python_sitedir = ldata.getVar('PYTHON_SITEPACKAGES_DIR', True)
+
+        dynload_dir = os.path.join(os.path.dirname(python_sitedir), 'lib-dynload')
+        python_dirs = [python_sitedir + os.sep,
+                       os.path.join(os.path.dirname(python_sitedir), 'dist-packages') + os.sep,
+                       os.path.dirname(python_sitedir) + os.sep]
+        packages = {}
+        for pkgdatafile in glob.glob('{}/runtime/*'.format(pkgdata_dir)):
+            files_info = None
+            with open(pkgdatafile, 'r') as f:
+                for line in f.readlines():
+                    field, value = line.split(': ', 1)
+                    if field == 'FILES_INFO':
+                        files_info = ast.literal_eval(value)
+                        break
+                else:
+                    continue
+
+            for fn in files_info.iterkeys():
+                for suffix in suffixes:
+                    if fn.endswith(suffix):
+                        break
+                else:
+                    continue
+
+                if fn.startswith(dynload_dir + os.sep):
+                    base = os.path.basename(fn)
+                    provided = base.split('.', 1)[0]
+                    packages[provided] = os.path.basename(pkgdatafile)
+                    continue
+
+                for python_dir in python_dirs:
+                    if fn.startswith(python_dir):
+                        relpath = fn[len(python_dir):]
+                        base, _ = os.path.splitext(relpath)
+
+                        if '/.debug/' in base:
+                            continue
+                        if os.path.basename(base) == '__init__':
+                            base = os.path.dirname(base)
+                        base = base.replace(os.sep + os.sep, os.sep)
+                        provided = base.replace(os.sep, '.')
+                        packages[provided] = os.path.basename(pkgdatafile)
+        return packages
+
     @classmethod
     def run_command(cls, cmd, **popenargs):
         if 'stderr' not in popenargs:
scripts/pythondeps new file +250 -0

250 lines not on this page · raw message

Signature · 1 line
1.8.3.4
#3 lore raw
In reply to Christopher Larson

Hi Chris,

Quoted 10 lines · On Thursday 08 January 2015 11:24:08 Christopher Larson wrote:

- Handles distutils & setuptools.
- Supports pulling metadata from PKG-INFO, .egg-info, & setup.py (via two different mechanisms).
- Doesn't handle python 3 yet.
- Optional dependencies via extra_requires are not currently handled.
- Implements scanning for dependencies by using the python ast to determine what modules/packages are being imported by the python code in question

Quoted 8 lines

See https://gist.github.com/kergoth/6cca6caa4e9b22a21f75 for the projects I used to test this against, and
https://gist.github.com/kergoth/7fea9494e3cf60b382ff which is the result of running recipetool create against every recipe that inherits distutils or setuptools in my build environment.

https://gist.github.com/kergoth/7ad4b5102b2a5fe3a956 has my current TODO for this feature.

This works pretty well, thanks!

I tried this on python-mako and got this:

------------- snip --------------
...
# WARNING: the following rdepends are from setuptools install_requires. These

# upstream names may not correspond exactly to bitbake package names.
RDEPENDS_${PN} += "markupsafe"

# WARNING: the following rdepends are determined through basic analysis of the

# python sources, and might not be 100% accurate. It is your responsibility to
# verify that the values are complete and correct.
RDEPENDS_${PN} += "python-core python-textutils"

# WARNING: We were unable to map the following python package/module

# dependencies to the bitbake packages which include them:
#    mako.lookup
#    mako.template
#    sys
------------- snip --------------

* Shouldn't it know that sys is provided by python-core (maybe this has to be hardcoded)?

* Possibly also that "mako" is a module provided by this recipe?

* Our existing recipe has "python-threading python-netclient python-html" for RDEPENDS_${PN}, I don't know if all of these are correct but it does at least try to import threading.

* Should we just assume by convention that package names should start with "python-" and thus make that prefix on all items brought in from setuptools install_requires?

* I think "It is your responsibility ..." is a little harsh for the dependency situation - you'll soon find out at runtime if the value is insufficient. I used this wording for LICENSE because if you don't check it yourself you won't find out if it's incorrect.

Earlier you mentioned it would be nice if the buildsystem handler could replace the existing value of LICENSE - I checked and it already can; you'll find the existing value in lines_before. It's all a little bit clunky API-wise but it is at least possible.

I also noticed when looking at this that my code wasn't replacing the version with ${PV} in S (but was in SRC_URI). I'll send a patch to fix that. The way the code works at the moment, I only replace it in SRC_URI if you've specified a file name containing the version and then we can find that same version in the SRC_URI value (I'm not sure there is any other practical way).

Cheers,
Paul

Signature · 2 lines
Paul Eggleton
Intel Open Source Technology Centre
#4 lore raw
Quoted 43 lines · Paul Eggleton

Hi Chris,

Quoted 11 lines · On Thursday 08 January 2015 11:24:08 Christopher Larson wrote:

- Handles distutils & setuptools.
- Supports pulling metadata from PKG-INFO, .egg-info, & setup.py (via two different mechanisms).
- Doesn't handle python 3 yet.
- Optional dependencies via extra_requires are not currently handled.
- Implements scanning for dependencies by using the python ast to determine what modules/packages are being imported by the python code in question

See https://gist.github.com/kergoth/6cca6caa4e9b22a21f75 for the

projects

Quoted 2 lines

I used to test this against, and
https://gist.github.com/kergoth/7fea9494e3cf60b382ff which is the

result of

Quoted 4 lines

running recipetool create against every recipe that inherits distutils or setuptools in my build environment.

https://gist.github.com/kergoth/7ad4b5102b2a5fe3a956 has my current

TODO for

Quoted 1 line

this feature.

This works pretty well, thanks!

I tried this on python-mako and got this:

------------- snip --------------
...
# WARNING: the following rdepends are from setuptools install_requires. These

# upstream names may not correspond exactly to bitbake package names.
RDEPENDS_${PN} += "markupsafe"

# WARNING: the following rdepends are determined through basic analysis of the

# python sources, and might not be 100% accurate. It is your
responsibility to
# verify that the values are complete and correct.
RDEPENDS_${PN} += "python-core python-textutils"
Quoted 7 lines

# WARNING: We were unable to map the following python package/module

# dependencies to the bitbake packages which include them:
#    mako.lookup
#    mako.template
#    sys
------------- snip --------------

There was a bug which didn't properly detect a case where some of its info from setup.py (scripts in this case) is available, but some of it is not (packages), and as a result ended up only parsing some of the python code available. Since the paths provided to the dependency scanning are also passed to the packages search, it didn't pick up on the provide of mako & mako.* either. Once that's fixed, it looks like this:
https://gist.github.com/0a641e90cdfd37fd2100.

* Shouldn't it know that sys is provided by python-core (maybe this has to

Quoted 3 lines

be
hardcoded)?

Yeah, there are cases where it can't pick up a provide. Built-in modules (which is the case here), C extensions, or if a module is renamed or similar programmatically (os.path is actually posixpath in linux).

It seems that sys.builtin_module_names lists the built-in modules. To get at that list, we could use that from recipetool and implicitly assume that this list is the same for the host python as the target, which isn't ideal, or we could run the native python from the sysroot, which I'm not currently using in any way, or we could copy the list into recipetool. Thoughts?

* Our existing recipe has "python-threading python-netclient python-html"

Quoted 5 lines

for
RDEPENDS_${PN}, I don't know if all of these are correct but it does at least
try to import threading.

With the aforementioned bug fixed, it picks up these and many others, thankfully.

Quoted 4 lines

* Should we just assume by convention that package names should start with "python-" and thus make that prefix on all items brought in from setuptools install_requires?

Good question, I'd thought about this too. Whichever way we go, the user will have to review and confirm sanity regardless, so it's a matter of trying to optimize for the common case. One would hope that the python- convention would be the common case, so I'm not opposed to this.

Quoted 9 lines

* I think "It is your responsibility ..." is a little harsh for the dependency
situation - you'll soon find out at runtime if the value is insufficient. I used
this wording for LICENSE because if you don't check it yourself you won't find
out if it's incorrect.

K, I'll drop that.

Earlier you mentioned it would be nice if the buildsystem handler could

Quoted 6 lines

replace the existing value of LICENSE - I checked and it already can; you'll
find the existing value in lines_before. It's all a little bit clunky API-wise
but it is at least possible.

Ah! I swear I tried exactly that, but apparently something went wrong. I'll look into adding that feature to simplify the recipe.

I also noticed when looking at this that my code wasn't replacing the

Quoted 9 lines

version
with ${PV} in S (but was in SRC_URI). I'll send a patch to fix that. The way
the code works at the moment, I only replace it in SRC_URI if you've specified
a file name containing the version and then we can find that same version in the
SRC_URI value (I'm not sure there is any other practical way)

Cool, thanks. I'd noticed this too (in fact it's in the linked todo list :).

After reviewing the generated recipe for mako more closely, I see multiple potential concerns:
- It doesn't handle find_packages() for packages in setup.py. This is relatively minor, without knowing the list of packages being shipped, we just scan the whole source tree -- this is why things like nose are showing up in the new recipe, because it scanned the unit test suite. So I see this as a potential future enhancement.
- setuptools/pkg_resources still isn't being properly mapped, even with both python and python-distribute built. It looks like python-distribute ships setuptools.py & friends in an egg, and the package search via pkgdata isn't handling that. - Fixed locally.
- The detected 'beaker' dependency is an optional one, which we'd know if we parsed extra_requires() or the optional sections of *.egg-info/requires.txt. This is a known limitation and is already on the todo list.
- The babel/pygments/templating deps are slightly interesting. Mako doesn't actually depend on these itself, but it does provide extensions to those projects via entry points. It could be worth enhancing the tool to handle those specially, either excluding the entry point packages from the dependency scanning, or somehow automatically splitting out the entry point bits into separate binary packages, but that'd be slightly non-trivial, and might be more "magic" than we want going on. Worth looking into as a potential enhancement.
- urllib.parse/urllib.request/html.entities: these were picked up out of compat.py, which does runtime python 2 vs 3 handling, so these are python 3 module deps. There's really no way to avoid this sort of thing, whenever we have conditional imports going on, it's going to pick up them all.

Up next:
- Drop the duplicated LICENSE
- Drop the 'your responsibility' message
- Rebase to merge in the local fixes mentioned above
- Add python- prefixes to non-mapped deps (e.g. install-requires)
- For now, add 'sys' to the hardcoded list of modules to ignore (part of core)

After that, I'll re-submit.

Then for the future enhancements todo:
- Handle all of sys.builtin_module_names
- Consider handling find_packages(), particularly the excludes=
- Consider handling deps detected from non-local entry points

Signature · 5 lines
Christopher Larson
kergoth at gmail dot com
Founder - BitBake, OpenEmbedded, OpenZaurus
Maintainer - Tslib
Senior Software Engineer, Mentor Graphics
#5 lore raw

Hi Chris,

Quoted 15 lines · On Monday 12 January 2015 11:00:56 Christopher Larson wrote:

There was a bug which didn't properly detect a case where some of its info from setup.py (scripts in this case) is available, but some of it is not (packages), and as a result ended up only parsing some of the python code available. Since the paths provided to the dependency scanning are also passed to the packages search, it didn't pick up on the provide of mako & mako.* either. Once that's fixed, it looks like this:
https://gist.github.com/0a641e90cdfd37fd2100.

Quoted 2 lines

* Shouldn't it know that sys is provided by python-core (maybe this has to be hardcoded)?

Yeah, there are cases where it can't pick up a provide. Built-in modules (which is the case here), C extensions, or if a module is renamed or similar programmatically (os.path is actually posixpath in linux).

Quoted 5 lines

It seems that sys.builtin_module_names lists the built-in modules. To get at that list, we could use that from recipetool and implicitly assume that this list is the same for the host python as the target, which isn't ideal, or we could run the native python from the sysroot, which I'm not currently using in any way, or we could copy the list into recipetool. Thoughts?

In this instance as long as we aren't mixing 2.x vs 3.x I think we should be OK with assuming that the host and target python will be the same (at least for now).

Quoted 6 lines
Quoted 3 lines

* Our existing recipe has "python-threading python-netclient python-html" for RDEPENDS_${PN}, I don't know if all of these are correct but it does at least try to import threading.

With the aforementioned bug fixed, it picks up these and many others, thankfully.

Great!

Quoted 33 lines
Quoted 3 lines

* Should we just assume by convention that package names should start with "python-" and thus make that prefix on all items brought in from setuptools install_requires?

Good question, I'd thought about this too. Whichever way we go, the user will have to review and confirm sanity regardless, so it's a matter of trying to optimize for the common case. One would hope that the python- convention would be the common case, so I'm not opposed to this.

Quoted 4 lines

* I think "It is your responsibility ..." is a little harsh for the dependency situation - you'll soon find out at runtime if the value is insufficient. I used this wording for LICENSE because if you don't check it yourself you won't find out if it's incorrect.

K, I'll drop that.

Quoted 4 lines

Earlier you mentioned it would be nice if the buildsystem handler could replace the existing value of LICENSE - I checked and it already can; you'll find the existing value in lines_before. It's all a little bit clunky API-wise but it is at least possible.

Ah! I swear I tried exactly that, but apparently something went wrong. I'll look into adding that feature to simplify the recipe.

Quoted 6 lines

I also noticed when looking at this that my code wasn't replacing the version with ${PV} in S (but was in SRC_URI). I'll send a patch to fix that. The way the code works at the moment, I only replace it in SRC_URI if you've specified a file name containing the version and then we can find that same version in the SRC_URI value (I'm not sure there is any other practical way)

Cool, thanks. I'd noticed this too (in fact it's in the linked todo list :).

Quoted 8 lines

After reviewing the generated recipe for mako more closely, I see multiple potential concerns:

- It doesn't handle find_packages() for packages in setup.py. This is relatively minor, without knowing the list of packages being shipped, we just scan the whole source tree -- this is why things like nose are showing up in the new recipe, because it scanned the unit test suite. So I see this as a potential future enhancement.

Right, that would be useful; test suites often do have extended dependencies.

Quoted 8 lines

- setuptools/pkg_resources still isn't being properly mapped, even with both python and python-distribute built. It looks like python-distribute ships setuptools.py & friends in an egg, and the package search via pkgdata isn't handling that. - Fixed locally.
- The detected 'beaker' dependency is an optional one, which we'd know if we parsed extra_requires() or the optional sections of *.egg-info/requires.txt. This is a known limitation and is already on the todo list.

OK, cool. At least for the moment it's better to have the note than to not have it and miss dependencies leading to an additional round of recipe fixing.

Quoted 8 lines

- The babel/pygments/templating deps are slightly interesting. Mako doesn't actually depend on these itself, but it does provide extensions to those projects via entry points. It could be worth enhancing the tool to handle those specially, either excluding the entry point packages from the dependency scanning, or somehow automatically splitting out the entry point bits into separate binary packages, but that'd be slightly non-trivial, and might be more "magic" than we want going on. Worth looking into as a potential enhancement.

Right, that sounds like a future enhancement to me as well.

Quoted 4 lines

- urllib.parse/urllib.request/html.entities: these were picked up out of compat.py, which does runtime python 2 vs 3 handling, so these are python 3 module deps. There's really no way to avoid this sort of thing, whenever we have conditional imports going on, it's going to pick up them all.

Right, yes.

Quoted 9 lines

Up next:
- Drop the duplicated LICENSE
- Drop the 'your responsibility' message
- Rebase to merge in the local fixes mentioned above
- Add python- prefixes to non-mapped deps (e.g. install-requires)
- For now, add 'sys' to the hardcoded list of modules to ignore (part of core)

After that, I'll re-submit.

Great, thanks.

Quoted 4 lines

Then for the future enhancements todo:
- Handle all of sys.builtin_module_names
- Consider handling find_packages(), particularly the excludes=
- Consider handling deps detected from non-local entry points

Sounds good :)

Cheers,
Paul

Signature · 2 lines
Paul Eggleton
Intel Open Source Technology Centre