簡體   English   中英

Git預提交掛鈎:防止更改特定文件的提交

[英]Git pre-commit hook: Prevent commits that change particular files

我的項目下有幾個.json文件,其中包含多個鍵。 這些密鑰不得受版本控制。 為了防止在持續集成中構建失敗,我在項目中將這些實際密鑰替換為偽密鑰。

但是,開發人員需要先在筆記本電腦上復制/粘貼這些文件,然后才能測試該應用程序。

現在,問題是開發人員可能會忘記並將它們錯誤地提交到git中。 我想運行一個pre-commit腳本,該腳本檢查修改后的文件,如果添加了其中一個,則提交失敗。

有什么辦法可以做到嗎?

您可以在預提交掛鈎中執行以下操作:

FILES_PATTERN='<regexp_to_match_file_names>'
if git diff --cached --name-only | grep -qE $FILES_PATTERN; then
    exit 1;
else
    exit 0;
fi

該想法基於以下參考:

請注意,我沒有對此進行測試。

使用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鈎子拒絕任何會修改受保護文件的推送。

#!/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>'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM