Skip to content

Commit

Permalink
fix: do not pick a remote arbitrarily
Browse files Browse the repository at this point in the history
  • Loading branch information
ruifm committed Oct 18, 2021
1 parent c4f49ad commit 3f29108
Showing 1 changed file with 49 additions and 19 deletions.
68 changes: 49 additions & 19 deletions lua/gitlinker/git.lua
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,19 @@ local function get_rev(revspec)
return rev
end

local function get_rev_name(revspec)
local rev
local p = job:new({
command = "git",
args = { "rev-parse", "--abbrev-ref", revspec },
})
p:after_success(function(j)
rev = j:result()[1]
end)
p:sync()
return rev
end

function M.is_file_in_rev(file, revspec)
local is_in_rev = false
local p = job:new({
Expand Down Expand Up @@ -268,30 +281,47 @@ function M.get_branch_remote()
return remotes[1]
end

local upstream_branch = get_rev_name("@{u}")
if not upstream_branch then
vim.notify(
[[
Multiple remotes available and all of them can be used.
Either set up a tracking remote tracking branch by creating one your
current branch (git push -u) or set an existing one
(git branch --set-upstream-to=<remote>/<branch>).
Otherwise, choose one of them using
require'gitlinker'.setup({opts={remote='<remotename>'}}).
]],
vim.log.levels.Warning
)
return nil
end

local remote_from_upstream_branch = upstream_branch:match(
"^(" .. allowed_chars .. ")%/"
)
if not remote_from_upstream_branch then
error(
string.format(
"Could not parse remote name from remote branch '%s'",
upstream_branch
)
)
return nil
end
for _, remote in ipairs(remotes) do
-- try upstream branch HEAD (a.k.a @{u})
local upstream_revspec = "@{u}"
if
get_rev(upstream_revspec)
and is_rev_in_remote(upstream_revspec, remote)
then
if remote_from_upstream_branch == remote then
return remote
end

-- try HEAD and last 50 parent commits
for i = 0, 50 do
local revspec = "HEAD~" .. i
if is_rev_in_remote(revspec, remote) then
return remote
end
end
end

error([[
Multiple remotes available and all of them can be used.
Please choose one of them using
require'gitlinker'.setup({opts={remote='<remotename>'}})
]])
error(
string.format(
"Parsed remote '%s' from remote branch '%s' is not a valid remote",
remote_from_upstream_branch,
upstream_branch
)
)
return nil
end

Expand Down

0 comments on commit 3f29108

Please sign in to comment.