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?
Asked
Active
Viewed 2,989 times
3 Answers
15
In Magit this is available as magit-toplevel
(but I agree with
@abo-abo that it makes sense to use vc-root-dir
).

tarsius
- 25,685
- 4
- 70
- 109

Kyle Meyer
- 7,024
- 27
- 22
-
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! – Pradhan Feb 17 '15 at 21:52
9
You need vc-root-dir
. Works for more than git.

abo-abo
- 14,113
- 1
- 30
- 43
-
3Could you elaborate? I don't see a function or a package titled
vc-root-dir
. The only thing that's close isvc-root-diff
. And on avc
-related search, I find this. – Pradhan Feb 17 '15 at 21:33 -
-
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. – Pradhan Feb 17 '15 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. – phils Feb 17 '15 at 21:52
2
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.

jch
- 5,720
- 1
- 23
- 39
-
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
. – Pradhan Feb 17 '15 at 22:21 -
If the current buffer is not tracked by
vc
, thenvc-deduce-backend
returnsnil
. Does that explain it? – jch Feb 17 '15 at 22:25 -
1Ah, it does. I was running it in
ielm
and expectingvc-deduce-backend
to usedefault-directory
. Thanks! – Pradhan Feb 17 '15 at 22:35 -
git rev-parse --show-toplevel
instead ofgit rev-parse --git-dir
? – Kyle Meyer Feb 17 '15 at 21:50