Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse remote host from ssh config #52

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions lua/gitlinker/git.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
55 changes: 55 additions & 0 deletions lua/gitlinker/ssh.lua
Original file line number Diff line number Diff line change
@@ -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