はじめに
今回はGitのコマンドを実際に動かして、バージョンの確認や変更について理解を深めたいと思います。参考図書はこちらの動かして学ぶ!Git入門を使用しました。
コマンド
37. git revert
このコマンドは指定したコミットを打ち消すコミットを新たに作成します。実行するとエディタが開かれ、メッセージが表示されます。ここでコミットメッセージを書くことができます。git resetでも同様の結果が得られますが、コミット自体が無くなってしまいます。そのため、業務に支障を及ぼすがある場合はgit revertを使用しましょう。
$ git revert HEAD
[main a6633a4] Revert "commit Very Nice !"
1 file changed, 1 deletion(-)
補足:
ここではHEADが指すコミット以外を打ち消す場合について説明します。例えば3つ前のコミットを打ち消したい場合について考えます。
まずは実行してみましょう。
$ git revert @~3
Auto-merging hello.txt
CONFLICT (content): Merge conflict in hello.txt
error: could not revert 8ba08a1... Yeah !
hint: After resolving the conflicts, mark them with
hint: "git add/rm <pathspec>", then run
hint: "git revert --continue".
hint: You can instead skip this commit with "git revert --skip".
hint: To abort and get back to the state before "git revert",
hint: run "git revert --abort".
このように指定したコミット以降でも、変更を加えているのでコンフリクトが発生してしまいます。このような場合はマージにおけるコンフリクト同様、該当する部分を修正して、ステージングし、git revert --continueを行うことで解消できます。
#hello.txtからYeah !という文章を削除
$ git add hello.txt
$ git revert --continue
[main 21927ae] Revert "Yeah !"
1 file changed, 1 insertion(+), 2 deletions(-)
$ git log --all --oneline
21927ae (HEAD -> main) Revert "Yeah !" #「削除した」というコミットが追加されている
a6633a4 Revert "commit Very Nice !"
36c7012 commit Very Nice !
3d2ad50 (practice2) commit prac2.txt
b79fc14 (tag: v1.0) resolve conflict
1ca01f9 Hoo.txt
8ba08a1 Yeah !
c691967 commit merge.txt
ba022a9 commit prac.txt
0e420a2 Have a nice day !
aa36595 Enjoy !
714ed15 check status
e6e9a3b first commit
無事、コンフリクトが解消されました。
コンフリクトを解消せず、コミットの削除自体を取りやめたい場合はgit revert --abortを使用します。
38. git cherry-pick
このコマンドは指定したコミットやブランチの変更を、他のコミットやブランチにマージすることなく、適用するコマンドです。
それでは、practice2ブランチにmainブランチのHEADの変更を適用してみましょう。
$ git checkout practice2
Switched to branch 'practice2'
$ git cherry-pick main
[practice2 29c6ca1] Revert "Yeah !"
Date: Sat Nov 4 11:26:33 2023 +0900
1 file changed, 1 insertion(+), 2 deletions(-)
$ git log --all --oneline
29c6ca1 (HEAD -> practice2) Revert "Yeah !"
21927ae (main) Revert "Yeah !"
a6633a4 Revert "commit Very Nice !"
36c7012 commit Very Nice !
3d2ad50 commit prac2.txt
b79fc14 (tag: v1.0) resolve conflict
1ca01f9 Hoo.txt
8ba08a1 Yeah !
c691967 commit merge.txt
ba022a9 commit prac.txt
0e420a2 Have a nice day !
aa36595 Enjoy !
714ed15 check status
e6e9a3b first commit
無事に適用できましたね。このコマンドを使用する状況としては、エラー修正用のブランチの変更を、開発用のブランチに適用する際など、どちらもマージせずに変更だけを適用したい場合などに使用されます。
39. git rebase
このコマンドはあるコミットの先のブランチを、別のコミットの先に移すコマンドになります。この処理は、連続でcherry-pickを行っています。そのため、コンフリクトが発生する可能性があります。git revbertコマンドと同様にコンフリクトを解消して--continueを行うか、--abortで取りやめるかを決めます。
まとめ
今回の記事では、履歴の操作ついて学習しました。今回でGitのコマンドの学習は一旦終了としたいと思います。もしGitについて他に気になるコマンドや、処理の仕方があれば記事にしたいと思います。
前回:【勉強用】Gitのコマンドを実際に動かしてみた(⑤リモートリポジトリ編)
