在 Git 上将一组提交压缩为一个

我有做大量小承诺的习惯,我对此没有意见。但是,我希望时不时地采用一些线性提交,并将它们折叠在一起,作为一个提交,同时能够编写一个新的提交消息。

我查了一下文件,但似乎有点神秘,有人知道怎么做吗?

52708 次浏览

You can squash any number of commits into a single one using

git rebase --interactive <commit>

Suppose you want to rewrite the history of the tree going back until (but not including) commit a739b0d.

export EDITOR=vim # or your favorite editor
git rebase a739b0d --interactive

Be sure to read up on interactive rebasing first.

Use the command git rebase -i <commit> where <commit> is the SHA for the last stable commit.

This will take you to your editor where you can replace the label pick that is next to each commit since the <commit> you included as an argument to your interactive rebase command. On the command you want to start collapsing at, replace pick with reword, and for each commit thereafter which you wish to collapse into it, replace pick with fixup. Save, and you'll then be allowed to provide a new commit message.

Assuming you don't care about retaining any of your existing commit messages, there's a nifty (and fast) git recipe you can use. First, make sure your branch is checked out:

git checkout <branch-to-squash>

For safety, lets tag the current commit.

git tag my-branch-backup

Next, move the branch HEAD back to your last good commit (without modifying the workspace or index). EDIT: The last good commit is the most recent commit on your branch that you want to retain.

git reset --soft <last-good-commit>

Using git status, you'll notice that all changes on your feature branch are now staged. All that's left to do is ...

git commit

This method is great for consolidating long, convoluted git histories and gnarly merges. Plus, there's no merge/rebase conflicts to resolve!

Now, if you need to retain any of your existing commit messages or do anything fancier than the above allows, you'll want to use git rebase --interactive.

Solution derived from: http://makandracards.com/makandra/527-squash-several-git-commits-into-a-single-commit

Reference: http://git-scm.com/docs/git-reset

Reference: http://git-scm.com/docs/git-rebase