我用:

git checkout -b testbranch

我做了20次提交。

现在我想要压缩这20个提交。我是这样做的:

git rebase -i HEAD~20

如果我不知道有多少次提交呢?有没有什么方法可以做到:

git rebase -i all on this branch

当前回答

为了完善一下Caveman的回答,使用git reset——soft <commit>。从文档中,这个命令:

根本不触及索引文件或工作树(但将头部重置为<commit>,就像所有模式一样)。这将使所有更改过的文件都变成“要提交的更改”,就像git状态所显示的那样。

换句话说,它将撤销到<commit>之前的所有提交。但是它不会改变工作目录。您最终会得到所有的更改,这些更改都是未分期和未提交的。就好像那些介入的提交从未发生过一样。

例子:

# on master
git checkout -b testbranch
# make many commits
git reset --soft master
git add .
git commit -m 'The only commit.'

此时,您仍然在testbranch上,它只有一次提交。像往常一样合并到master中。

在我的手中,Caveman回答的第一部分(git rebase -i)并没有压缩提交。

其他回答

在阅读了几个关于压缩的Stackoverflow问题和答案后,我认为这是一个很好的压缩分支上所有提交的代码行:

git reset --soft $(git merge-base master YOUR_BRANCH) && git commit -am "YOUR COMMIT MESSAGE" && git rebase -i master

这是假设master是基础分支。

对于喜欢点击的人的解决方案:

安装源代码树(免费) 检查你的提交是什么样的。很可能你有类似的东西 右键单击父提交。在我们的例子中,它是主分支。

您可以通过单击一个按钮来取消上一个提交。在我们的例子中,我们需要点击2次。您也可以更改提交消息 结果非常棒,我们已经准备好了!

旁注:如果你把你的部分提交推到远程,你必须在挤压后强制推

另一种简单的方法是:在原始分支上进行合并-挤压。该命令不执行“压缩”提交。当你这样做时,你分支的所有提交消息将被收集。

$ git checkout master
$ git merge --squash yourBranch
$ git commit # all commit messages of yourBranch in one, really useful
 > [status 5007e77] Squashed commit of the following: ...

我知道这个问题已经有了答案,但我围绕已接受的答案编写了一个bash函数,以允许您在一个命令中完成它。它首先创建一个备份分支,以防压缩由于某种原因失败。然后压缩并提交。

# Squashes every commit starting after the given head of the given branch.
# When the squash is done, it will prompt you to commit the squash.
# The head of the given parent branch must be a commit that actually exists
# in the current branch.
#
# This will create a backup of the current branch before it performs the squash.
# The name of the backup is the second argument to this function.
#
# Example: $ git-squash master my-current-branch-backup
git-squash() {
  PARENT_BRANCH=$1
  BACKUP_BRANCH=$2

  CURRENT_BRANCH=$(git branch --show-current)

  git branch $BACKUP_BRANCH
  BACKUP_SUCCESS=$?

  if [ $BACKUP_SUCCESS -eq 0 ]; then
    git reset $(git merge-base $PARENT_BRANCH $CURRENT_BRANCH)
    git add -A
    git commit
    echo "Squashed $CURRENT_BRANCH. Backup of original created at $BACKUP_BRANCH$"
  else
    echo "Could not create backup branch. Aborting squash"
  fi
}

如果你可以接受涉及另一个分支的答案,尝试git checkout——orphan <new_branch>它允许我简单地将前一个分支的所有文件作为一个提交。

这有点像git的合并压缩,但不完全相同。