从 master 合并后压缩功能分支提交

Squash feature branch commit after merging from master

我正在尝试将分支中的提交压缩到最终合并到主分支时(如果批准后拉取请求)提交历史看起来 clean.Hence 在提出拉取请求之前我做了一个

git rebase -i

并重写历史。

然而,在其分支中开发功能时,我必须将 master 的内容合并到分支上,因为 master 通常会因为其他功能分支被合并而向前移动。

我看到我将 master 合并到 feature 分支我不能再使用交互式 rebase 压缩他提交的内容。它会导致在拉取请求期间出现不寻常的差异,即作为来自 master 的合并的一部分的更改。

在这种情况下压缩提交的最佳方法是什么?

如果你只是想 sqaush 一切,那么你有一种更简单的方法来做到这一点,而不依赖于使用交互式变基。您可以对主分支进行软重置,然后提交这些更改:

git reset --soft master
git commit -m 'All changes from my branch squashed'

这基本上将分支指针重置为 master 分支,而不更改工作目录中的任何内容。所以结果是您的索引中有所有这些更改,您可以立即提交这些更改。

如果您希望功能分支位于主分支的顶部,以便您的拉取请求包含来自合并的其他功能分支的更改。您可以使用以下命令:

git checkout feature
git pull origin master --rebase

这将在从原始主服务器获取后在主分支顶部重新设置功能分支。

I am trying to squash commits in a branch to that when it is finally merged to master (after pull request if aproved) the commit history looks clean

您可以使用 soft reset 压缩您的分支(例如,feature)提交。假设您在 feature 分支中有 5 次提交。现在你需要 5 次提交 = 1 次新提交。

$ git checkout feature
$ git log                        # see how many commits do you need to squash

$ git reset --soft HEAD~4        # note: if you have N commits then HEAD~{N-1}
Or, git reset --soft <first-commit> # reset to first commit of your branch

$ git add .                      # add the files  
$ git commit --amend -am 'Squash all commits'  # squash all the commits

$ git push -f origin feature     # force(-f) push to remote since git history is changed  

现在,拉主分支更改。

$ git pull origin master

现在使用 GitHub GUI(浏览器)创建拉取请求。