diff --git a/lua/gitlinker.lua b/lua/gitlinker.lua index ad46cd09..46befc14 100644 --- a/lua/gitlinker.lua +++ b/lua/gitlinker.lua @@ -100,7 +100,7 @@ local function get_buf_range_url_data(mode, user_opts) end return vim.tbl_extend("force", repo_url_data, { - rev = rev, + rev = repo_url_data.rev or rev, file = buf_repo_path, lstart = range.lstart, lend = range.lend, diff --git a/lua/gitlinker/git.lua b/lua/gitlinker/git.lua index 404f3381..653d3ac7 100644 --- a/lua/gitlinker/git.lua +++ b/lua/gitlinker/git.lua @@ -238,6 +238,31 @@ function M.get_closest_remote_compatible_rev(remote) return nil end +local function get_remote_branch(remote) + local errs = { + string.format("Failed to retrieve remote branch for remote '%s'", remote), + } + local symRef + local p = job:new({ + command = "git", + args = { "symbolic-ref", "-q", "HEAD" }, + }) + p:after_success(function(j) + symRef = j:result()[1] + end) + p:sync() + local trackingBranch + local p = job:new({ + command = 'git', + args = { 'for-each-ref', '--format=%(upstream:short)', symRef }, + }) + p:after_success(function(j) + trackingBranch = (j:result()[1]):match(remote .. '/(.+)$') + end) + p:sync() + return trackingBranch or 'origin/master' +end + function M.get_repo_data(remote) local errs = { string.format("Failed to retrieve repo data for remote '%s'", remote), @@ -255,6 +280,12 @@ function M.get_repo_data(remote) if not repo or vim.tbl_isempty(repo) then vim.notify(table.concat(errs), vim.log.levels.Error) end + + local branch = get_remote_branch(remote) + if branch then + repo.rev = branch + end + return repo end diff --git a/lua/gitlinker/hosts.lua b/lua/gitlinker/hosts.lua index 1d405050..88859b88 100644 --- a/lua/gitlinker/hosts.lua +++ b/lua/gitlinker/hosts.lua @@ -11,9 +11,12 @@ end --- Constructs a github style url function M.get_github_type_url(url_data) local url = M.get_base_https_url(url_data) - if not url_data.file or not url_data.rev then + if not url_data.file and not url_data.rev then return url end + if not url_data.file and url_data.rev then + return url .. "/tree/" .. url_data.rev + end url = url .. "/blob/" .. url_data.rev .. "/" .. url_data.file if not url_data.lstart then