Home > Net >  git rebase -i HEAD~N --> How to determine N?
git rebase -i HEAD~N --> How to determine N?

Time:06-25

I created a pull-request and upstreams wants me to create a single commit.

I know that I can use this:

git rebase -i HEAD~N

# then pick the first commit, and squash the following commits

git push --force-with-lease 

But there are many commits, so that I don't know the right number of N immediately.

Is there a way to detect N with a one-liner?

CodePudding user response:

Note that HEAD~N simply resolves to a specific commit ID, which you can quickly determine by glancing at git log or any UI. Besides, using N as the number of commits only works if the commits you wish to rebase are linear. Therefore, if you don't know what N is, consider not trying to determine it and just use the commit ID instead.

If you know your branch came off of master, you could even view the commit ID without even looking at the log or a UI graph:

git merge-base master your-branch

Which means in the general sense you could always use (in Git Bash):

git rebase -i $(git merge-base master @)
# Note @ is shorthand for HEAD which is your current branch tip

Another consideration is you can interactive rebase onto master directly:

git rebase -i master

If your local copy of master hasn't changed since you created the branch you are rebasing, then that will be identical to using the merge-base. If master is now ahead of where you started, then this won't be identical because you are replaying your commits onto a different state, and it's possible you'll have conflicts. Note in this case these are conflicts you'll have to resolve anyway, but some people may prefer to finish the squash first without the possibility of conflicts, and then do another rebase onto a newer master to resolve conflicts afterwards. One reason for this is before the squash you may have to resolve conflicts in multiple commits, whereas if you squash first you'll only have to resolve conflicts in the squashed commit(s).

A faster squash: in the case where you wish to squash all of your commits down into a single one, it's usually more efficient to use reset instead of interactive rebase:

git reset --soft <commit-ID-you-started-your-branch-from>
# or without even looking:
git reset --soft $(git merge-base master @)

# now commit
git commit -m "Add new commit message here"

Note you could also reset to master directly instead of the merge-base command above, like Romain Valeri mentioned in a comment, but you can do this only if the master branch hasn't changed since you branched off of it. Just in case you're wrong about that I would recommend sticking with either the merge-base command or just use the hash of the parent commit of the first commit on your branch.

CodePudding user response:

This worked for me:

git log master.. --oneline| wc -l
  •  Tags:  
  • git
  • Related