简体   繁体   中英

Squash feature branch commit after merging from master

I am trying to squash commits in a branch to that when it is finally merged to master (after pull request if aproved) the commit history looks clean.Hence before raising the pull request I do a

git rebase -i

and rewrite the history.

However while developing the feature in its branch I have to merge the content of the master onto the branch because master usually moves ahead due to other feature branches being merged.

I see ones I merged master to feature branch I can not squash he commits any more using interactive rebase. It leads to unusual diff during pull requests ie changes which came as part of merges from master.

What is the best way to squash the commits in this case?

If you just want to sqaush everything, then you have a way simpler way to do that that does not rely on using interactive rebasing. You can just do a soft reset to your master branch and then commit those changes:

git reset --soft master
git commit -m 'All changes from my branch squashed'

This basically resets the branch pointer to the master branch, without changing any of the content in your working directory. So the result is that you have all those changes in your index which you can commit then at once.

If you want the feature branch is on the top of master branch, so that your pull request contains changes from other feature branches merged. You can use below commands:

git checkout feature
git pull origin master --rebase

This will rebase feature branch on the top of master branch after fetching from origin master.

I am trying to squash commits in a branch to that when it is finally merged to master (after pull request if aproved) the commit history looks clean

You can use soft reset to squash your branch (say, feature ) commits. Say you have 5 commits in feature branch. Now you need 5 commits = 1 new commit.

$ git checkout feature
$ git log                        # see how many commits do you need to squash

$ git reset --soft HEAD~4        # note: if you have N commits then HEAD~{N-1}
Or, git reset --soft <first-commit> # reset to first commit of your branch

$ git add .                      # add the files  
$ git commit --amend -am 'Squash all commits'  # squash all the commits

$ git push -f origin feature     # force(-f) push to remote since git history is changed  

Now, Pull master branch changes.

$ git pull origin master

Create a Pull request now using GitHub GUI (browser).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM