使用 Git 在两个分支中推送提交

如何在两个分支中推送提交?

我不能使用“ git push”,因为它会推到三个分支,我只需要其中两个分支中的提交。.

我在分支 B 中尝试了“ git merge HEAD ——从分支 A 提交 id ——”,但是它从分支 A 获取所有内容并与分支 B 合并。我只想要最后一次提交,而不是其他所有内容与分支 B 合并。

有人知道该怎么做吗?

62058 次浏览

长话短说

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

假设您有一个具有这种结构的存储库:

A--B--C--D  ← master ← HEAD
\--E  ← v1-release

经过一些开发(提交 ABC)项目发布,并创建了 v1-release分支(这样就可以用 bug 修复程序支持 v1,并在 master中开发下一个版本)。提交 E用于指定版本信息(添加发行说明等)。提交 D引入了新的特性,这是计划的下一个版本,不应该出现在 v1-release

现在,如果在 v1-release中发现一个 bug,那么它必须在两个分支中都得到修复,这样用户就可以继续使用 v1,而且它不会出现在下一个版本中。

After fixing the bug in master, repository should look like this:

A--B--C--D--F  ← master ← HEAD
\--E     ← v1-release

现在提交带有 bug 的 F必须应用到 v1-release分支。

该怎么做呢

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

之后,存储库应该是这样的:

A--B--C--D--F  ← master
\--E--G  ← v1-release ← HEAD

提交 G引入了与 F相同的更改。

您可能必须解决冲突(与合并后完全一样)。

错误信息

之前的樱桃采摘器现在空了。

意味着当前分支中已经存在由选择提交所做的更改。您可能忘记签出正确的分支。

在出现错误或冲突的情况下,可以使用 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

试试这个:

git push origin <commitId>:<brancnName_1>
git push origin <commitId>:<brancnName_2>

在我这边很管用。