概要
git を利用していて commit を積み重ねていった時に、昔のcommitのファイルが取得したくなる事がある。
revert したかったり、昔のリビジョンを元に、コードを修正したくなった時とか。
そんなとき、いつも手順を忘れるのでメモしておく。
手順
前提
- こういうファイルがあるとする。
$ cat test.txt
v3
- コミット履歴はこんな感じ
- ファイルの中身は コミットごとに v1,v2,v3 という感じで変更していった。
$ git log
commit aa995e5c736b45d724ebbc60fbef4f464dacc43f
Author: user <user@example.com>
Date: Wed Aug 31 12:04:40 2016 +0900
v3 commit
commit a7113d26f7f6d8ac129a14df0fb00b9d45d5aa17
Author: user <user@example.com>
Date: Wed Aug 31 12:04:26 2016 +0900
v2 commit
commit 1e733cf18d5880fde3a968e74e7e6216027dc370
Author: user <user@example.com>
Date: Wed Aug 31 12:04:15 2016 +0900
v1 commit
取得したい commit に移動
-
v1 commit
の内容を取得したいのでハッシュ値1e733cf18d5880fde3a968e74e7e6216027dc370
へ移動
git checkout 1e733cf18d5880fde3a968e74e7e6216027dc370
Note: checking out '1e733cf18d5880fde3a968e74e7e6216027dc370'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
HEAD is now at 1e733cf... v1 commit
- v1 commit の内容が取得できた
$ cat text.txt
v1
最新のハッシュ値 へ戻る
- 今回は
aa995e5c736b45d724ebbc60fbef4f464dacc43f
$ git reset aa995e5c736b45d724ebbc60fbef4f464dacc43f
Unstaged changes after reset:
M text.txt
- ファイルの内容はそのまま
$ cat text.txt
v1
- git diff で差分が見える
$ git diff
diff --git a/text.txt b/text.txt
index 29ef827..626799f 100644
--- a/text.txt
+++ b/text.txt
@@ -1 +1 @@
-v3
+v1
- git branch で master を checkout
- no branch になっているため
$ git branch
* (no branch)
master
$ git checkout master
M text.txt
Switched to branch 'master'
完了
- 好きなように編集してコミットができる状態になったので、ソースを直して commit する。