Python Black Code Formatter - Is there any way to apply automatic black formatting before commiting project to Github
Asked Answered
M

1

8

Recently I started to use Black code formatter for my projects and sometimes it can be hard to track did I formatted all my changed files or not. Let's assume that my project contains 20 different scripts (.py files) and I made changes on last 5 of them what I do normally before commit.

First option

black /project_directory

Second option

black script1.py

black script2.py

and etc.

Is there a way to automate this process before git commit or not ?

Thanks a lot in advance

Mullite answered 18/2, 2022 at 23:2 Comment(0)
N
14

Yes, you can use a pre-commit hook. If you're using Linux or macOS, or Windows with Git Bash, put the following in a file named .git/hooks/pre-commit:

#!/bin/bash

# Paths are relative to the root of the git repository
black .
black script1.py
black script2.py

Use chmod +x .git/hooks/pre-commit to make this runnable. Then, every time you do a commit, the hook will run first and format all your code. You can read more about hooks on the Git Hooks documentation.

Nagoya answered 18/2, 2022 at 23:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.