LoginSignup
34
27

More than 5 years have passed since last update.

gitで特定のファイルの更新を禁止する

Posted at

プロジェクトによっては、そう安々と変更してほしくないファイルが有ったりします。
そこで、特定のファイルの変更をコミット出来なくするGitフックの紹介です。

例えば、.htaccesslibディレクトリ配下の全てのファイルの変更を禁止するには以下の様なpre-commitフックを作成します。

.git/hooks/pre-commit

#!/bin/sh

unchangeable_files=(
  ^\\.htaccess$
  ^lib/.*
)

containsElement () {
  local e
  for e in "${@:2}"; do [[ "$1" =~ $e ]] && return 0; done
  return 1
}

for FILE in `git diff --cached --name-status $against -- | cut -c3-`; do
  if containsElement $FILE "${unchangeable_files[@]}"; then
    echo "$FILE"
    CHANGE_DETECTED=1
  fi
done

if [ "$CHANGE_DETECTED" ]; then
  echo "Failed to commit because of modification of files above."
  exit 1
fi

変更禁止ファイルを変更してコミットしようとするとエラーメッセージが表示され、コミットが失敗します。

34
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
27