Sometimes it gets to 4:59 on a Friday and you’ve got a bunch of files you’ve been mucking around with but don’t really want to commit. This could be because you’re just using throwaway code or because you’ve made changes to existing files that you don’t want to break.
In these circumstances, you have a few options:
Save everything, power down your machine and go home
All well and good. But what if your hard drive dies over the weekend? Or the roof leaks and your machine is a mess of mould?
Copy your files up to a shared folder
Better, but what shared folder? If you have somewhere non-tamperable on the network then fair enough: that’s a decent option.
Create a temporary branch in Git
Yeah, but we said that we didn’t want to create a commit. That’s where the idea of a scratch branch comes in.
Scratchy Scratchy
The idea of a scratch branch is to act as a temporary store. We’ll add our files to the branch and push it to a central repository, kind of like a shelveset in TFS.
When we come back after the weekend, we’ll revert the commit in a safe way to get our current state back.
We’ll start with our current, edited repository.
All clean. Let’s hack a couple of the files.
Now we’ll create a scratch branch and switch to that. Our changes will come along.
We can now add our files to the scratch branch and push them to the server.
And we can go home knowing our code is backed up.
Monday Morning
So, we’re now back in the office after the weekend and want to get our code back to the way we had it. Assuming no disaster has befallen our machine, we can start working in the current directory as normal.
First, we need to revert the last scratch commit but keep the changes that were made.
NOTE: If you’re using Cmder, it has some issues with the ^ character. You can get the same result as above using the command git reset –soft HEAD~1
You can see that our last scratch commit has been undone and our files are staged for commit.
Now you can either continue working with the files as is (this is a decent way of tracking which files you’ve changed since the scratch commit) or you can unstage everything. If we want to go back to having everything unstaged, we just reset.
And we can even switch back to master…
…and delete the scratch branch locally and from the server.