shell functions for rebase
Often I find the need to squash commits, especially those that don’t need to stand-alone. And so little a function, which is more an alias with arguments, is used for the job, so I don’t have to think. The git command I use for this in, say, master branch, looks like this:
git rebase -i origin/master~4 master
The -i switch makes it interactive, and in the (below) list it produces, I can mark lines selectively from pick to squash for items to be squashed, followed by :wq.1 If there are multiples marked up in the list, then git produces parent commits with an option to edit commit message(s) should you want to, and you can follow it up with :wq. Here’s an example of the list, in which, one can markup the first column as required.
pick fa77b22 # m:homepage updates
pick 04863ce # link titles update
squash c8fb9a8 # m:edit
# Rebase 69a0567..c8fb9a8 onto 69a0567 (3 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
...
I follow it up with a forced push like so — for sending it upstream. It’s only if the remote already has commits you’re trying to squash.
git push -u origin +master
fish shell
The rebase command feels a little tedious to type out at the prompt, and so this function (placed in ~/.config/fish/config.fish) helps me do the job quickly by running the command gr 4 master, which translates to the first command above:
# fish function to rebase, e.g., gr 4 master
function gr
git rebase -i origin/$argv[2]~$argv[1] $argv[2]
end
Using two arguments for the freedom to define the number of commits, and the other being able to choose the branch.
For the push, I could write a function to run gpp master like so:
# fish function for push following rebase, e.g., gpp master
function gpp
git push -u origin +$argv[1]
end
bash shell
Of course, I have machines where bash is still the default. For those, the function (placed in, e.g., ~/.bashrc) becomes:
# bash function for rebase, e.g., gr 4 master
gr() {
git rebase -i origin/"${2}~${1}" "$2"
}
And for the push in bash, the function would be:
# bash function for the push post rebase, e.g., gpp master
gpp() {
git push -u origin +"$1"
}
Pulling from a force-pushed remote repository, say, origin/master needs some care. The right way is as follows:
git fetch origin
git reset --hard origin/master
-
Write and quit in Vim, which is my default git commit editor. ↩