過去のコミットに戻る方法

はじめに

git check out <コミットID>で、過去時点のコミットに戻ることができる。

テストリポジトリ

以下のテストリポジトリを作成した。

ki-hi-ro/git

2回変更を加える

コミット履歴を作るために、2回変更を加えていこう。

まずは、通常のFizzBuzz。

fizz-buzz.py

for i in range(1, 31):
  if i % 3 == 0 and i % 5 == 0:
    print('FizzBuzz')
  elif i % 3 == 0:
    print('Fizz')
  elif i % 5 == 0:
    print('Buzz')
  else:
    print(i)

続いて、効率的な書き方を行なったFizzBuzz。

fizz-buzz.py

for i in range(1, 31):
  output = ''
  if i % 3 == 0:
    output += 'Fizz'
  if i % 5 == 0:
    output += 'Buzz'
  print(output or i)

最初のFizzBuzzに戻る

以下の「create initial fizzbuzz」に戻りたいとしよう。

右の方にコミットIDが書かれているので、これをコピーする。

VSCodeで見た方が分かりやすいかもしれない。

右クリックで、コミットIDのコピーが選択できる。

現在は、mainブランチの最新にいる。

git checkout <コミットID>で、戻りたい時点のコミット履歴に戻ることができた。

hiroki@shibatahiroshitakanoiMac git % git checkout ba07a2077fdb1320fb7db2ed759688233b5b121f
Note: switching to 'ba07a2077fdb1320fb7db2ed759688233b5b121f'.

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 switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at ba07a20 create initial fizzbuzz

FizzBuzzのロジックが書いてある「fizz-buzz.py」は、以下のように変化した。

create initial fizzbuzz
change fizzbuzz

git checkout <create initial fizzbuzzのコミットID>で、この時点に戻すことができた。

hiroki@shibatahiroshitakanoiMac git % git checkout ba07a2077fdb1320fb7db2ed759688233b5b121f

逆に今の状態に戻したい時

git checkout <ブランチ名>で、指定したブランチの最新バージョンに戻すことができる。

git checkout mainで、最新に戻る。

hiroki@shibatahiroshitakanoiMac git % git checkout main

実務での学び

チームメンバーに昨日共有したコミット内容でテストをしてもらった。

バグが見つかって、それを修正しようとしたが、ブランチの変更は進んでいた。

そのため、昨日共有したコミットに戻って、エラーの再現と修正を行なった。

しかし、その修正をどうやって共有するのか悩んだ。

最終的に、fix-〇〇というブランチを切って、そこで修正作業を行って共有した。

その部分を次回の記事では行っていこう。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です