Sharing a Git Stash With Another Developer

Sharing a git stash or single commit with another developer is a pretty easy task, but sometimes I forget EXACTLY what I need to type in to make it work the way I want.

Also, BONUS section below for new thing I learned the last time I did it (yesterday!).

I found myself needing a small pile of prototype code from another developer that doesn’t necessarily make sense to push to a remote (or to even commit!). He had that code stashed in his repo for whenever he wanted to exercise a particular piece of plumbing code that is otherwise hard to exercise.

The following is how we moved that code (i.e. patch) from his machine, to my machine

Creating the stash as a patch

On his machine:

$ git stash show "stash@{0}" -p > changes.patch

This creates a patch file that contains all the differences represented by the set of changes in the stash. The “stash@{0}” is the ref of the stash. You may want a different one. Use “git stash list” to see your list of stashes. Note – those quotes are important! Most shells will eat the curly braces and it won’t do what you’re likely expecting.

snip… <sends file to me over Slack>

Applying the patch

On my machine:

snip… <downloads the patch file and drops it into the root of my source directory>

$ git apply changes.patch

If all goes well, the apply changes are applied to your working copy. They aren’t automatically committed like you may be familiar with from cherry-pick.

BONUS – Reversing the stash

Now, you may remember this code I don’t actually want to commit to the repository. Here is how to blow away only these changes before I commit my actual changes.

$ git apply changes.patch --reverse

This does exactly what it looks like. It applies the “reverse” of the patch; thereby removing the set of changes it had applied in the first place.

Note: this is a summarized version of my trip in and around this stackoverflow question.