LoginSignup
0
0

More than 1 year has passed since last update.

Gitで誤ったコミットをしないために

Last updated at Posted at 2023-04-28

概要

gitでコミットする際に、デバッグログや不要な情報などが入ってしまうことが多々ある。
プルリクで毎回それを指摘されると申し訳なくなるため、ヒューマンエラーはgitの機能で対処しようと思う。

pre-commitを使用する

gitには特定タイミングでスクリプトを実行するフックという機能がある。
今回はこれのpre-commitを使用する。
とりあえず、変更部分に"Debug"の文字列が入っていた場合はコミットさせないようにしてみる。

.git/hooks/pre-commitのファイルを次のように設定する

# "Debug"の文字列が入ったコミットを禁止
files=`git status|grep -e "modified" -e "new file"|sed "s/new file:\(.*\)/\1/g"|sed "s/modified:\(.*\)/\1/g"|cut -f 2`

for file in $files
do
   result=`git diff --cached -w --ignore-blank-lines --unified=0 $file | grep -e "Debug"`;

   if [ -n "$result" ]; then
       echo -e "${file} にデバッグ文が入っています。 \n $result}";
       exit 1
    fi
done

おまけ

ついでに、誤ってdevelopブランチにコミットしないようにもしてみる。

# develop branchでのcommitを禁止
BRANCH_NAME=`git symbolic-ref HEAD | sed -e 's:^refs/heads/::'`
if test $BRANCH_NAME = upstream -o $BRANCH_NAME = develop; then
    echo "We cannot commit on ${BRANCH_NAME} branch."
    exit 1
fi
0
0
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
0
0