Git 预提交 Hook : Prevent commits that change particular files

标签 git githooks

我的项目下有一些 .json 文件,其中包含几个键。这些 key 不得受版本控制。我在项目中用假 key 替换了这些实际 key ,以防止构建在持续集成时失败。

但是,开发人员需要在他们的笔记本电脑上复制/粘贴这些文件,然后才能测试应用程序。

现在,问题是开发人员可能会忘记并错误地将它们提交到 git 中。我想运行 pre-commit检查修改文件并在添加其中一个文件时使提交失败的脚本。

有什么办法可以做到吗?

最佳答案

使用 pre-commit 在开发人员方面防止它发生钩。请注意 git commit --no-verify将绕过此安全机制。

下面的代码完全阻止对文件的任何更改 dir/key1.jsonkey2.json .

#!/bin/sh

# full paths from the repo root separated by newlines
MUST_NOT_CHANGE='dir/key1.json
key2.json'

if git rev-parse --verify HEAD >/dev/null 2>&1
then
  against=HEAD
else
  # Initial commit: diff against an empty tree object
  against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

exec 1>&2

if git diff --cached --name-only $against |
   grep --quiet --line-regexp --fixed-strings "$MUST_NOT_CHANGE"
then
  echo Commit would modify one or more files that must not change.
  exit 1
else
  exit 0
fi
pre-receive下面的钩子(Hook)必须安装在您的中央存储库上,拒绝任何会修改 protected 文件的推送。

#!/bin/sh

# full paths from the repo root separated by newlines
MUST_NOT_CHANGE='dir/key1.json
key2.json'

z40=0000000000000000000000000000000000000000

while read old_value new_value ref_name
do
  if [ "$old_value" = $z40 ]; then
    # New branch: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
  else
    against=$old_value
  fi

  if git diff --name-only $against..$new_value |
     grep --quiet --line-regexp --fixed-strings "$MUST_NOT_CHANGE"
  then
    echo "$ref_name" may commit key, rejected ... >&2
    exit 1
  fi
done

在行动:
$ git push origin master
Counting objects: 10, done.
Delta compression using up to 40 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (10/10), 820 bytes | 410.00 KiB/s, done.
Total 10 (delta 1), reused 0 (delta 0)
remote: refs/heads/master may commit key, rejected ...
To '<URL>'
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to '<URL>'

关于Git 预提交 Hook : Prevent commits that change particular files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57961129/

相关文章:

git - 您如何处理 AWS CodePipelines 的配置文件?

git - 如何使用 VS Code 将新项目添加到 Github

git - 如何使用 git 和 git hooks 同步数据库以及如果它不起作用如何调试

git - 自定义 commitlint header 格式

在多个服务器上进行 Git pull

ruby - 推送预提交 git 钩子(Hook) (Rubocop)

git - 在两个 Git 存储库之间同步单个文件

git - git中强制推送和普通推送有什么区别

git - 如何忽略已提交给 Git 的文件的任何更改

git - 在 git 提交期间清理输出和格式化 Jupyter 笔记本文件