Search code examples
pycharmpre-commitpre-commit.com

How to run pre-commit on current active file in Pycharm?


I'm looking for a way to run my pre-commit hooks on the currently active file in Pycharm without committing the file. I do not want to artificially add changes to the file and then commit it. The intent is to clean my code while writing it, without the need to commit. Ideally, this would happen via a hotkey. How would I do this?


Solution

  • To run a pre-commit over a single file (e.g., main.py) we need to use the following command

    pre-commit run --files main.py
    

    Let's set up an "external tool" in PyCharm. Go to Setting -> Tools -> External Tools

    enter image description here

    Now let's set up the external tool itself

    enter image description here

    Important points

    • One should provide a path to the pre-commit executable (which pre-commit in the terminal on Unix should help)
    • Use run --files $FileName$ as arguments, $FileName$ is IDE macros, it will be auto-replaced with the filename of the currently open file in the editor

    Now let's experiment - open some Python file, make some changes so you can see the pre-commit result in action, and trigger the external tools with Tools -> External Tools -> pre-commit

    enter image description here

    For a shortcut - Settings -> Keymap -> External Tools. Feel free to assign whatever shortcut you like

    enter image description here