Skip to content

Instantly share code, notes, and snippets.

@dialtone
Created January 24, 2012 06:49
Show Gist options
  • Save dialtone/1668484 to your computer and use it in GitHub Desktop.
Save dialtone/1668484 to your computer and use it in GitHub Desktop.
Find root of a project given some markers
function! s:findroot(curr, markers, depth)
" Search all markers in the current directory
for marker in a:markers
let found = !empty(globpath(a:curr, marker))
if !found && a:depth > 40
return ''
endif
if found
return a:curr
endif
endfor
" Increase depth
let depth = a:depth + 1
" get the parent and recurse
let parent = s:getparent(a:curr)
if parent != a:curr
return s:findroot(parent, a:markers, depth)
endif
endfunction
function! s:getparent(item)
let parent = substitute(a:item, '[\/][^\/]\+[\/:]\?$', '', '')
if parent == '' || match(parent, '[\/]') < 0
let parent .= '/'
endif
return parent
endf
function g:projectRoot(path)
let markers = ['root.dir','.git/','.hg/','_darcs/','.bzr/']
let root = s:findroot(a:path, markers, 0)
if root == ''
return path
endif
return fnameescape(root)
endf
if has("autocmd")
" This calls projectRoot and sets it to the root of the file currently open
au BufEnter * silent! exec "lcd ".g:projectRoot(expand("%:p:h"))
endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment