Here are two quick git tricks that I’ve added to my toolbox lately…
I wanted to create a git alias that takes in argv from the command, but in the middle of the command. Here’s the hack that I came up with for the [alias]
section of my ~/.gitconfig
:
[alias]
# cherryfetch fetches a repo ($1) / branch ($2) and applies it rebased!
# the && true at the end eats up the appended args
cherryfetch = !git fetch "$1" "$2" && git cherry-pick HEAD..FETCH_HEAD && true
Explanation:
The git alias is called “cherryfetch”. It starts with an exclamation point (!
) which means it’s a command to execute. It uses $1
and $2
as arguments, which thankfully exist in this environment! Because running a git alias causes the arguments to get appended to the command, the &&
true part exists at the end to receive those commands so that they are silently ignored! This works because the command:
$ true ignored command line arguments
Does absolutely nothing but return success. Better naming suggestions for my alias are welcome!
What does this particular alias do?
Too often I receive a patch which has not been rebased against my current git master. This happens because the patch author started hacking on the feature against current git master, but git master grew new commits before the patch was done. The best solution is to ask the author to rebase against git master and resubmit, but when I’m feeling helpful, I can now use git cherryfetch
to do the same thing! When their patch is unrelated to my changes, this works perfectly.
Example:
$ git cherryfetch https://github.com/example_user/puppet-gluster.git feat/branch_name
From https://github.com/example_user/puppet-gluster
* branch feat/branch_name -> FETCH_HEAD
[master abcdef01] Pi day is awesome, but Tau day is better! purpleidea/puppet-gluster#feat/branch_name
Author: Example User <[email protected]>
Date: Tue Mar 14 09:26:53 2015 -0400
4 file changed, 42 insertions(+), 13 deletions(-)
Manual learning:
If you were to do the same thing manually, this operation is the equivalent of checking out a branch at the same commit this patch applies to, pulling the patch down (causing a fast-forward) running a git rebase master
, switching to master and merging your newly rebased branch in.
My version is faster, isn’t it?
Happy hacking!
James
Update: I’ve updated the alias so that it works with N commits. Thanks to David Schmitt for pointing it out, and Felix Frank for finding a nicer solution!
You can follow James on Mastodon for more frequent updates and other random thoughts.
You can follow James on Twitter for more frequent updates and other random thoughts.
You can support James on GitHub if you'd like to help sustain this kind of content.
You can support James on Patreon if you'd like to help sustain this kind of content.
Your comment has been submitted and will be published if it gets approved.
Click here to see the patch you generated.
Comments
Nothing yet.
Post a comment