Pages

Tuesday, October 01, 2024

Trading git patches "via email"

Okay, I've had this open in drafts too long. I think it's got most of the info I wanted, so let's cut it loose for when I need it in the future.


I often take a different laptop with me when I'm travelling than whatever the "prime" development box is for a project, often to ensure I don't lose sensitive information if the laptop "disappears" while I'm out. When doing this, I usually copy the folder I'm working in, remotes (so personal access tokens, VPN setup, etc) be darned, and work from that.

The issue is often getting that work back onto the "prime" boxen. That usually means remembering how to make and apply git patches.

Look, here's the deal... ;)

If you want to copy over and preserve individual commits, you want to use "email" formatted patches. You can envision why. If you came before the time when everyone had shared remotes or if your workforce is distributed and most simply don't have remote access, it's easy to schlep around code via email. And so git has email support built-int! Though do note we're only using the format, as it carefully preserves each commit separately; we're not actually emailing anything. Unless you really want to.

On the travelling box:

Let's say I wanted the last 5 commits. I'd use this command to create an email-formatted patch file:

git format-patch -k --stdout HEAD~5 > patch.patch

Open up the text file and take a look! It's actually kinda interesting, begging for an SMTP server to send it on its way.

On the "prime" development box:

git am -3 patch.patch

Now look, if you used git apply here, it would apply EVERYTHING IN THE FILE AS A SINGLE ACTION and not commit anything. It's like rolling all the changes into a single worksession that needs to be committed. Using git apply for an email versioned patch reduces to the same operation as creating a diff with git diff and git applying it.

We DON'T want that. You have to use git am to get the email action going.

The -3 is for three-way merge if there's a conflict git can't resolve, and is the way I (and several other StackOverflow users, apparently) best prefer to manage conflicting patch applications. But you really shouldn't run into that much if you just worked on an existing branch.

Do make sure you're on the right branches on both boxes.


TODO: How do you get the patch to include staged files?