LoginSignup
2
1

複数のコミットをまとめる方法

Posted at

0. まとめ

  1. rebase -i でコミットをまとめる(例:git rebase -i HEAD~2
  2. テキストエディタが開くので、集約先の pick はそのままにして、集約によって消したいコミットの picks または squash に変更する
    • vim の場合、:wq で保存して終了
  3. 再度テキストエディタが開くので、残したいほうのコミットのコメントを編集。
    • vim の場合、:wq で保存して終了
  4. git push -f origin (ブランチ名) でプッシュ

1. コミットをまとめるときに注意すること

  • 共同開発のリモートブランチに安易に git push -f するのは危険なので注意すること
    • push -f はリモートリポジトリに既に公開されているコミット履歴を改変してしまうので、他のメンバがpushしたコミットを上書きしたり削除してしまう可能性があります。

2. 詳細手順

rebase -i でコミット2つをまとめたいとする。

ひとまず git rebase -i
-i (--interactive)で過去のコミットを編集できます)

$ git rebase -i HEAD~~

または

$ git rebase -i HEAD~2

するとテキストエディタが開き、HEADから2つ分のコミットが表示される。

pick b71985f commit A
pick 32eea59 commit B

# Rebase 7a54171..32eea59 onto 7a54171 (2 commands)
(以下略)

集約先のコミット(残したいコミット)の pick はそのままにして、集約によって消したいコミットの picks または squash に変更する:

pick b71985f commit A
s 32eea59 commit B

# Rebase 7a54171..32eea59 onto 7a54171 (2 commands)
(以下略)

:wq で保存して終了。

すると、再度テキストエディタが開:

# This is a combination of 2 commits.
# This is the 1st commit message:

commit A comment

# This is the commit message #2:

commit B comment
(以下略)

残したいほうのコミットのコメントを好きなように編集する:

# This is a combination of 2 commits.
# This is the 1st commit message:

commit A comment + commit B comment

# This is the commit message #2:

# ここを消した
(以下略)

:wq で保存して終了。

最後にプッシュ:

git push -f origin (ブランチ名)

以上。

参考になる記事

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1