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?
How to run pre-commit on current active file in Pycharm?
Asked Answered
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
Now let's set up the external tool itself
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
For a shortcut - Settings -> Keymap -> External Tools. Feel free to assign whatever shortcut you like
Thanks, that's a great answer! Worked like a charm :) It's a bit unfortunate that any external commands seem to show up simply as "External Tool" when configuring keymaps, regardless of their actual assigned name, but that's on JetBrains. –
Parthenon
Yeap, seems to be a regression in 2023.1. I've redirected the feedback to the responsible team. –
Agnusago
© 2022 - 2024 — McMap. All rights reserved.