git log
を実行して取り消しコミットを見つける
このステップでは、git log
を使用して取り消されたコミットを見つける方法を学びます。コミットを取り消すとは、以前のコミットで導入された変更を元に戻す新しいコミットを作成することを意味します。これは、間違いを犯した場合に、元のコミットの履歴を失うことなく簡単に取り消すために便利です。
まず、プロジェクトディレクトリにいることを確認しましょう。ターミナルを開き、my-time-machine
ディレクトリに移動します。
cd ~/project/my-time-machine
次に、いくつかのコミットを作成してプロジェクトの履歴をシミュレートしましょう。これには、後で取り消すコミットも含まれます。
最初のファイルを作成します。
echo "Initial content" > file1.txt
git add file1.txt
git commit -m "Add file1"
以下のような出力が表示されるはずです。
[master (root-commit) a1b2c3d] Add file1
1 file changed, 1 insertion(+)
create mode 100644 file1.txt
次に、さらにコンテンツを追加し、別のコミットを作成しましょう。
echo "Adding more content" >> file1.txt
git add file1.txt
git commit -m "Add more content to file1"
以下のような出力が表示されるはずです。
[master 4e5f6g7] Add more content to file1
1 file changed, 1 insertion(+)
次に、後で取り消すコミットを作成しましょう。
echo "This commit will be reverted" > file2.txt
git add file2.txt
git commit -m "Add file2 (will be reverted)"
以下のような出力が表示されるはずです。
[master 8h9i0j1] Add file2 (will be reverted)
1 file changed, 1 insertion(+)
create mode 100644 file2.txt
では、最後のコミットを取り消しましょう。git revert HEAD
を使用して、最新のコミットを取り消すことができます。
git revert HEAD --no-edit
--no-edit
フラグは、Git にエディタを開かずに自動的に取り消しコミットメッセージを作成するよう指示します。以下のような出力が表示されるはずです。
[master k2l3m4n] Revert "Add file2 (will be reverted)"
1 file changed, 1 deletion(-)
delete mode 100644 file2.txt
素晴らしい!これで、「Add file2 (will be reverted)」コミットの変更を取り消すコミットを作成しました。
次に、git log
を使用してコミット履歴を表示し、取り消しコミットを見つけましょう。
git log --oneline
以下のような出力が表示されるはずです。
k2l3m4n (HEAD -> master) Revert "Add file2 (will be reverted)"
8h9i0j1 Add file2 (will be reverted)
4e5f6g7 Add more content to file1
a1b2c3d Add file1
コミットメッセージ「Revert 'Add file2 (will be reverted)'」に注目してください。これは、このコミットが以前のコミットの取り消しであることを明確に示しています。--oneline
フラグを使用して git log
を実行すると、コミット履歴の概要をすばやく確認し、メッセージから取り消しコミットを識別することができます。