Skip to content

Instantly share code, notes, and snippets.

@jamescherti
Last active December 25, 2022 22:06
Show Gist options
  • Save jamescherti/c36c975aad4802a0e47a4a8274d55684 to your computer and use it in GitHub Desktop.
Save jamescherti/c36c975aad4802a0e47a4a8274d55684 to your computer and use it in GitHub Desktop.
Vim: Return the Git root directory / folder (Git top level).
" Language: Vim script
" Author: James Cherti
" URL: https://gist.github.com/jamescherti/c36c975aad4802a0e47a4a8274d55684
" License: MIT
" Description: Return the Git root directory / folder (Git top level).
" let toplevel = GitRootDir()
" let toplevel = GitRootDir("/path/to/dir")
function! GitRootDir(...) abort
if len(a:000) > 0
let l:dir = a:000[0]
else
let l:dir = getcwd()
endif
let l:gitdir = systemlist('git -C ' . shellescape(l:dir) .
\ ' rev-parse --show-toplevel')
if len(l:gitdir) > 0 && isdirectory(l:gitdir[0])
return l:gitdir[0]
endif
return ''
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment