这为压缩多个提交提供了很好的解释:

http://git-scm.com/book/en/Git-Branching-Rebasing

但它不适用于已经推送的提交。如何在本地和远程回购中压缩最近的几次提交?

当我执行gitrebase-I origin/master ~4 master时,将第一个设置为pick,将其他三个设置为squash,然后退出(通过emacs中的c-x-c-c),我得到:

$ git rebase -i origin/master~4 master
# Not currently on any branch.
nothing to commit (working directory clean)

Could not apply 2f40e2c... Revert "issue 4427: bpf device permission change option added"
$ git rebase -i origin/master~4 master
Interactive rebase already started

其中2f40是选择提交。现在,4个提交都没有出现在git日志中。我希望我的编辑器重新启动,以便我可以输入一条提交消息。我做错了什么?


当前回答

当您使用Gitlab或Github时,您可能会以这种方式遇到麻烦。您可以使用上述方法之一压缩提交。我最喜欢的是:

git rebase -i HEAD~4
or
git rebase -i origin/master

为您的提交选择squash或fixup。此时,您将检查git状态。信息可能是:

    On branch ABC-1916-remote
    Your branch and 'origin/ABC-1916' have diverged,
    and have 1 and 7 different commits each, respectively.
      (use "git pull" to merge the remote branch into yours)

你可能会被诱惑去做。不要那样做,否则你会陷入和以前一样的境地。

相反,通过以下方式推到原点:

git push origin +ABC-1916-remote:ABC-1916

+只允许强制推动一个分支。

其他回答

Squash使用本地提交

git rebase -i origin/master~4 master

然后用力推

git push origin +master

力与+

从git push的文档中:

注意--力应用于所有被推动的ref,因此使用它具有push.default设置为匹配或多个push使用remote.*.push配置的目标可能会覆盖其他引用比当前分支(包括严格落后的本地引用它们的远程对应物)。要强制推送仅一个分支,请使用+在refspec前面推送(例如git推送原点+主推送强制推到主分支)。

Sqush远程更改

首先确保您的本地主机与远程主机相同然后将本地功能分支重置为与master相同:gitreset-soft-master然后添加您对您刚刚重置为master的本地功能分支)到临时区域:gitadd。然后提交这些更改:gitcommit-m“这是最后的提交消息”然后强制推到远程分支:gitpushRemoteBranch--force

在一个分支上,我可以这样做(最后4次提交)

git checkout my_branch
git reset --soft HEAD~4
git commit
git push --force origin my_branch

对于压缩单个分支上的两个提交(其中一个已被推送),以下操作有效:

git rebase -i HEAD~2
    [ pick     older-commit  ]
    [ squash   newest-commit ]
git push --force

默认情况下,这将包括最新提交的提交消息,作为对旧提交的注释。

通过只创建一个分支来处理而不处理主分支,可以避免许多问题:

git checkout-b mybranch

以下方法适用于已推送的远程提交以及远程推送提交/仅本地提交的混合:

# example merging 4 commits

git checkout mybranch
git rebase -i mybranch~4 mybranch

# at the interactive screen
# choose fixup for commit: 2 / 3 / 4

git push -u origin +mybranch

我也有一些请求笔记,这可能会有所帮助。