我如何挑选以前的提交?

时间:2021-03-25 16:34:03

标签: git git-rebase

假设我们有一个 master 分支和一个 feature 分支。

(master) M1 -> M2 -> M3 -> M4
                \
(feature)       M2 -> F1

现在我想做的是将 F1 中的所有更改合并到提交 M2 中(而不是在 M4 之后)。我知道将 F1 重新设置为 master 或合并到 master 会在 M4 之后添加 F1。但是,我想通过 F1 的更改来修改 M2 提交。

以下是我已经尝试过的:重新调整基址以编辑 M2,将 F1 挑选到 M2,软重置为 M1,提交,然后继续变基址。这或多或少有效,但如果 M3/M4 和 F1 之间存在冲突,则行为有点奇怪(无法解释,因为我没有完全理解)。

2 个答案:

答案 0 :(得分:0)

您可以查看 M2,并修改该提交:

# Assuming you are on the tip of 'feature'

git tag feature_before_amending # Tag the F1 commit in case things go badly
git reset --hard M2             # Reset current branch pointer to M2
git checkout F1 -- .            # Restore changes from F1 as staged files
git commit --amend              # Amend the M2 commit with changes from F1
git push origin HEAD --force    # Push the new, amended commit

这假设 F1 提交是好的。如果 F1 提交很糟糕,并且您基本上需要将其重新合并到 M2 中,那么创建一个新分支然后重置“功能”分支应该可以解决问题:

git checkout -b amended_feature M2 # Create a new local branch from M2
git merge --no-commit F1           # Merge the F1, but stage changes instead of committing
git commit --amend                 # Amend the M2 commit in 'amended_feature'
git checkout feature               # Check out the 'feature' branch again
git reset --hard amended_feature   # Reset the branch pointer of 'feature' to amended M2 commit
git push origin HEAD --force       # Finish by force-pushing the changes

答案 1 :(得分:-1)

我能够通过两个步骤来实现这一点,而不是我在问题中提到的一件奇怪的事情。概述以下步骤 -

  1. git rebase 以编辑 M2
  2. 在 rebase 中使用 git cherry-pick F1
  3. git rebase --continue。如果F1和M3/M4有冲突,可以在这里解决,然后继续rebase
  4. 回到头,再次变基并将 F1 提交压缩到 M2 上

这需要两个 rebase,但这有效。有没有办法在一个干净的 rebase 中实现这一目标?

编辑:根据 Greg Burghardt 在回复中的评论,我认为以下方式是一种直观且简单的方法 -

假设我们在 master (M4) 的头上,我们执行以下操作

git rebase -i M2^ (and edit M2)
git cherry-pick -n F1
git add .
git commit --amend
git rebase --continue (fix any conflicts and then run this again)
相关问题