将整洁、干净、紧凑的git PR和合并提交合并为一个提交。

5
大多数情况下,在仓库中我们会看到一个PR,然后是该PR的合并提交,只是说“从...合并拉取请求#XXX”。但最近我看到了一种压缩的版本,在这个版本中,拉取请求者和提交者的头像重叠在一起,历史记录中只显示一个干净的提交

enter image description here

如何完成这个任务?

我尝试过但不起作用的方法:


更新

以下是 我的一个PR 被合并时的示例:

enter image description here

结果为:

enter image description here

2个回答

6

2016年4月更新

GitHub引入了一种选项,在合并时压缩提交记录,因此您可以直接从其Web界面执行此操作:

Squash and merge

旧的解决方案

刚刚发现了Meteor团队的工作流程(巧合的是,感谢@Emily):

当您在GitHub网页界面中查看拉取请求时,会看到一个非常吸引人的“合并”按钮。永远不要使用合并按钮。它是一种有吸引力的诱因。它会导致比必要更复杂的git历史记录:如果PR是一个月前提交的,则提交的父级将是一个非常旧的修订版本,在git历史记录的图形视图中会导致比必要更多的行数。此外,如果您使用合并按钮,那意味着您从未检出代码并尝试过它!以下是更好的方法来处理拉取请求。

首先,在您的存储库中,找到.git/config文件的[remote "origin"]部分,并添加以下行:

fetch = +refs/pull/*/head:refs/remotes/origin/pr/*

确保在现有的fetch行之前添加它。现在,每次你git fetch,你都会得到repo中所有的Pull Requests更新!这是一次性的更改,将为您永久提供直接访问PR的权限。

然后,你只需要git checkout pr/XXX并直接处理更改。在cherry-picking之后进行git push origin将创建紧凑型PR:

git checkout pr/32
# ... test changes ...
git checkout master
git cherry-pick pr/32
git push 

enter image description here

唯一的缺点是GitHub不会自动删除PR分支,但只需要点击一下就可以了,而且换来的是更好的历史记录。

If the PR is multiple commits, the best thing to do is to check it out, rebase it onto your development branch, make whatever other changes you need, and merge it back to the development branch with an explicit merge commit. This is similar to what the GitHub merge button does, except that the merge button doesn't do the VERY IMPORTANT rebase step and so it leaves ugly spaghetti in the project's git commit history. To do this, run:

git checkout pr/32; git rebase devel; git checkout devel; git merge --ff-only pr/32

Then test and push.

If you'd like to combine some of the commits into a single commit, you can use interactive rebase by running git rebase -i devel instead. Some tutorials: http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html https://www.atlassian.com/git/tutorials/rewriting-history/git-reflog

Unfortunately GitHub is not smart enough to detect that you've merged a PR by hand, so you'll need to manually comment and close the issue with a link to the relevant commit. Alternatively, make sure that the merge commit's message contains Fixed #123.


更新: Kahmali Rose 进一步更新了内容,使得 GitHub 能够检测到 PR 是否已经合并,就像点击邪恶的“合并”按钮一样:确保使用 rebase and merge 而不是 cherry-pick

1
如果PR只包含一个提交,您可以将其cherry-pick到master分支(或您合并PR的任何其他分支)中。例如:
$ git checkout -b branch-for-pr master
$ git pull <fork url> <pr branch name>
$ git checkout master
$ git cherry-pick branch-for-pr

或者,您可以将PR分支rebase到master之上,以允许快进合并(这将跳过合并提交):

$ git checkout -b branch-for-pr master
$ git pull <fork url> <pr branch name>
$ git rebase master
$ git checkout master
$ git merge --ff-only branch-for-pr

1
我在this PR上尝试了第一组命令,但出现了“错误:提交37b2d6f35770196ffcbe338117651e7cac9a0b33是一个合并,但没有给出-m选项”的提示。 - Dan Dascalescu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接