* git reset(git add/commitの取り消し) [#j2afffca]

** 前提知識 [#de304cd4]
:ワーキングツリー|現在の状態
:インデックス|ワーキングツリーからgit addした状態
:HEAD|最後にコミットした状態
:HEAD^|HEADの1つ前のコミットした状態

** git resetのオプションとその機能 [#b3ef5d07]
*** soft [#v9b8df84]
 git reset --soft HEAD^
HEADの位置をHEAD^へ変更する。インデックスとワーキングツリーに影響はない。

*** mixed(またはオプションなし) [#xb2cea95]
 git reset --mixed HEAD
 git reset HEAD
HEADの位置とインデックスをHEADへ変更する。ワーキングツリーに影響はない。

*** hard [#d1385b4a]
 git reset --hard HEAD^
HEADの位置とインデックスとワーキングツリーをHEAD^へ変更する。

** 使用例 [#yc5b5988]
*** ステージングを取り消す [#l5b26aec]
 vi test.txt               # (1) test.txtを修正する。
 git add test.txt          # (2) test.txtをステージングする。
 git reset HEAD test.txt   # (3) 上のステージングを取り消す。
                           #     test.txtは修正されたまま。
*** コミットログを書き直したい/必要な修正ファイルをaddしてなかった(不要な修正ファイルをaddしてた) [#t6c54882]
 vi test.txt               # (1) test.txtを修正する。
 git add test.txt          # (2) test.txtをステージングする。
 git commit -am 'fixed'    # (3) コミットする。
 git reset --soft HEAD^    # (4) 上のコミットを取り消す。
 vi test2.txt              # (5) test2.txtを修正する。
 git add test2.txt         # (6) test2.txtをステージングする。
 git commit -am 'fixed 2 files' # (7) コミットし直す。
                                #     test.txt、test2,txt共に修正がコミットされた。
 
*** (コミットしてすぐの場合の)コミットを取り消す [#ve9b0731]
 vi test.txt               # (1) test.txtを修正する。
 git add test.txt          # (2) test.txtをステージングする。
 git commit -am 'fixed'    # (3) コミットする。     
 git reset --hard HEAD^    # (4) 上のコミットを取り消す。
                           #     コミットログ'fixed'は消え、test.txtは修正前の状態に戻っている。

*** (コミットして時間が経っていて、すでに他者が修正を行っている可能性が高い場合の)コミットを取り消す [#g90f15df]
 自分:
 git commit -am 'XXX'
 git push

 他者:
 git pull
 git commit -am 'XXX'

 自分:
 git revert HEAD
 git push

 (他者)
 git pull

*** git resetしたが、さっき取り消したコミットの内容を見たい [#x2a5a1e3]
 git reset --soft HEAD^
 git show ORIG_HEAD
他にも
 vi test.txt                 # (1) test.txtを修正する。
 git add test.txt            # (2) これをステージングして、
 git commit -am 'fixed'      # (3) コミットする。
 git reset --hard HEAD^      # (4) このコミットを取り消す。
 vi test.txt                 # (5) 再度、test.txtを修正する。
 git diff ORIG_HEAD test.txt # (6) (1)の修正とのdiffを見る。

*** 間違ってgit resetしてしまったので、元に戻したい [#uc2ec140]
[[Git/git reflog (git resetを取り消す)]]を参照。


** 参考 [#t880fec6]
- http://d.hatena.ne.jp/murank/20110327/1301224770
- http://transitive.info/article/git/command/reset/
- http://d.hatena.ne.jp/zariganitosh/20080905/1220621182

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS