Using Magit to selectively discard changes in your git working tree
Suppose, not entirely hypothetically, that you have been hacking
around with something that uses git and you've wound up with some
code changes in your working tree that have definitely turned out
to not be what you want. If these changes are the only changes
you've made to a particular file, you can restore the file with
'git checkout
'. If all of the other changes to the file are ones
that are ready to commit, you can use Magit to selectively stage
them, commit what you've staged, and now that the
file only has unwanted changes you can use 'git checkout
' on it.
But suppose neither of these are true. The file has some other changes in it, but you're not ready to commit them. Wouldn't it be nice if you could use magit to selectively discard changes in a file, in the same sort of nice interface as selectively staging chunks? The answer is that you can, but if you are me, how you do this is not necessarily obvious from the magit manual.
When I wanted to do this recently, I searched through the manual's
table of contents for something that seemed applicable and didn't
find anything. Reverting isn't it (that involves actual commits),
and resetting is
a whole tree activity. The answer is that magit puts this in a
variant of staging and unstaging changes and does it out of
the magit status buffer, which makes a kind of sense; discarding
changes from the working tree is sort of the strong version of
unstaging them. In specific, I want the k
operation (aka
magit-discard). This works just like staging and unstaging does,
which means that you can apply it to an explicitly selected change
within a chunk as well as to a chunk or an entire file.
There's some other interesting things in magit's Applying section. If I'm reading and
testing things correctly, magit's v
operation (aka magit-reverse)
provides a mechanism to pull back old, now-deleted things; you'd
go to the commit that removed whatever it is, select the chunk or
the lines you wanted, then reverse it into your tree (restoring the
old version). It's possible that there's a simpler way to do this,
of course.
(Well, there's visiting blobs and then just copying chunks from them, but that requires finding the right revision. I may be missing a Magit log buffer feature that visits a file as of the specific commit you're looking at.)
(This is one of those entries that I write for myself, so I hopefully don't have to go through finding this magit feature again the next time I want it.)
|
|