Skip to content
Advertisement

Install pre-commit on package install in setup.py file

I would like, when I install my python package with pip install ., that the command pre-commit install be run as well as everything else in the setup file.

Here is my setup.py file where I try to execute this:

from distutils.core import setup
from distutils.command.build import build as _build
from setuptools import find_packages, Command
import subprocess



class InstallPreCommit(Command):
    def run(self):
        subprocess.run(['pre-commit', 'install'])


# This class handles the pip install mechanism.
class build(_build):
    sub_commands = _build.sub_commands


setup(
    name="my-pkg",
    version="0.0.1",
    packages=find_packages(),
    install_requires=['pre-commit'],
    py_modules=["pkg"],
    cmdclass={
        'build': build,
        'install-pre-commit': InstallPreCommit
        }
)

However, when I run this, pre-commit install does not get run. I’m mostly taking inspiration from this SO post and this setup.py file in Apache Beam.

Does anyone have a sense of how to make sure I am invoking the setup of my package as well as calling my custom command, which runs the pre-commit install command?

Advertisement

Answer

you don’t actually want to do this, and the packaging system tries very hard to prevent you from doing this.

the main hurdles:

  • pip usually only runs setup.py once and then caches the result as a wheel
  • pip will sometimes build your package in a directory unrelated to your git repository
  • sometimes the library or tool won’t be available (ordering) at the time of installation

and last of all, something that does this subverts the expectations of the python community — that installation should not have side-effects outside of making the package available

ignoring all of that, you can trudge onwards and hack around the bits that attempt to prevent you

the rough stages for that are:

  1. prevent wheeling of your package — during the attempted wheeling make sure to exit, pip will usually fall back to just installing without wheeling
  2. attempt to find the original working directory (either $PWD or via assumptions of the running executable
  3. attempt to find the git repository you’re running in
  4. and lastly, make sure the tool is available

I’ve done all the dirty work for you, and I would strongly recommend not doing thishttps://github.com/pre-commit/pre-commit-installed


disclaimer, I created pre-commit, I also created pre-commit-installed but purely as a joke / proof of concept

Advertisement