So recently I found out there's a good reason to use a particular syntax for force pushing a branch to the backend.
I was doing this for a force push:
git push -f
Why would I force push a branch? Because I often end up squashing lots of small commits on the branch into a single commit to make the commit history easier to read. When I do that I need to force push to overwrite the existing history. Mind you I'm only doing this on my own branches.
However, I found out much to my distress that if you've got multiple references to your backend (that is multiple branches tracking to origin) they all get force pushed when you do -f. If you're curious about this it's here in the git documentation.
There is an alternative that works just fine if you're only meaning to force push your current branch. What you can do is this:
git push origin +<branch>
This will only force push the named branch. However since I need to do this fairly often (as I say after I squash all the commits on a branch I force push so that instead of having 12 commits on a PR, I've got one) I want a git alias to make this easier for me. And so I came up with this:
fp = "!p() { CURRENT_BRANCH=$(git branch --show-current); git push origin +$CURRENT_BRANCH; }; p
(I'm indebted to Phil Haack for demonstrating this technique of using a shell function in a git alias to allow for trickier stuff!)
First I get the current branch name into the CURRENT_BRANCH environment variable. Next I create the git push command substituting the CURRENT_BRANCH name. Finally the shell function is invoked.
This does a force push but only on the current branch so I don't have to worry about inadvertently forcing other branches to the backend.
Top comments (0)