diff --git a/lua/openingh/init.lua b/lua/openingh/init.lua index 4a02daa..3bcbccd 100644 --- a/lua/openingh/init.lua +++ b/lua/openingh/init.lua @@ -12,12 +12,14 @@ function M.setup() return end - -- init global variables - local username_and_reponame = utils.get_username_reponame(repo_url) - M.username = username_and_reponame.username - M.reponame = username_and_reponame.reponame - M.gh_url = "https://github.com/" - M.repo_url = M.gh_url .. M.username .. "/" .. M.reponame + local gh = utils.parse_gh_remote(repo_url) + if gh == nil then + print("Error parsing GitHub remote URL") + vim.g.openingh = false + return + end + + M.repo_url = string.format("https://%s/%s/%s", gh.host, gh.user_or_org, gh.reponame) end function M.openFile() diff --git a/lua/openingh/utils.lua b/lua/openingh/utils.lua index 82b7f7f..90f2a0d 100644 --- a/lua/openingh/utils.lua +++ b/lua/openingh/utils.lua @@ -16,27 +16,23 @@ function M.trim(string) return (string:gsub("^%s*(.-)%s*$", "%1")) end --- returns the username and the reponame form the origin url in a table -function M.get_username_reponame(url) - -- ssh has an @ in the url - if string.find(url, "@") then - local splitted_user_repo = M.split(url, ":")[2] - local splitted_username_and_reponame = M.split(splitted_user_repo, "/") - local username_and_reponame = { - username = splitted_username_and_reponame[1], - reponame = M.trim(string.gsub(splitted_username_and_reponame[2], ".git", "")), - } +-- 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 +function M.parse_gh_remote(url) + -- 3 capture groups for host, org/user and repo. whitespace is trimmed + -- when cloning with http://, gh redirects to https://, but remote stays http + local http = { string.find(url, "https?://([^/]*)/([^/]*)/([^%s/]*)") } + -- ssh url can be of type: + -- git@some.github.com:user_or_org/reponame.git + -- ssh://git@some.github.com/user_or_org/reponame.git + -- .* is used for ssh:// since lua matching doesn't support optional groups, only chars + local ssh = { string.find(url, ".*git@(.*)[:/]([^/]*)/([^%s/]*)") } - return username_and_reponame - else - local splitted_username_and_reponame = M.split(url, "/") - local username_and_reponame = { - username = splitted_username_and_reponame[3], - reponame = M.trim(string.gsub(splitted_username_and_reponame[4], ".git", "")), - } + local matches = http[1] == nil and ssh or http + if matches[1] == nil then return nil end - return username_and_reponame - end + local _, _, host, user_or_org, reponame = unpack(matches) + return { host = host, user_or_org = user_or_org, reponame = string.gsub(reponame, ".git", "") } end -- get the remote default branch