Push a commit in two branches with Git
Short answer
You can apply already existing commit to another branch using cherry-pick
command, and then push both branches using git push origin branchA branchB
.
Why pushing a commit in two branches might be useful
Assume you have a repository with this structure:
A--B--C--D ← master ← HEAD
\--E ← v1-release
After some development (commits A
, B
, C
) project was released and v1-release
branch was created (so that v1 can be supported with bugfixes and next version can be developed in master
). Commit E
was used to specify version information (added release notes, etc). Commit D
introduced new feature, which is planned for the next version and should not appear in v1-release
.
Now, if a bug is found in v1-release
, it must be fixed in both branches, so that users can continue using v1 and it does not appear in the next version.
After fixing the bug in master
, repository should look like this:
A--B--C--D--F ← master ← HEAD
\--E ← v1-release
Now commit F
with a bugfix must be applied to v1-release
branch.
How to actually do it
Commits cannot be exactly copied (since commit is a directory saved state), but you can apply changes made in commit to another commit.
cherry-pick
command does exactly that. It applies changes made by a specified commit to the current branch, creating new commit:
git checkout v1-release
git cherry-pick F
After this, repository should look like this:
A--B--C--D--F ← master
\--E--G ← v1-release ← HEAD
Commit G
introduces same changes as F
.
You may have to resolve conflicts (exactly like after merge).
Error message
The previous cherry pick was now empty ...
means that changes made by cherry-picked commit are already present in current branch. You probably forgot to checkout correct branch.
In case of errors or conflicts cherry-pick can be aborted using git cherry-pick --abort
.
Finally, you can return to master
branch and push both branches to remote repository:
git checkout master
git push origin master v1-release
Final repository structure:
A--B--C--D--F ← master ← HEAD
\--E--G ← v1-release