DEV Community 👩‍💻👨‍💻

Davyd McColl
Davyd McColl

Posted on

#TIL how to move uncommitted code from one git repo to another


in the source repo, do:

git stash
git stash show -p > /tmp/stash.patch
git stash drop
Enter fullscreen mode Exit fullscreen mode

in the target repo, do:

git apply /tmp/stash.patch
Enter fullscreen mode Exit fullscreen mode

🎉 WIN 🎉

The full story:

I often have two clones of work repos on my machines:

  • one I'm working in
  • one where I can check out reviews or do fixes for ongoing PRs without disrupting my main working repo

Today, I started doing some work in the secondary clone and realised that I needed to move that work over to the primary one. I hadn't committed, and I figured that there was a way to do this with git's stash command, but I wasn't sure. So I googled a bit to get to the above, based on a stackoverflow post.

Let's go through what's happening:

In the source repo

  • git stash puts all your uncommitted changes in the stash, which is a stack-based storage for changesets.
  • git stash show -p shows the latest stashed changeset in patch format. Here I pipe it into a file in /tmp, but you could pipe it anywhere. Without the -p, git stash show will give you similar information as what you'd see with git log --stat: showing a condensed version of the changes per file. So don't forget that -p!
  • git stash drop drops the latest stash -- you won't be needing it, since you have a patch file, but if you're feeling nervous, don't: there's a way to get it back

In the target repo

  • git apply /tmp/stash.patch applies the patchset to your current repository

Wrapping up

git can be challenging and confusing when you're new to it... even when you're not-so-new to it 😆 but the one thing I like to remind people is that it's quite difficult to permanently lose information in git. Well, except if you git reset --hard, then you can kiss those uncommitted changes good-bye! But most of the time, the reflog or fsck can find pieces you think are gone forever. Also, git probably does a lot more than you might expect, so try googling what you want to do before resorting to a manual plan or panicking -- chances are someone has had the same problem before and found a solution!

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.