LoginSignup
37
38

More than 5 years have passed since last update.

【git】 authorを間違えてcommitした上で、pushしてしまった時の対処法と再発防止策

Last updated at Posted at 2016-09-27

gitのuser.name/user.emailの設定を誤ってpushしてしまうと、GitHub上で空のアイコンになったり、アカウントが紐づけされて、別の用途に使っているアカウントがバレてしまう。
その対処法と再発防止策。

やらかしたコミットを修正する

範囲を選択_045.jpg

「commit 002」を修正したい。

$ git rebase -i 【間違えたコミットのひとつ前のコミット】

ここでは acedb...を指定

参考: rebase -i でコミットを修正する

sample : emacs – Konsole_046.jpg

修正したいコミットの「pick」を「edit」に修正して保存。

範囲を選択_047.jpg

こんな感じのメッセージがでてくる。
コミットを修正できる状態になったので、authorを上書きしてコミットする。

$ git commit --amend --author="example <example@example.com>"

rebase から復帰する

$ git rebase --continue

範囲を選択_048.jpg

無事修正された。
あとはpushすればおk

$ git push -f

forceする覚悟をキメるんだ

再発防止策をとる

gitにhookの概念があることを知らなかった(´ω`;)
というわけでパクらせてもらおう

参考: https://github.com/aiya000/dotfiles/blob/master/.git_templates/hooks/pre-commit

.git/hook/pre-commit

#!/bin/sh
if [ -z "`git config --local user.name`" ] ; then
  echo '名無し(´・ω・`)'
  exit 1
fi

if [ -z "`git config --local user.email`" ] ; then
  echo 'メールアドレスがない(T_T)'
  exit 1
fi

※ 原因が分かりやすいメッセージで置き換えましょう

実行権限の付与も忘れずに。

$ chmod u+x .git/hook/pre-commit

範囲を選択_049.jpg

上手くいった。

とはいえ、いちいちpre-commitのスクリプトを配置するのも面倒。
git initの際に配置されるようにする。

テンプレート用のディレクトリを作成してスクリプトを配置

$ mkdir -p ~/.git_template/hook
$ touch ~/.git_template/hook/pre-commit

(上記のスクリプトを仕込む)

$ chmod u+x ~/.git_template/hook/pre-commit

gitにテンプレートとして認識させる

$ git config --global init.templatedir

範囲を選択_050.jpg

おk
これでヒヤヒヤすることも無くなるだろう。たぶん。

37
38
2

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
37
38