sherlock
sherlock

Reputation: 2807

How to merge a commit with the next commit in git interactive rebase?

git rebase -i allows one to merge a commit with the previous one through squash or fixup. Both the options require at least one commit to be pick-ed. What about the case when one wants to use the very first commit but discard its commit message? In other words, if I want the very first commit to be merge with the subsequent ones, what should I do?

Upvotes: 2

Views: 1129

Answers (2)

Sajib Khan
Sajib Khan

Reputation: 24184

  • See the branch name (say, branch-1)
    $ git branch
  • See the first-commit-hash and save it others (say, first-commit)
    $ git log
  • Check out to first-commit
    $ git checkout first-commit
  • Change the commit message
    $ git commit --amend -am 'new-commit-msg' --allow-empty
  • Now save the new commit hash (say, new-commmit)
    $ git log
  • Back to your 'branch-1' branch git checkout branch-1
  • Replace first-commit by new-commit
    $ git replace first-commit new-commit
  • Rewrite all futures commits based on the replacement
    $ git filter-branch -- --all
  • Push your change by force
    git push -f origin HEAD

Upvotes: 0

torek
torek

Reputation: 489223

You just need the --root flag (available since Git 1.7.12, i.e., to everyone except certain unnamed never-updated cough*Centos*cough Linux distributions).

Consider that the result of squashing A and B is (sort of—commits don't quite obey this simple algebra, but it works for our case) just A + B. Therefore, since B + A = A + B, it does not matter whether you squash commit #1 into commit #2, or commit #2 into commit #1. Of course this does not count the squashed-together commit's message, so let's take a closer look at that.

Suppose you have run git rebase -i --root so as to be able to rebase everything including the root commit. You now have:

pick cb57fdd initial commit
pick 478acbd second commit

Change the second one to squash and write the file and exit the editor. Git squashes the two commits together and brings up your editor again, and you see:

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

initial commit

# This is the commit message #2:

second commit

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Sat Nov 19 14:44:07 2016 -0800
#
# interactive rebase in progress; onto 45bc10c
# Last commands done (2 commands done):
#    pick cb57fdd initial commit
#    squash 478acbd second commit

(the precise details depend on your Git version, as well of course as the commit contents).

Since you are in your favorite editor, it is easy to construct whatever new commit message you want. For instance, you can just delete the entire first commit's message, if that's what you want. Do that, write the file, and exit the editor, and you are all set.

Upvotes: 2

Related Questions