Skip to contentSkip to conversation

utils/scanpypi: refactor setuptools handling to not use imp

PATCH Superseded James Hilliard 2 participants 3 messages Nov 30, 2023 – May 9, 2024

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 utils/scanpypi: refactor setuptools handling to not use imp

The imp module is deprecated as of python verison 3.12.

Refactor setuptools handling to remove monkeypatching hack and instead do pep517 metadata generation and dependency resolution.

Invert setuptools/pyproject fallback ordering so that we try parsing pyproject.toml files first.

---
Changes v1 -> v2:
- split out set comprehension changes

---
 utils/scanpypi | 88 +++++++++++++++++---------------------------------
 1 file changed, 29 insertions(+), 59 deletions(-)
utils/scanpypi +29 -59
index 021c99a172..9de1b5d402 100755
@@ -18,8 +18,8 @@ import hashlib
 import re
 import textwrap
 import tempfile
-import imp
-from functools import wraps
+import importlib
+from setuptools.build_meta import prepare_metadata_for_build_wheel
 import six.moves.urllib.request
 import six.moves.urllib.error
 import six.moves.urllib.parse
@@ -93,32 +93,6 @@ def toml_load(f):
         raise ex
 
 
-def setup_decorator(func, method):
-    """
-    Decorator for distutils.core.setup and setuptools.setup.
-    Puts the arguments with which setup is called as a dict
-    Add key 'method' which should be either 'setuptools' or 'distutils'.
-
-    Keyword arguments:
-    func -- either setuptools.setup or distutils.core.setup
-    method -- either 'setuptools' or 'distutils'
-    """
-
-    @wraps(func)
-    def closure(*args, **kwargs):
-        # Any python packages calls its setup function to be installed.
-        # Argument 'name' of this setup function is the package's name
-        BuildrootPackage.setup_args[kwargs['name']] = kwargs
-        BuildrootPackage.setup_args[kwargs['name']]['method'] = method
-    return closure
-
-# monkey patch
-import setuptools  # noqa E402
-setuptools.setup = setup_decorator(setuptools.setup, 'setuptools')
-import distutils   # noqa E402
-distutils.core.setup = setup_decorator(setuptools.setup, 'distutils')
-
-
 def find_file_upper_case(filenames, path='./'):
     """
     List generator:
@@ -345,26 +319,18 @@ class BuildrootPackage():
         """
         current_dir = os.getcwd()
         os.chdir(self.tmp_extract)
-        sys.path.insert(0, self.tmp_extract)
         try:
-            s_file, s_path, s_desc = imp.find_module('setup', [self.tmp_extract])
-            imp.load_module('__main__', s_file, s_path, s_desc)
-            if self.metadata_name in self.setup_args:
-                pass
-            elif self.metadata_name.replace('_', '-') in self.setup_args:
-                self.metadata_name = self.metadata_name.replace('_', '-')
-            elif self.metadata_name.replace('-', '_') in self.setup_args:
-                self.metadata_name = self.metadata_name.replace('-', '_')
+            metadata = prepare_metadata_for_build_wheel(self.tmp_extract)
             try:
-                self.setup_metadata = self.setup_args[self.metadata_name]
-            except KeyError:
-                # This means setup was not called
-                print('ERROR: Could not determine package metadata for {pkg}.\n'
-                      .format(pkg=self.real_name))
-                raise
+                dist = importlib.metadata.Distribution.at(metadata)
+                self.metadata_name = dist.name
+                self.setup_metadata = {'method': 'setuptools'}
+                if dist.requires:
+                    self.setup_metadata['install_requires'] = dist.requires
+            finally:
+                shutil.rmtree(metadata)
         finally:
             os.chdir(current_dir)
-            sys.path.remove(self.tmp_extract)
 
     def load_pyproject(self):
         """
@@ -372,7 +338,6 @@ class BuildrootPackage():
         """
         current_dir = os.getcwd()
         os.chdir(self.tmp_extract)
-        sys.path.insert(0, self.tmp_extract)
         try:
             pyproject_data = toml_load('pyproject.toml')
             try:
@@ -380,20 +345,25 @@ class BuildrootPackage():
                 self.metadata_name = self.setup_metadata.get('name', self.real_name)
                 build_system = pyproject_data.get('build-system', {})
                 build_backend = build_system.get('build-backend', None)
-                if build_backend and build_backend == 'flit_core.buildapi':
-                    self.setup_metadata['method'] = 'flit'
+                if build_backend:
+                    if build_backend == 'flit_core.buildapi':
+                        self.setup_metadata['method'] = 'flit'
+                    elif build_backend == 'setuptools.build_meta':
+                        raise Exception("handle setuptools")
+                    else:
+                        self.setup_metadata['method'] = 'unknown'
                 elif build_system.get('backend-path', None):
                     self.setup_metadata['method'] = 'pep517'
                 else:
-                    self.setup_metadata['method'] = 'unknown'
+                    raise Exception("handle setuptools")
             except KeyError:
                 print('ERROR: Could not determine package metadata for {pkg}.\n'
                       .format(pkg=self.real_name))
                 raise
         except FileNotFoundError:
             raise
-        os.chdir(current_dir)
-        sys.path.remove(self.tmp_extract)
+        finally:
+            os.chdir(current_dir)
 
     def get_requirements(self, pkg_folder):
         """
@@ -778,15 +748,15 @@ def main():
 
             # Loading the package install info from the package
             try:
-                package.load_setup()
-            except ImportError as err:
-                if 'buildutils' in str(err):
-                    print('This package needs buildutils')
-                    continue
-                else:
-                    try:
-                        package.load_pyproject()
-                    except Exception:
+                package.load_pyproject()
+            except Exception:
+                try:
+                    package.load_setup()
+                except ImportError as err:
+                    if 'buildutils' in str(err):
+                        print('This package needs buildutils')
+                        continue
+                    else:
                         raise
             except (AttributeError, KeyError) as error:
                 print('Error: Could not install package {pkg}: {error}'.format(
Signature · 6 lines
2.34.1

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#1 lore raw

Hello James,

Quoted 4 lines · On Thu, 30 Nov 2023 14:21:53 -0700 James Hilliard <[email protected]>…

The imp module is deprecated as of python verison 3.12.

Refactor setuptools handling to remove monkeypatching hack and instead do pep517 metadata generation and dependency resolution.

How does it work without monkeypatching? Why was monkeypatching needed before and no longer needed now?

Quoted 2 lines

Invert setuptools/pyproject fallback ordering so that we try parsing pyproject.toml files first.

What is the motivation for this particular change (inverting the order between setuptools and pyproject)?

Also, this patch should be split into several ones, as you're really doing several independent things, as far as I can see.

utils/scanpypi import hashlib · line 22

Quoted 12 lines
utils/scanpypi +2 -2
index 021c99a172..9de1b5d402 100755
@@ -18,8 +18,8 @@ import hashlib
 import re
 import textwrap
 import tempfile
-import imp
-from functools import wraps
+import importlib
+from setuptools.build_meta import prepare_metadata_for_build_wheel

This is part of the "don't use imp / remove monkeypatching" thing if I understand correctly.

Quoted 21 lines
utils/scanpypi +0 -14
 import six.moves.urllib.request
 import six.moves.urllib.error
 import six.moves.urllib.parse
@@ -93,32 +93,6 @@ def toml_load(f):
         raise ex
 
 
-def setup_decorator(func, method):
-    """
-    Decorator for distutils.core.setup and setuptools.setup.
-    Puts the arguments with which setup is called as a dict
-    Add key 'method' which should be either 'setuptools' or 'distutils'.
-
-    Keyword arguments:
-    func -- either setuptools.setup or distutils.core.setup
-    method -- either 'setuptools' or 'distutils'
-    """
-
-    @wraps(func)
-    def closure(*args, **kwargs):
-        # Any python packages calls its setup function to be installed.

utils/scanpypi def toml_load(f): · line 119

Quoted 10 lines
utils/scanpypi +0 -10
-        # Argument 'name' of this setup function is the package's name
-        BuildrootPackage.setup_args[kwargs['name']] = kwargs
-        BuildrootPackage.setup_args[kwargs['name']]['method'] = method
-    return closure
-
-# monkey patch
-import setuptools  # noqa E402
-setuptools.setup = setup_decorator(setuptools.setup, 'setuptools')
-import distutils   # noqa E402
-distutils.core.setup = setup_decorator(setuptools.setup, 'distutils')

This is part of the "don't use imp / remove monkeypatching" thing if I understand correctly.

utils/scanpypi class BuildrootPackage(): · line 348

Quoted 8 lines
utils/scanpypi +0 -1
 def find_file_upper_case(filenames, path='./'):
     """
     List generator:
@@ -345,26 +319,18 @@ class BuildrootPackage():
         """
         current_dir = os.getcwd()
         os.chdir(self.tmp_extract)
-        sys.path.insert(0, self.tmp_extract)

Not sure to what this is related? The monkeypatching as well? The use of imp?

Quoted 14 lines
utils/scanpypi +1 -11
         try:
-            s_file, s_path, s_desc = imp.find_module('setup', [self.tmp_extract])
-            imp.load_module('__main__', s_file, s_path, s_desc)
-            if self.metadata_name in self.setup_args:
-                pass
-            elif self.metadata_name.replace('_', '-') in self.setup_args:
-                self.metadata_name = self.metadata_name.replace('_', '-')
-            elif self.metadata_name.replace('-', '_') in self.setup_args:
-                self.metadata_name = self.metadata_name.replace('-', '_')
+            metadata = prepare_metadata_for_build_wheel(self.tmp_extract)
             try:
-                self.setup_metadata = self.setup_args[self.metadata_name]
-            except KeyError:
-                # This means setup was not called

utils/scanpypi class BuildrootPackage(): · line 331

Quoted 10 lines
utils/scanpypi +7 -3
-                print('ERROR: Could not determine package metadata for {pkg}.\n'
-                      .format(pkg=self.real_name))
-                raise
+                dist = importlib.metadata.Distribution.at(metadata)
+                self.metadata_name = dist.name
+                self.setup_metadata = {'method': 'setuptools'}
+                if dist.requires:
+                    self.setup_metadata['install_requires'] = dist.requires
+            finally:
+                shutil.rmtree(metadata)

This is part of the "don't use imp / remove monkeypatching" thing if I understand correctly.

Quoted 17 lines
utils/scanpypi +0 -2
         finally:
             os.chdir(current_dir)
-            sys.path.remove(self.tmp_extract)
 
     def load_pyproject(self):
         """
@@ -372,7 +338,6 @@ class BuildrootPackage():
         """
         current_dir = os.getcwd()
         os.chdir(self.tmp_extract)
-        sys.path.insert(0, self.tmp_extract)
         try:
             pyproject_data = toml_load('pyproject.toml')
             try:
@@ -380,20 +345,25 @@ class BuildrootPackage():
                 self.metadata_name = self.setup_metadata.get('name', self.real_name)
                 build_system = pyproject_data.get('build-system', {})

utils/scanpypi class BuildrootPackage(): · line 354

Quoted 10 lines
utils/scanpypi +7 -2
                 build_backend = build_system.get('build-backend', None)
-                if build_backend and build_backend == 'flit_core.buildapi':
-                    self.setup_metadata['method'] = 'flit'
+                if build_backend:
+                    if build_backend == 'flit_core.buildapi':
+                        self.setup_metadata['method'] = 'flit'
+                    elif build_backend == 'setuptools.build_meta':
+                        raise Exception("handle setuptools")
+                    else:
+                        self.setup_metadata['method'] = 'unknown'

This seems more related to PEP517 handling improvements?

utils/scanpypi class BuildrootPackage(): · line 358

Quoted 5 lines
utils/scanpypi +1 -1
                 elif build_system.get('backend-path', None):
                     self.setup_metadata['method'] = 'pep517'
                 else:
-                    self.setup_metadata['method'] = 'unknown'
+                    raise Exception("handle setuptools")

So we don't support setuptools as a PEP517 backend? I guess it was already the case before your patch?

utils/scanpypi class BuildrootPackage(): · line 396

Quoted 8 lines
utils/scanpypi +0 -2
             except KeyError:
                 print('ERROR: Could not determine package metadata for {pkg}.\n'
                       .format(pkg=self.real_name))
                 raise
         except FileNotFoundError:
             raise
-        os.chdir(current_dir)
-        sys.path.remove(self.tmp_extract)

Related to what?

Quoted 17 lines
utils/scanpypi +2 -8
+        finally:
+            os.chdir(current_dir)
 
     def get_requirements(self, pkg_folder):
         """
@@ -778,15 +748,15 @@ def main():
 
             # Loading the package install info from the package
             try:
-                package.load_setup()
-            except ImportError as err:
-                if 'buildutils' in str(err):
-                    print('This package needs buildutils')
-                    continue
-                else:
-                    try:
-                        package.load_pyproject()

utils/scanpypi def main(): · line 759

Quoted 10 lines
utils/scanpypi +9 -1
-                    except Exception:
+                package.load_pyproject()
+            except Exception:
+                try:
+                    package.load_setup()
+                except ImportError as err:
+                    if 'buildutils' in str(err):
+                        print('This package needs buildutils')
+                        continue
+                    else:

This is a separate change, about the ordering between .load_setup() and .load_pyproject().

Could you split this useful patch into smaller chunks, with a better justification for each chunk?

Believe me, if you do this, patches like this will be merged, much, much, much faster.

Thanks a lot for your contribution!

Thomas

Signature · 7 lines
Thomas Petazzoni, co-owner and CEO, Bootlin
Embedded Linux and Kernel engineering and training
https://bootlin.com
_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#2 lore raw
Quoted 6 lines · Thomas Petazzoni

Hello James,

On Thu, 30 Nov 2023 14:21:53 -0700
James Hilliard <[email protected]> wrote:

Quoted 7 lines
Quoted 4 lines

The imp module is deprecated as of python verison 3.12.

Refactor setuptools handling to remove monkeypatching hack and instead do pep517 metadata generation and dependency resolution.

How does it work without monkeypatching? Why was monkeypatching needed before and no longer needed now?

This is due to pep517 having a standardized way of retrieving metadata, the monkeypatching was a hack to deal with setuptools/distutils not providing a proper method for getting metadata.

Quoted 6 lines
Quoted 3 lines

Invert setuptools/pyproject fallback ordering so that we try parsing pyproject.toml files first.

What is the motivation for this particular change (inverting the order between setuptools and pyproject)?

We want this to follow the same order of preference as our build infrastructure, which now uses pep517 for setuptools based packages and thus pyproject.toml is checked first.

Quoted 3 lines

Also, this patch should be split into several ones, as you're really doing several independent things, as far as I can see.

It's all kind of intertwined and hard to split out.

Quoted 16 lines

utils/scanpypi import hashlib · line 22

Quoted 13 lines
utils/scanpypi +2 -2
index 021c99a172..9de1b5d402 100755
@@ -18,8 +18,8 @@ import hashlib
 import re
 import textwrap
 import tempfile
-import imp
-from functools import wraps
+import importlib
+from setuptools.build_meta import prepare_metadata_for_build_wheel

This is part of the "don't use imp / remove monkeypatching" thing if I understand correctly.

Yes, this is related to replacing the monkeypatching.

Quoted 27 lines
Quoted 27 lines
utils/scanpypi +0 -19
 import six.moves.urllib.request
 import six.moves.urllib.error
 import six.moves.urllib.parse
@@ -93,32 +93,6 @@ def toml_load(f):
         raise ex
 
 
-def setup_decorator(func, method):
-    """
-    Decorator for distutils.core.setup and setuptools.setup.
-    Puts the arguments with which setup is called as a dict
-    Add key 'method' which should be either 'setuptools' or 'distutils'.
-
-    Keyword arguments:
-    func -- either setuptools.setup or distutils.core.setup
-    method -- either 'setuptools' or 'distutils'
-    """
-
-    @wraps(func)
-    def closure(*args, **kwargs):
-        # Any python packages calls its setup function to be installed.
-        # Argument 'name' of this setup function is the package's name
-        BuildrootPackage.setup_args[kwargs['name']] = kwargs
-        BuildrootPackage.setup_args[kwargs['name']]['method'] = method
-    return closure
-
Quoted 8 lines

utils/scanpypi def toml_load(f): · line 119

Quoted 5 lines
utils/scanpypi +0 -5
-# monkey patch
-import setuptools  # noqa E402
-setuptools.setup = setup_decorator(setuptools.setup, 'setuptools')
-import distutils   # noqa E402
-distutils.core.setup = setup_decorator(setuptools.setup, 'distutils')

This is part of the "don't use imp / remove monkeypatching" thing if I understand correctly.

Yes.

Quoted 12 lines

utils/scanpypi class BuildrootPackage(): · line 348

Quoted 9 lines
utils/scanpypi +0 -1
 def find_file_upper_case(filenames, path='./'):
     """
     List generator:
@@ -345,26 +319,18 @@ class BuildrootPackage():
         """
         current_dir = os.getcwd()
         os.chdir(self.tmp_extract)
-        sys.path.insert(0, self.tmp_extract)

Not sure to what this is related? The monkeypatching as well? The use of imp?

Yeah, so this is being removed due to it being used by the monkeypatching hack.

Quoted 26 lines
Quoted 15 lines
utils/scanpypi +1 -11
         try:
-            s_file, s_path, s_desc = imp.find_module('setup', [self.tmp_extract])
-            imp.load_module('__main__', s_file, s_path, s_desc)
-            if self.metadata_name in self.setup_args:
-                pass
-            elif self.metadata_name.replace('_', '-') in self.setup_args:
-                self.metadata_name = self.metadata_name.replace('_', '-')
-            elif self.metadata_name.replace('-', '_') in self.setup_args:
-                self.metadata_name = self.metadata_name.replace('-', '_')
+            metadata = prepare_metadata_for_build_wheel(self.tmp_extract)
             try:
-                self.setup_metadata = self.setup_args[self.metadata_name]
-            except KeyError:
-                # This means setup was not called

utils/scanpypi class BuildrootPackage(): · line 331

Quoted 10 lines
utils/scanpypi +7 -3
-                print('ERROR: Could not determine package metadata for {pkg}.\n'
-                      .format(pkg=self.real_name))
-                raise
+                dist = importlib.metadata.Distribution.at(metadata)
+                self.metadata_name = dist.name
+                self.setup_metadata = {'method': 'setuptools'}
+                if dist.requires:
+                    self.setup_metadata['install_requires'] = dist.requires
+            finally:
+                shutil.rmtree(metadata)
Quoted 2 lines

This is part of the "don't use imp / remove monkeypatching" thing if I understand correctly.

Yep, this is also part of replacing the monkeypatching.

Quoted 22 lines
Quoted 22 lines
utils/scanpypi +1 -4
         finally:
             os.chdir(current_dir)
-            sys.path.remove(self.tmp_extract)
 
     def load_pyproject(self):
         """
@@ -372,7 +338,6 @@ class BuildrootPackage():
         """
         current_dir = os.getcwd()
         os.chdir(self.tmp_extract)
-        sys.path.insert(0, self.tmp_extract)
         try:
             pyproject_data = toml_load('pyproject.toml')
             try:
@@ -380,20 +345,25 @@ class BuildrootPackage():
                 self.metadata_name = self.setup_metadata.get('name', self.real_name)
                 build_system = pyproject_data.get('build-system', {})
                 build_backend = build_system.get('build-backend', None)
-                if build_backend and build_backend == 'flit_core.buildapi':
-                    self.setup_metadata['method'] = 'flit'
+                if build_backend:
Quoted 8 lines

utils/scanpypi class BuildrootPackage(): · line 354

Quoted 6 lines
utils/scanpypi +6 -0
+                    if build_backend == 'flit_core.buildapi':
+                        self.setup_metadata['method'] = 'flit'
+                    elif build_backend == 'setuptools.build_meta':
+                        raise Exception("handle setuptools")
+                    else:
+                        self.setup_metadata['method'] = 'unknown'

This seems more related to PEP517 handling improvements?

Yes, but it's related to removing the monkeypatching still in that otherwise stuff will break due to incorrect ordering.

Quoted 9 lines

utils/scanpypi class BuildrootPackage(): · line 358

Quoted 6 lines
utils/scanpypi +1 -1
                 elif build_system.get('backend-path', None):
                     self.setup_metadata['method'] = 'pep517'
                 else:
-                    self.setup_metadata['method'] = 'unknown'
+                    raise Exception("handle setuptools")

So we don't support setuptools as a PEP517 backend? I guess it was already the case before your patch?

This is just to force the codepath to use the fallback for setuptools which was previously used preferentially with the monkeypatching.

I'm thinking I should probably refactor this to handle pyproject.toml setuptools within load_pyproject as it's a bit confusing.

Quoted 11 lines

utils/scanpypi class BuildrootPackage(): · line 396

Quoted 9 lines
utils/scanpypi +0 -2
             except KeyError:
                 print('ERROR: Could not determine package metadata for {pkg}.\n'
                       .format(pkg=self.real_name))
                 raise
         except FileNotFoundError:
             raise
-        os.chdir(current_dir)
-        sys.path.remove(self.tmp_extract)

Related to what?

Removal of the monkeypatching hack.

Quoted 23 lines
Quoted 23 lines
utils/scanpypi +6 -9
+        finally:
+            os.chdir(current_dir)
 
     def get_requirements(self, pkg_folder):
         """
@@ -778,15 +748,15 @@ def main():
 
             # Loading the package install info from the package
             try:
-                package.load_setup()
-            except ImportError as err:
-                if 'buildutils' in str(err):
-                    print('This package needs buildutils')
-                    continue
-                else:
-                    try:
-                        package.load_pyproject()
-                    except Exception:
+                package.load_pyproject()
+            except Exception:
+                try:
+                    package.load_setup()
Quoted 8 lines

utils/scanpypi def main(): · line 759

Quoted 5 lines
utils/scanpypi +5 -0
+                except ImportError as err:
+                    if 'buildutils' in str(err):
+                        print('This package needs buildutils')
+                        continue
+                    else:

This is a separate change, about the ordering between .load_setup() and .load_pyproject().

This is actually related as the new pep517 based setuptools method does also look at pyproject.toml and will in some cases cause the wrong setup method to be used if we don't change the ordering.

Quoted 3 lines

Could you split this useful patch into smaller chunks, with a better justification for each chunk?

It's a bit tricky in this case due to all the side effects of migrating away from the monkeypatching which makes testing stuff in isolation hard, the existing code here is also broken in a bunch of random ways to to begin with.

My development process here was to just hack on stuff until things work properly. I'll try and clean some stuff up more and see if I can split out or minimize the reordering related changes but it's a bit tricky to test things incrementally.

Quoted 11 lines

Believe me, if you do this, patches like this will be merged, much, much, much faster.

Thanks a lot for your contribution!

Thomas
--
Thomas Petazzoni, co-owner and CEO, Bootlin Embedded Linux and Kernel engineering and training
https://bootlin.com

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot