Python Black Code Formatter - 在将项目提交到 Github 之前有什么方法可以应用自动黑色格式化

5 python code-formatting github automated-refactoring black-code-formatter

最近,我开始在我的项目中使用黑色代码格式化程序,有时很难跟踪我是否格式化了所有更改的文件。假设我的项目包含 20 个不同的脚本(.py 文件),并且我对其中最后 5 个脚本进行了更改,就像我在提交之前通常所做的那样。

第一个选项

black /project_directory
Run Code Online (Sandbox Code Playgroud)

第二个选项

black script1.py

black script2.py
Run Code Online (Sandbox Code Playgroud)

等等。

有没有办法在 git commit 之前自动执行此过程?

预先非常感谢

nne*_*neo 10

是的,您可以使用预提交挂钩。如果您使用的是 Linux 或 macOS,或者带有 Git Bash 的 Windows,请将以下内容放入名为 的文件中.git/hooks/pre-commit

#!/bin/bash

# Paths are relative to the root of the git repository
black .
black script1.py
black script2.py
Run Code Online (Sandbox Code Playgroud)

用于chmod +x .git/hooks/pre-commit使其可运行。然后,每次执行 a 时commit,挂钩都会首先运行并格式化所有代码。您可以在Git Hooks 文档中阅读有关钩子的更多信息。