强制 git 拒绝特定内容的提交

3 git

是否可以在我的代码中添加注释,以便 GIT 拒绝提交它?

原因是有时我正在研究两种不同的策略来解决问题,例如两个不同的类。那么如果可以在类中的某个位置添加注释, // DONT COMMIT这样我就不会意外提交两个并行类,那就太好了。

axi*_*iac 5

一个简单的预提交钩子可以完成这项工作:

#!/usr/bin/env bash


# The text that refuses the commit
# Change it to match your needs; keep it enclosed in single quotes
MARKER='// DONT COMMIT'


# Verify the staged files for the presence of the marker text
if git diff --cached --name-only | xargs grep -q "$MARKER"; then
  echo 'Cannot commit because the "no-commit" marker has been found in one of the staged files.' 1>&2
  # Refuse to commit
  exit 1
fi
Run Code Online (Sandbox Code Playgroud)

将其放入项目中的文件中.git/hooks/pre-commit并使该文件可执行 ( chmod +x .git/hooks/pre-commit)。

它只是一个存根,可能无法在所有情况下按预期工作。扩展它以满足您的需求。

-n您可以通过在命令行中传递选项(或--no-verify)来告诉 Git 跳过挂钩git commit