git - cherry-pick 与 rebase

标签 git rebase git-rebase cherry-pick

以下是我经常遇到的场景:

您在 masterdesign 上有一组提交,我想将其放在 production 分支之上。

我倾向于创建一个以 production 为基础的新分支,cherry-pick 这些提交并将其 merge 到 production

然后,当我将 master merge 到生产环境时,我面临 merge 冲突,因为即使更改相同,但由于 cherry-pick 而被注册为不同的提交。

我已经找到了一些解决方法来解决这个问题,所有这些都很费力并且可以称为“hacks”。

尽管我没有做太多 rebase ,但我相信这也会创建一个新的提交哈希。

我应该在我挑选的地方使用 rebase 吗?与此相比,它还有哪些其他优势。

最佳答案

您应该在生产之上创建一个rebase --interactive 设计分支,其中:

  • 您可以重新排序您的提交,从您在生产中需要的那些开始
  • 然后您可以将生产 merge 到您要 merge 的最后一次提交的设计中(快进)
    -x--x--x1--x--x2 (design)
      \
       p--p (production)

With x1 and x2 needing to be included in production:

git checkout design
git rebase --interactive production

-x
  \
   p--p (production)
       \ 
        x1'-x2'--x'--x' (design)

然后:

git checkout production
git merge x2'
-x
  \
   p--p--x1'--x2' (production)
                \
                 x'--x' (design)

这让你:

  • 根据生产提交验证当前的设计提交(在 rebase 期间)
  • 重新排序设计提交
  • 在生产中包括第一批
  • 允许从设计到生产的后续 merge 成为快进 merge 。

Lakshman Prasad添加:

I push the changes at the end of the day most of the time. So doesn't really help that much. How would your answer change for the pushed master branch

我会做同样的事情,但是会创建一个专为操作创建的私有(private)分支:

git checkout master
git checkout -b master-private
    -x--x--x1--x--x2 (master, master-private)
      \
       p--p (production)

, then the rebase, this time with the private branch (i.e. a branch you won't ever push).

git rebase --interactive production

-x--x--x1--x--x2 (master)
  \
   p--p (production)
       \ 
        x1'-x2'--x'--x' (master-private)

然后:

git checkout production
git merge x2'

-x--x--x1--x--x2 (master)
  \
   p--p--x1'--x2' (production)
                \
                 x'--x' (master-private)

master 不会从提交重新排序中受益(使用更符合逻辑的顺序),但至少您可以随时推送 master

并且 production 仍然可以包含它所需要的内容。
如果后续提交到 master 有同样的问题(一些需要包含到 production,其他的稍后),我会:

  • 删除 master-private(我们并不真正关心那些 x',x 从 master 提交的副本)
  • 在 master 之上创建一个 master-private 分支
  • 重新执行 rebase --interactive,使用粗略的冲突解决策略(除了 master-private 分支的第一次提交,因为那些需要集成到 production 分支)
    -x--x--x1--x--x2--x--x3--x (master)
      \
       p--p--x1'--x2'--x3' (production)
                   |     \
                   |      x''--x'' (master-private)
                    \
                     x'..x' (old x' from the first master-private)

关于git - cherry-pick 与 rebase ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3022409/

相关文章:

git - Unfork 一个 GitHub 分支而不删除

git - git show 的管道输出通过过滤器?

git - 如何在交互式 git rebase 期间编辑挂起的命令?

git - git rebase 可以完全删除远程历史记录吗?

git - git rebase --onto --preserve-merges再现了我已经在 merge 中解决的冲突

Git 压缩重命名文件的提交(保留历史记录)

git - 使用 Git 创建更改文件的存档

Git 推送到错误的 heroku 应用程序

git rebase,跟踪 'local' 和 'remote'

git - 如何只保留 git rebase 中的头部更改