From 7fdac5e4b433482ce1a27b80f80a8c5e501390a9 Mon Sep 17 00:00:00 2001 From: "Ricardo B. Marliere" Date: Tue, 17 Dec 2024 18:19:50 -0300 Subject: [PATCH 1/2] fix: Don't use short refname in has_branch() If there is a tag with the same name, git will prepend "heads/" to the branch name. --- lua/git-worktree/git.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/git-worktree/git.lua b/lua/git-worktree/git.lua index c245bfe..8a021db 100644 --- a/lua/git-worktree/git.lua +++ b/lua/git-worktree/git.lua @@ -113,7 +113,7 @@ end function M.has_branch(branch, opts, cb) local found = false - local args = { 'branch', '--format=%(refname:short)' } + local args = { 'branch', '--format=%(refname)' } opts = opts or {} for _, opt in ipairs(opts) do args[#args + 1] = opt @@ -123,7 +123,8 @@ function M.has_branch(branch, opts, cb) command = 'git', args = args, on_stdout = function(_, data) - found = found or data == branch + local current = data:match('^refs/heads/(.+)') or data:match('^refs/remotes/(.+)') + found = found or current == branch end, cwd = vim.loop.cwd(), } From 42a90816535d1f977866e1d0dc80dc18c2f63cb6 Mon Sep 17 00:00:00 2001 From: "Ricardo B. Marliere" Date: Tue, 17 Dec 2024 19:01:23 -0300 Subject: [PATCH 2/2] fix: Use new current_branch() in worktree deletion Using rev-parse is not fail proof when dealing with ambiguous ref names. --- lua/git-worktree/git.lua | 23 +++++++++++++++++++++++ lua/git-worktree/worktree.lua | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/lua/git-worktree/git.lua b/lua/git-worktree/git.lua index 8a021db..1a99aed 100644 --- a/lua/git-worktree/git.lua +++ b/lua/git-worktree/git.lua @@ -278,6 +278,29 @@ function M.parse_head(path) return table.concat(stdout, '') end +--- @param path string +--- @return string|nil +function M.current_branch(path) + local job = Job:new { + command = 'git', + args = { 'branch', '--show-current' }, + cwd = path, + on_start = function() + Log.debug('git branch --show-current') + end, + } + + local stdout, code = job:sync() + if code ~= 0 then + Log.error( + 'Error in getting current branch: code:' .. tostring(code) .. ' out: ' .. table.concat(stdout, '') .. '.' + ) + return nil + end + + return table.concat(stdout, '') +end + --- @param branch string --- @return Job|nil function M.delete_branch_job(branch) diff --git a/lua/git-worktree/worktree.lua b/lua/git-worktree/worktree.lua index aeb93c4..819243e 100644 --- a/lua/git-worktree/worktree.lua +++ b/lua/git-worktree/worktree.lua @@ -169,7 +169,7 @@ function M.delete(path, force, opts) opts = {} end - local branch = Git.parse_head(path) + local branch = Git.current_branch(path) Git.has_worktree(path, nil, function(found) if not found then