16

I've got a file foo.txt in branch A, and I want to check out foo.txt from branch B into the index. On the command line, I would do this:

$ git checkout B -- foo.txt

I want to be able to do this in magit by going to log, finding the commit I'm interested in (e.g l o B), finding foo.txt, and running some command, but I can't figure out how to do it.

20

As of magit 2.11.0 this is possible directly from the reset dispatcher (X f and you may specify the revision and file):

enter image description here

This can be done programmatically within magit using magit-file-checkout which accepts a version spec and the filename (thanks to @Emoses' feature request and @Kyle Meyer's implementation). Previously the function was named magit-checkout-file (from v2.3.0 - v2.9.0).

  • 3
    magit-checkout-file is now obsolete. Use magit-file-checkout instead. – Sagar Jha Apr 26 '17 at 14:06
3

I'm not aware of a builtin way to do this.

Assuming you're on branch A, another approach would be to diff branch B (d r ..B), and then move point to the file you're interested in. Pressing a will apply those changes to the working tree (rather than the index).

I have a command in my configuration to reset or checkout a file from a revision, but, in its current state, it doesn't fit exactly what you're asking for because it won't offer a good revision default when in Magit Revision mode.

(defun km/magit-reset-file (rev file &optional checkout)
  "Reset FILE from revision REV.

If prefix argument CHECKOUT is non-nil, checkout FILE from REV
instead.

\(git reset REV -- FILE)
\(git checkout REV -- FILE)"
  (interactive
   (let ((rev (magit-read-branch-or-commit "Revision")))
     (list rev (magit-read-file-from-rev rev "File") current-prefix-arg)))
  (magit-with-toplevel
    (magit-run-git (if checkout "checkout" "reset")
                   rev "--" file)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.