Skip to content

Commit

Permalink
retrieve work tree correctly even if CWD is in git-dir (fix rhysd#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
rhysd committed Feb 20, 2018
1 parent cabf820 commit 0f57324
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions autoload/committia/git.vim
Original file line number Diff line number Diff line change
Expand Up @@ -44,21 +44,43 @@ function! s:search_git_dir_and_work_tree() abort
let matched = matchlist(expand('%:p'), '[\\/]\.git[\\/]\%(\(modules\|worktrees\)[\\/].\+[\\/]\)\?\%(COMMIT_EDITMSG\|MERGE_MSG\)$')
if len(matched) > 1
let git_dir = expand('%:p:h')

if matched[1] ==# 'worktrees'
" Note:
" This was added in #31. I'm not sure that the format of gitdir file
" is fixed. Anyway, it works for now.
let work_tree = fnamemodify(readfile(git_dir . '/gitdir')[0], ':h')
else
let work_tree = s:extract_first_line(s:system(printf('%s --git-dir="%s" rev-parse --show-toplevel', g:committia#git#cmd, escape(git_dir, '\'))))
" TODO: Handle command error
return [git_dir, work_tree]
endif

" Avoid executing Git command in git-dir because `git rev-parse --show-toplevel`
" does not return the repository root. To handle work-tree properly,
" set $CWD to the parent of git-dir, which is outside of the
" git-dir. (#39)
let cwd_saved = getcwd()
let cwd = fnamemodify(git_dir, ':h')
if cwd_saved !=# cwd
execute 'lcd' cwd
endif
try
let cmd = printf('%s --git-dir="%s" rev-parse --show-toplevel', g:committia#git#cmd, escape(git_dir, '\'))
let out = s:system(cmd)
if s:error_occurred()
throw "Failed to execute 'git rev-parse --show-cdup': " . out
endif
finally
if cwd_saved !=# getcwd()
execute 'lcd' cwd_saved
endif
endtry

let work_tree = s:extract_first_line(out)
return [git_dir, work_tree]
endif

let output = s:system(g:committia#git#cmd . ' rev-parse --show-cdup')
if s:error_occurred()
throw "Failed to execute 'git rev-parse': " . output
throw "Failed to execute 'git rev-parse --show-cdup': " . output
endif
let root = s:extract_first_line(output)

Expand Down Expand Up @@ -97,7 +119,7 @@ function! s:execute_git(cmd) abort
endfunction

function! s:ensure_index_file(git_dir) abort
if $GIT_INDEX_FILE != ''
if $GIT_INDEX_FILE !=# ''
return 0
endif

Expand Down

0 comments on commit 0f57324

Please sign in to comment.