How can I get the root directory of the current git repo? I could run shell-command-to-string
on something like git rev-parse --show-toplevel
. Is there a better way? Does magit
or any other git front-end expose this info?
3 Answers
In Magit this is available as magit-toplevel
(but I agree with
@abo-abo that it makes sense to use vc-root-dir
).
-
vc-root-dir
is surely the most generic. However, I am unable to get it to work in that form as I mentioned in the comments on @abo-abo's answer. But this one worked straight. Thanks!– PradhanFeb 17, 2015 at 21:52
You need vc-root-dir
. Works for more than git.
-
3
-
-
Perhaps my
vc
is too old? I have the one built-in with emacs 24.3. I don't seevc-root
invc.el
or withapropos
etc. Looking atvc.el
, I see things like(setq rootdir (vc-call-backend...))
. And indeed,(vc-call-backend 'Git 'root default-directory)
works.– PradhanFeb 17, 2015 at 21:50 -
1n.b. I think
vc-root-dir
is only in trunk at this stage. It's certainly not in 24.4. Presumably it will be available in Emacs 25.– philsFeb 17, 2015 at 21:52
As mentioned by abo-abo, in Emacs 25, there is a function called vc-root-dir
that does what you need in a backend-agnostic manner. For earlier versions of Emacs, the following is a suitable replacement:
(defun vc-root-dir ()
(let ((backend (vc-deduce-backend)))
(and backend
(ignore-errors
(vc-call-backend backend 'root default-directory)))))
As mentioned by Kyle, Magit provides the function magit-get-top-dir
, which simply calls git rev-parse --show-cdup
and interprets the result.
-
1Indeed, after looking at the implementation of
vc-root-diff
, I triedvc-deduce-backend
. Somehow, that returnsnil
in my git-repo. However,vc-responsible-backend default-directory
returnsGit
.– PradhanFeb 17, 2015 at 22:21 -
If the current buffer is not tracked by
vc
, thenvc-deduce-backend
returnsnil
. Does that explain it?– jchFeb 17, 2015 at 22:25 -
1Ah, it does. I was running it in
ielm
and expectingvc-deduce-backend
to usedefault-directory
. Thanks!– PradhanFeb 17, 2015 at 22:35 -
git rev-parse --show-toplevel
instead ofgit rev-parse --git-dir
?