-2

let say i have a commit 1 which is already present in branch A. I have a new commit 2 in branch B, i want to move this commit 2 to branch A and merge with commit 1.

Inigo
  • 12,186
  • 5
  • 41
  • 70
  • 1
    Did you try using `git merge` with the `--ff-only` or `--no-ff` flags? Having the A branch checked out, it will merge the second commit from the B branch only (since the first commit is shared for two branches, that however contradicts with the title of your question). – terrorrussia-keeps-killing Jan 12 '22 at 06:08
  • @fluffy That only works if branch B's only difference with branch A is commit 2, which is a big assumption. Sai, by "merge" do you actually mean "squash" (combine the changes from the two commits into a single commit)? – Inigo Jan 12 '22 at 19:41

1 Answers1

0

My answer assumes that by "merge", you actually meant "squash", given the way you used it in your question.

⚠️ Doing the following will rewrite history.

(replace refs below with actual commit hashes and branch names)

to move commit-2 to branch branch-A:

git rebase --onto branch-A commit-2^ commit-2

to squash commit-2 into commit-1:

  1. Use interactive rebase to redo the commit history beginning with commit-1

    git rebase -i commit-1^ branch-A
    
  2. In the interactive rebase commit list, move the line for commit-2 so that it immediately follows commit-1.

  3. On the line for commit-2, replace the word pick with either squash or fixup. From the git help rebase:

    If you want to fold two or more commits into one, replace the command "pick" for the second and subsequent commits with "squash" or "fixup". If the commits had different authors, the folded commit will be attributed to the author of the first commit. The suggested commit message for the folded commit is the concatenation of the first commit’s message with those identified by "squash" commands, omitting the messages of commits identified by "fixup" commands, unless "fixup -c" is used. In that case the suggested commit message is only the message of the "fixup -c" commit, and an editor is opened allowing you to edit the message. The contents (patch) of the "fixup -c" commit are still incorporated into the folded commit. If there is more than one "fixup -c" commit, the message from the final one is used. You can also use "fixup -C" to get the same behavior as "fixup -c" except without opening an editor.

  4. Save and close the rebase commit list. git rebase will now apply the commits in the order you saw in the list. You will have to deal with any merge conflicts.

git rebase -i is one of the most powerful and useful commands in git. Learn it!

Inigo
  • 12,186
  • 5
  • 41
  • 70