Skip to content

Instantly share code, notes, and snippets.

@LemonBoy
Last active August 29, 2015 14:18
Show Gist options
  • Save LemonBoy/4b61b5ccaba2001f4ad4 to your computer and use it in GitHub Desktop.
Save LemonBoy/4b61b5ccaba2001f4ad4 to your computer and use it in GitHub Desktop.
Find the project root
let s:has_git = executable('git')
fun! s:find_root()
let cvs_dir = ['.git', '.hg', '.svn', '.bzr', '_darcs']
let dir = getcwd()
let depth = 10
if !exists('g:root_cache')
let g:root_cache = []
endif
for root in g:root_cache
if root == dir[:strlen(root) - 1]
return root
endif
endfor
" Shortcut for git, this way we don't have to descend into the rabbit hole
if s:has_git
:silent let ret = system('git rev-parse --git-dir')
if v:shell_error == 0
" git is nice enough to return the full path, unless we already are at the project root
let tmp = (ret == '.git') ? getcwd() : substitute(ret, '/\.git\n$', '', '')
call add(g:root_cache, tmp)
return tmp
endif
endif
" Try to find a vcs dir and assume it's the project root
while depth > 0 && dir != '/home'
for t in cvs_dir
if getfsize(dir . '/' . t) == 0
" Cache the result
call add(g:root_cache, dir)
return dir
endif
endfor
" Don't descend too much into the rabbit hole
let depth -= 1
" Go back in the folder hierarchy
let last_slash = strridx(dir, '/') - 1
let dir = dir[0:last_slash]
endwhile
return getcwd()
endf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment