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

1

5

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?

Parthenon answered 20/4, 2023 at 8:43 Comment(0)
A
8

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

Agnusago answered 20/4, 2023 at 18:23 Comment(2)
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.