Magit revert single file
Asked Answered
S

2

89

The question is about Magit major mode for Emacs function and less so about how to do this via command line interface.

I only have a local Git repository. How would I restore a selected file to its previous version? I believe that the Git command for this must be something like git checkout HEAD^ path/to/file but I may be wrong here too, just guessing really.

What I'm looking for is essentially the same thing as C-x v u in vc-dir buffer.

Essentially, what I was hoping to do was:

  • delete the modified file.

  • pull from local repo.

But Magit doesn't seem to be able to do that, it seems to prefer to just delete the file, instead of restoring it.

Sybille answered 16/6, 2013 at 9:4 Comment(2)
(1) Magit history buffer definitely supports that (although I don't remember how), do you need some other means (e.g. in *magit-status*)? (2) If you only want to revert to base, why not use the vc minor mode C-x v u?Feltner
Are you talking about discarding uncommitted changes (i.e. reverting to the currently-committed version), or reverting back to a prior commit? git checkout HEAD file would discard uncommitted changes. git checkout HEAD^ file would also revert changes (if any) made to the file in the most recent commit to the repository. If that commit did not involve the file in question, then the ^ is effectively redundant. Going by your "delete and pull" summary, you just want to discard uncommitted changes, in which case Rémi's answer is the one you want.Lordly
I
102

To discard a modification in magit you just have to go on the hunk or file you want to revert, and use M-x magit-discard which is bound to k with the default keybindings. See the relevant documentation at https://magit.vc/manual/magit/Applying.html for more detail.

Iolenta answered 16/6, 2013 at 13:47 Comment(2)
The action depend on where you use it. It will delete the file if the file is not tracked by git. But if the file is tracked, it discard the modification. Note that once your file is in git, it's hard to fully delete it from history.Preiser
I think it quite reasonably can also be used in reverse, after commit: if you have committed the file together with other changes, you can revert with v, and then k the inverse changes where you want to preserve the changes.Feltner
I
43

With the file open, you can M-x magit-file-checkout.

Incongruity answered 4/4, 2016 at 19:32 Comment(5)
which version of emacs/magit?Soapy
Available since Magit 2.3.0.Incongruity
magit-checkout-file is deprecated, use magit-file-checkout instead.Rowell
This is a nice addition but also a lot of prompting. I was wondering if there is a way to use the fie at point and default to HEADOospore
@AndreaRichiardi with M-x magit-file-checkout you can use HEAD and HEAD~~ (2 revisions back) and HEAD^10 (10 revisions back).Arithmetician

© 2022 - 2024 — McMap. All rights reserved.