我用:

git checkout -b testbranch

我做了20次提交。

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

git rebase -i HEAD~20

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

git rebase -i all on this branch

当前回答

如果你使用基于IDE的JetBrains,如IntelliJ Idea和prefare,使用命令行GUI:

进入版本控制窗口(Alt + 9/Command + 9) -“日志”选项卡。 在树中选择创建分支的点 右键点击它->重置当前分支到这里->选择软(!!)(重要的是不要失去你的变化) 按下对话框窗口底部的重置按钮。

就是这样。您未提交所有更改。现在如果你重新提交,它会被压缩

其他回答

我知道这个问题已经有了答案,但我围绕已接受的答案编写了一个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
}

在之前的回答中,我没有看到任何关于如何处理“凌乱的分支”和“自我冲突”的信息。例如,我经常在我的特性分支(称为特性)上有主提交,这导致了它们之间的冲突。我发现这是最难处理的问题之一。

如何挤压凌乱的树枝?使用临时分支!

我发现Felix Rieseberg的解决方案是最好的。以下是我对他的建议略短的抄写:

Create a local tmp branch of off master git checkout master && git pull && git checkout -b tmp Merge all feature changes into tmp (without any commits, only staged file changes). git merge --squash $feature Manually solve all remaining "real conflicts" (This is the only step you cannot have a script do for you) Commit. tmp is now master + 1 commit (containing all changes). git commit ... Checkout feature and git reset --hard tmp (feature's original contents are gone, and it is now basically tmp, but renamed) git checkout $feature && git reset --hard tmp Ignore and override origin/feature (then clean up) git push -f && git branch -D tmp

Felix指出,这将产生最干净的合并,没有任何来自master和feature之间混乱/复杂关系的奇怪的自我冲突:

您可能会遇到一些不可避免的合并冲突。请相信,这是尽可能少的冲突,因为您跳过了最初创建的许多中间提交。

签出您希望将所有提交压缩为一次提交的分支。我们说它叫feature_branch。

git checkout feature_branch

步骤1:

用你的本地主分支对你的origin/feature_branch进行软重置(根据你的需要,你也可以用origin/main重置)。这将重置feature_branch中所有额外的提交,但不会在本地更改任何文件更改。

git reset --soft main

步骤2:

将git repo目录中的所有更改添加到将要创建的新提交中。并通过信息提交相同的信息。

# Add files for the commit.
git add ...
git commit -m "commit message goes here"

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

$ 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: ...

你可以通过子命令来实现

$ git rebase -i HEAD~$(git rev-list -count HEAD ^master)

这将首先计算从master分离后的提交次数,然后将其还原到确切的长度。