Encode uri component properly and apply it for branch name and also file path

This commit is contained in:
Masahiro Kasashima 2023-05-28 07:47:32 +09:00
parent 9437ab08c5
commit 30535d4c28

View file

@ -22,6 +22,12 @@ function M.trim(string)
return (string:gsub("^%s*(.-)%s*$", "%1")) return (string:gsub("^%s*(.-)%s*$", "%1"))
end end
-- url encode
-- see: https://datatracker.ietf.org/doc/html/rfc3986#section-2.3
function M.encode_uri_component(string)
return (string:gsub("[^%w_~%.%-]", function (c) return string.format("%%%02X", string.byte(c)) end))
end
-- returns a table with the host, user/org and the reponame given a github remote url -- returns a table with the host, user/org and the reponame given a github remote url
-- nil is returned when the url cannot be parsed -- nil is returned when the url cannot be parsed
function M.parse_gh_remote(url) function M.parse_gh_remote(url)
@ -77,21 +83,17 @@ end
-- Returns the current branch or commit if they are available on remote -- Returns the current branch or commit if they are available on remote
-- otherwise this will return the default branch of the repo -- otherwise this will return the default branch of the repo
function M.get_current_branch_or_commit() function M.get_current_branch_or_commit()
local core = function() local current_branch = get_current_branch()
local current_branch = get_current_branch() if current_branch ~= "HEAD" and M.is_branch_upstreamed(current_branch) then
if current_branch ~= "HEAD" and M.is_branch_upstreamed(current_branch) then return M.encode_uri_component(current_branch)
return current_branch
end
local commit_hash = get_current_commit_hash()
if current_branch == "HEAD" and M.is_commit_upstreamed(commit_hash) then
return commit_hash
end
return M.get_default_branch()
end end
return string.gsub(core(), "#", "%%23") local commit_hash = get_current_commit_hash()
if current_branch == "HEAD" and M.is_commit_upstreamed(commit_hash) then
return commit_hash
end
return M.encode_uri_component(M.get_default_branch())
end end
-- get the active buf relative file path form the .git -- get the active buf relative file path form the .git
@ -100,9 +102,13 @@ function M.get_current_relative_file_path()
local absolute_file_path = vim.api.nvim_buf_get_name(0) local absolute_file_path = vim.api.nvim_buf_get_name(0)
local git_path = vim.fn.system("git rev-parse --show-toplevel") local git_path = vim.fn.system("git rev-parse --show-toplevel")
local relative_file_path = "/" .. string.sub(absolute_file_path, git_path:len() + 1) local relative_file_path_components = M.split(string.sub(absolute_file_path, git_path:len() + 1), "/")
local encoded_components = {}
for i, path_component in pairs(relative_file_path_components) do
table.insert(encoded_components, i, M.encode_uri_component(path_component))
end
return relative_file_path return "/" .. table.concat(encoded_components, '/')
end end
-- get the line number in the buffer -- get the line number in the buffer