Last Updated: February 25, 2016
·
263
· tastycode

Using git-patch for fun and profit

I hate using git stash. It is supposed to let me put what I'm working aside and come back to it later, but there are clear issues that I've ran into.

  • Stashing something and forgetting about it
  • Doing git stash pop and getting merge conflicts + losing the ability to retry it

As a result, many times I just do git add .; git commit -am "WIP" and then do git reset HEAD^ when I get back.

There are times though, when I want to store "code ideas". I don't really want them in the repo, but I'd like to be able to refer to them if I want to go look them up.

Most commands in git accept an argument -p: This argument shows the changes related to the current command in "patch form".

  • git show -p defaults to HEAD and in that case is equivalent to git diff. It can be used to show any valid ref.

  • git log -p shows the history in patch format

  • git diff -p shows diffs between two refs in patch format

So, these are particularly useful when combined with git apply. This command will take a file or STDIN and apply the changes to the working tree.

Example: I've guessed that a bug was related to how we truncate tables with transactional fixtures. It failed on CI and I want to go back and "diverge" from that and try mucking with our JSON serialization, but I don't want to lose the work in case it was ultimately a good direction.

git log -1 -p > ~/tmp/project/transactional_fixtures.patch

git reset HEAD^ --hard

# do the work! 

Let's say I find out after mucking around with the current branch and CI and find that I actually did want to go with the transactional_fixtures direction.

git reset REF^ --hard #REF is the common parent of the divergence
cat ~/tmp/project/transactional_fixtures.patch | git apply

Voila! I've got my original commit(s) back for the original direction.

You could imagine this being helpful when you are worried about git stash. git cmd -p and git apply are super useful for maintaining offline stashes outside of the repo and being able to use them later.