-
Notifications
You must be signed in to change notification settings - Fork 0
/
open-pr
executable file
·94 lines (65 loc) · 2.46 KB
/
open-pr
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env python
import argparse
import re
import sys
import subprocess
import webbrowser
def fetch_remote(path):
remote_parser = re.compile(r"^(?P<name>\w+)\s(?P<url>.+)\s(\(fetch\)|\(push\))")
try:
output = subprocess.check_output(["git", "-C", path, "remote", "-v"]).decode("utf-8")
except subprocess.CalledProcessError:
sys.exit(0)
lines = output.split("\n")
lines = [line for line in lines if line]
remotes = []
for line in lines:
parsed_line = remote_parser.match(line)
if parsed_line:
remotes.append((parsed_line.group("name"), parsed_line.group("url")))
remotes = set(remotes)
return {remote: url for remote, url in remotes}
def get_branch():
try:
return subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]).decode("utf-8").strip()
except subprocess.CalledProcessError:
sys.exit(0)
def get_remote(args):
remotes = fetch_remote(args["path"])
if remotes.get(args["remote"]):
return remotes[args["remote"]]
elif remotes.get("origin"):
return remotes["origin"]
elif len(remotes.keys()) <= 1:
for value in remotes.values():
return value
break
else:
print("No remotes found")
sys.exit(0)
def format_remote(remote):
match = None
if remote is None:
print("Invalid remote")
sys.exit(0)
elif remote.startswith("https://"): # avoid having to potentially use both regexs
match = re.match(r"^https://(?P<domain>\w+.\w+)/(?P<username>.+)/(?P<repository>.+).git$", remote)
else:
match = re.match(r"^git@(?P<domain>\w+.\w+):(?P<username>.+)/(?P<repository>.+).git$", remote)
if not match:
print("Could not parse remote url")
sys.exit(0)
return "http://{domain}/{username}/{repository}".format(**match.groupdict())
def parse_args():
parser = argparse.ArgumentParser(description="A command line utility for opening a repositories remote homepage.")
parser.add_argument("-r", "--remote", required=False, help="remote to open. default: origin")
parser.add_argument("path", nargs="?", default=".", help="path to local repository, defaults to '.'")
args = parser.parse_args()
return vars(args)
def main():
args = parse_args()
remote = get_remote(args)
url = format_remote(remote)
branch = get_branch()
webbrowser.open("{url}/pull/{branch}".format(url=url, branch=branch))
main()