Git Rebase or Squash?

2019-08-10 00:39发布

问题:

I have created a feature branch from develop and that feature branch contains bunch of commits for approximately 20. Before merging the feature branch to the develop I want to convert all commits into one. Which one is the best way to accomplish this task git squash or rebase and how to do it?

回答1:

If you want to squash your bunch of commits into a single commit on feature branch you can do it as follows, but if this bunch of commits is already pushed to remote you have to be sure that no one is working on the feature branch because you'll have to force push to that branch and this implies rewriting remote history (something you usually don't want to do if working on a public repository or more people are working on that branch).

  1. git checkout FEATURE (where FEATURE has to be replaced by the name of your feature branch.
  2. git rebase -i HEAD~21 This is assuming you want to squash the 20 most recent commits. If you have the HASH of the oldest commit you can also do git rebase -i HASH^
  3. Now you have to replace pick by squash (or s) on all lines except the first one and save the file
  4. You have to choose a commit message for this new commit. Git shows you the messages of the commits your are squashing
  5. If the original commits had been already pushed to remote, you'll have to force push, because you are rewriting remote history, replacing those 20 commits by a new one. This is something you usually don't want to do if you are working with more people on that branch. git push -f