仅在特定分支上运行 pre-commit。

15
我正在寻找在.pre-commit-config.yaml文件中的配置,以便排除某些分支上的 pre-commit 运行,或者仅在某些分支上运行它。我不知道这个功能是否已经实现,还是我在文档中漏掉了它。
谢谢!

1
.pre-commit-config.yaml 不仅仅是 git 的一部分,它必须是额外工具的一部分:gitlabjenkinsredmine 等等。你能指定是哪一个吗? - LeGEC
1
稍后的推送将会上传到GitLab,但据我所知.pre-commit-config.yaml只在本地工作(当我添加或删除钩子时确实如此)。@LasseV.Karlsen 这就是我的问题所涉及的内容。我希望在某些分支上不运行pre-commit。这个配置在overcommit中是可用的,但我在pre-commit中找不到它。 - Alex Martínez Ascensión
7
如果我在dev或其他的分支上,可能会有一些代码审查和其他问题,但我并不想在那个时候去纠正它们,因为我只是想快速提交代码。然而,在发布、热修复或主分支上,我希望这些问题能被解决。 - Alex Martínez Ascensión
1
是的,完全正确。有时我只想保存正在进行的代码,如果它是一个WIP分支,那就可以了。但是这个代码不应该被推到主分支。 - Alexey Grigorev
你正在寻找SKIP。但说实话,这听起来有点懒。我从未理解那些“我想写烂代码直到PR时间”的人。 - anthony sottile
显示剩余3条评论
3个回答

1

Git 钩子只是被执行的 shell 脚本。

所以在脚本中,你可以做类似于这样的事情:

if [ $(git branch --no-color | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/') = "main" ]; then
  # Do checks for main here
fi

1
你可以通过在 git branch 命令中添加 --show-current 参数来避免使用 sed - Ginger Jesus

0

有几种不同的方法可以实现这个目标:

选项1:从特定分支中删除配置

$ git switch -c no-pre-commit
Switched to a new branch 'no-pre-commit'
$ git rm .pre-commit-config.yaml
rm '.pre-commit-config.yaml'
$ git commit -m 'Remove pre-commit config'
No .pre-commit-config.yaml file was found
- To temporarily silence this, run `PRE_COMMIT_ALLOW_NO_CONFIG=1 git ...`
- To permanently silence this, install pre-commit with the --allow-missing-config option
$ pre-commit install --allow-missing-config
pre-commit installed at .git/hooks/pre-commit
$ git commit -m 'Remove pre-commit config'
`.pre-commit-config.yaml` config file not found. Skipping `pre-commit`.
[no-pre-commit 948c59a] Remove pre-commit config
 1 file changed, 159 deletions(-)
 delete mode 100644 .pre-commit-config.yaml

如果您已经为不同的阶段安装了pre-commit,则还必须运行

pre-commit install -t <stage> --allow-missing-config

选项二:为特定分支提供不执行任何操作的配置

从技术上讲,使得预提交配置有效的唯一必要条件是repos列表存在,而该列表可以为空。如果您将一个提交添加到更改其.pre-commit-config.yaml的某些分支中,则会变成这样:

repos: []

然后,当您提交到这些分支时,pre-commit将不会执行任何操作。


-1

根据您的使用情况,您可以使用--no-verify标志来绕过钩子,例如:

git commit --no-verify -m "WIP Commit message"

或者

git commit -n -m "WIP Commit message"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接