Skip to content

Commit 0dee19b

Browse files
committed
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
1 parent ff33d07 commit 0dee19b

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

lua/gitlinker/git.lua

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ local M = {}
22

33
local job = require("plenary.job")
44
local path = require("plenary.path")
5+
local ssh = require("gitlinker.ssh")
56

67
-- wrap the git command to do the right thing always
78
local function git(args, cwd)
@@ -69,6 +70,8 @@ local function strip_protocol(uri, errs)
6970

7071
local stripped_uri = uri:match(protocol_schema .. "(.+)$")
7172
or uri:match(ssh_schema .. "(.+)$")
73+
or ssh.fix_hostname(uri)
74+
7275
if not stripped_uri then
7376
table.insert(
7477
errs,

lua/gitlinker/ssh.lua

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
local M = {}
2+
3+
local job = require("plenary.job")
4+
5+
-- wrap the ssh command to do the right thing always
6+
local function ssh(args)
7+
local output
8+
local p = job:new({
9+
command = "ssh",
10+
args = args,
11+
})
12+
p:after_success(function(j)
13+
output = j:result()
14+
end)
15+
p:sync()
16+
return output or {}
17+
end
18+
19+
local function as_table(data)
20+
local result = {}
21+
for _, line in ipairs(data) do
22+
for key, value in string.gmatch(line, "(%w+)%s+(.*)") do
23+
result[key] = value
24+
end
25+
end
26+
return result
27+
end
28+
29+
local function get_configuration(alias)
30+
local configuration = ssh({ "-G", alias })
31+
return as_table(configuration)
32+
end
33+
34+
local function get_hostname(alias)
35+
return get_configuration(alias)["hostname"]
36+
end
37+
38+
--- Fixes aliased remote uri using the hostname set in ssh config.
39+
-- In some cases, the user can create an alias for a given user/hostname.
40+
-- So this function replaces the aliased name with the hostname set in ssh
41+
-- config.
42+
-- @params uri Remote uri from which alias will be replaced
43+
-- @return uri with replaced alias or nil
44+
function M.fix_hostname(uri)
45+
local alias = string.match(uri, "([^:]+):.*")
46+
local hostname = get_hostname(alias)
47+
48+
if alias == hostname then
49+
return nil
50+
end
51+
52+
return string.gsub(uri, alias, hostname)
53+
end
54+
55+
return M

0 commit comments

Comments
 (0)