我用:
git checkout -b testbranch
我做了20次提交。
现在我想要压缩这20个提交。我是这样做的:
git rebase -i HEAD~20
如果我不知道有多少次提交呢?有没有什么方法可以做到:
git rebase -i all on this branch
我用:
git checkout -b testbranch
我做了20次提交。
现在我想要压缩这20个提交。我是这样做的:
git rebase -i HEAD~20
如果我不知道有多少次提交呢?有没有什么方法可以做到:
git rebase -i all on this branch
当前回答
你可以使用我专门为这个任务创建的工具:
https://github.com/sheerun/git-squash
基本上你需要打电话给git壁球大师,你就搞定了
其他回答
另一种简单的方法是:在原始分支上进行合并-挤压。该命令不执行“压缩”提交。当你这样做时,你分支的所有提交消息将被收集。
$ 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: ...
假设你在特征分支上:
在特性分支中找到第一个提交。如果你正在使用gitlab或github,你可以直接在分支中查看它,并从那里复制散列,或者你可以使用以下命令:
Git日志<source_branch>..< feature_branch >——漂亮=格式:% h
执行以下命令:
git reset --soft <base_commit_hash>
git commit --amend --no-edit
现在在这个阶段,在您的本地,您有一个提交,其中包括在所有以前的提交中所做的更改。
回顾它,你需要用力推它。在强制推送之后,所有的更改都将合并到一个提交中,而您的分支将只有1个提交。
在特征分支中强制推送
git push --force
你正在做的事情很容易出错。只做:
git rebase -i master
它会自动将你的分支的提交重置到当前最新的主节点上。
签出您希望将所有提交压缩为一次提交的分支。我们说它叫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"
另一种压缩所有提交的方法是将索引重置为master:
git checkout yourBranch
git reset $(git merge-base master $(git branch --show-current))
git add -A
git commit -m "one commit on yourBranch"
这并不完美,因为这意味着你知道“你的分支”来自哪个分支。 注意:在Git中找到原始分支并不容易/不可能(可视化的方式通常是最简单的,如图所示)。
注意:git分支——show-current已在git 2.22(2019年第二季度)中引入。
或者,正如Hiroki Osame在评论中指出的那样:
git switch yourBranch
git reset --soft $(git merge-base main HEAD)
git commit -m "one commit on yourBranch"
不需要git分支——show-current,因为HEAD已经是该分支的引用。 不需要git add -A,因为git重置-soft只移动HEAD,并保持索引不变(换句话说,文件已经“添加”)。
编辑:你将需要使用git push——force
Karlotcha Hoa在评论中写道:
对于重置,可以这样做 git reset $(git merge-base master $(git rev-parse——abbrev-ref HEAD)) 自动使用您当前所在的分支。 如果使用它,还可以使用别名,因为该命令不依赖于分支名称。
Sschoof在评论中补充道:
因为我的默认分支被称为main,我的搜索多次把我带到这里: 为我下次上课抄一份 git reset $(git merge-base main $(git rev-parse——abbrev-ref HEAD))