-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy-git-permalink
More file actions
executable file
·79 lines (60 loc) · 2.3 KB
/
Copy pathcopy-git-permalink
File metadata and controls
executable file
·79 lines (60 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3
import argparse
import subprocess
import re
from pathlib import Path
def get_revision() -> str:
return subprocess.check_output(
("git", "rev-parse", "HEAD"), text=True, stderr=subprocess.DEVNULL
).strip()
def lookup_hostname(hostname: str) -> str:
ssh_config = (Path.home() / ".ssh" / "config").read_text()
current_host: str | None = None
hostname_map: dict[str, str] = {}
for line in ssh_config.splitlines():
if line.startswith("Host"):
current_host = line.split(" ")[1].strip()
elif not line.startswith(" "):
# We're at the end of a block,
# and so whatever `Host` we've found
# is now invalid.
current_host = None
if not current_host:
continue
line = line.strip()
if line.startswith("HostName"):
hostname_map[current_host] = line.split(" ")[1].strip()
return hostname_map[hostname]
SSH_URL_RE = re.compile(r"^git@(?P<url>[^:]+):(?P<repo_name>.+?)(\.git)?$")
def get_remote_url() -> str:
url = subprocess.check_output(
("git", "remote", "get-url", "origin"), text=True, stderr=subprocess.DEVNULL
).strip()
if url.startswith("http://") or url.startswith("https://"):
return url
match = SSH_URL_RE.match(url)
if match is None:
raise ValueError(f"Invalid SSH URL: {url}")
match_url = lookup_hostname(match["url"])
match_repo_name = match["repo_name"]
return f"https://{match_url}/{match_repo_name}"
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("buffer_name")
parser.add_argument("selection_start")
parser.add_argument("selection_end")
namespace = parser.parse_args()
buffer_name: str = namespace.buffer_name
selection_end = int(namespace.selection_end)
selection_start = int(namespace.selection_start)
remote_url = get_remote_url()
revision = get_revision()
if selection_start == selection_end:
selection = f"L{selection_start}"
else:
selection = f"L{selection_start}-L{selection_end}"
permalink = f"{remote_url}/blob/{revision}/{buffer_name}#{selection}"
copy = subprocess.Popen(("pbcopy"), stdin=subprocess.PIPE, text=True)
_ = copy.communicate(permalink)
if __name__ == "__main__":
main()