VSCode integrated source control and pre-commit

17.1k views Asked by At

When using https://pre-commit.com with VSCode hooks that depend on packages installed in a Python venv. In pre-commit on can specify to use "system" as environment. This works great from the terminal with desired venv active.

However using the integrated source control it seems that global interpeter is accessed and thus required packages are not available.

Is there a workaround here? As for now I specify the entrypoint "path/to/bin/python -m package" in pre-commit config. However I do think that also the integrated source control should respect at least the selected interpeter.

Any thoughts?

2

There are 2 answers

3
darda On

VSCode seems to choose willy-nilly what it respects and what it doesn't. I have the same situation - committing on the integrated terminal works fine; doing it from the Source Control sidebar gives me a "Python can't be found" message (which only appeared after installing a pre-commit hook).

My guess is you'll have to, by trial and error, install pre-commit in every Python installation in your system until you find which one the sidebar is invoking.

0
Mr_Robot On

TLDR: I have found a solution, but it requires some manual work initially.

At first I also tried to use pre-commit, but came to see the same problem as some of my colleagues reporting about VS Code not being able to execute it correctly when staging and committing over the GUI. (I always use my terminal).


So I wrote my own quality-gate.sh script, that:

  1. runs source venv/bin/activate
  2. and only afterwards runs the script previously defined under pre-commit-config.yaml

I then added the git hook manually inside of .git/hooks folder, by:

  1. Creating the pre-commit hook mv pre-commit.sample pre-commit
  2. Opening the script: vim pre-commit
  3. Getting rid of all the contents inside the previous sample file
  4. Adding the script I'd like to run:
#!/bin/sh
sh ./quality-gate.sh
  1. Saving the file: ESC + :wq
  2. Done!

✅ Now the script is run whenever I have staged (aka added) some changes and run "git commit ...".

This also works for the GUI approach in VS Code - the "Commit" loading bar will be running as long as your script runs - so you might have to be patient, depending on what exactly your pre-commit script does.

I also included an exit 1 command inside of my quality-gate.sh if any of the checks failed, so that the commit will be aborted.



Additional info:

As we are using a monorepo, I included some logic with changed_files=$(git diff --name-only --cached) in order to get a list of changed_project folders, in order to only run pre-commit hooks if there is a staged file inside of the respective folder - aka there are any changes - else the checks will be skipped.

As this is off topic, I will not include it here - but feel free to comment, if further instructions are needed, or if you are interested in this topic.