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

标签 python github code-formatting automated-refactoring black-code-formatter

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

第一个选项

black /project_directory

第二个选项

black script1.py

black script2.py

等等

有没有办法在 git commit 之前自动化这个过程?

提前致谢

最佳答案

是的,您可以使用预提交 Hook 。如果您使用的是 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

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

关于Python Black Code Formatter - 在将项目提交到 Github 之前是否有任何方法可以应用自动黑色格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71180810/

相关文章:

c++ - 你如何缩进预处理器语句?

python - 如何从函数返回局部变量([object])?

git - 如何git添加整个文件夹

git - 将 Angular 2 应用程序部署到 Azure

json - 为什么我的 GitHub 存储库中的代码是红色的以及如何禁用它?

java - 自定义 Eclipse 格式

python - 删除不包含指定整数值的行(Pandas)

python - TensorFlow:使用不同的损失函数恢复训练

python - 有人能告诉我我的 WIP Python 刽子手游戏出了什么问题吗?

html - 有没有人知道在 html 中对齐脚本标签?因为我必须将脚本标签一个一个地对齐