From c8f04b1d992a84f2f5dbac8fdf286c902fedb730 Mon Sep 17 00:00:00 2001 From: Joao P Dubas Date: Sat, 19 Feb 2022 19:19:04 -0300 Subject: [PATCH] feat: parse remote uri with aliased hostname In some situations the user can set a Host rule in [ssh config][0], where the Host and Hostname differ. To avoid problems in this scenario a `ssh` module was create to fix the hostname configured in the remote uri. [0]: https://www.man7.org/linux/man-pages/man5/ssh_config.5.html --- lua/gitlinker/git.lua | 3 +++ lua/gitlinker/ssh.lua | 55 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 lua/gitlinker/ssh.lua diff --git a/lua/gitlinker/git.lua b/lua/gitlinker/git.lua index 43522e41..22659985 100644 --- a/lua/gitlinker/git.lua +++ b/lua/gitlinker/git.lua @@ -2,6 +2,7 @@ local M = {} local job = require("plenary.job") local path = require("plenary.path") +local ssh = require("gitlinker.ssh") -- wrap the git command to do the right thing always local function git(args, cwd) @@ -69,6 +70,8 @@ local function strip_protocol(uri, errs) local stripped_uri = uri:match(protocol_schema .. "(.+)$") or uri:match(ssh_schema .. "(.+)$") + or ssh.fix_hostname(uri) + if not stripped_uri then table.insert( errs, diff --git a/lua/gitlinker/ssh.lua b/lua/gitlinker/ssh.lua new file mode 100644 index 00000000..e740e147 --- /dev/null +++ b/lua/gitlinker/ssh.lua @@ -0,0 +1,55 @@ +local M = {} + +local job = require("plenary.job") + +-- wrap the ssh command to do the right thing always +local function ssh(args) + local output + local p = job:new({ + command = "ssh", + args = args, + }) + p:after_success(function(j) + output = j:result() + end) + p:sync() + return output or {} +end + +local function as_table(data) + local result = {} + for _, line in ipairs(data) do + for key, value in string.gmatch(line, "(%w+)%s+(.*)") do + result[key] = value + end + end + return result +end + +local function get_configuration(alias) + local configuration = ssh({ "-G", alias }) + return as_table(configuration) +end + +local function get_hostname(alias) + return get_configuration(alias)["hostname"] +end + +--- Fixes aliased remote uri using the hostname set in ssh config. +-- In some cases, the user can create an alias for a given user/hostname. +-- So this function replaces the aliased name with the hostname set in ssh +-- config. +-- @params uri Remote uri from which alias will be replaced +-- @return uri with replaced alias or nil +function M.fix_hostname(uri) + local alias = string.match(uri, "([^:]+):.*") + local hostname = get_hostname(alias) + + if alias == hostname then + return nil + end + + return string.gsub(uri, alias, hostname) +end + +return M