-
Notifications
You must be signed in to change notification settings - Fork 0
/
gh-checkout-pr
executable file
·169 lines (149 loc) · 5.42 KB
/
gh-checkout-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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#!/usr/bin/python3
import unicodedata
import argparse
import textwrap
from datetime import datetime
import re
import sys
import json
import os
import subprocess
prog_description = """\
Checkout to the selected PR
# To checkout to the PR with specified number.
gh checkout-pr \$number
# To checkout to the PR by searching name.
gh checkout-pr \$title
"""
RESET, RED, GREEN, MAGENTA = 0, 31, 32, 35
STATE_COLOR = {
'MERGED': MAGENTA,
'CLOSED': RED,
}
PR_LIST_TEMPLATE = '\x1b[31m({idx}) \x1b[{color}m{title} \x1b[0m#{number} ({timeago})'
PR_CONTENT_TEMPLATE = """
\x1b[1;{color}m{title} \x1b[0m(#{number})
{timeago}
{body}
"""
def parse_args():
parser = argparse.ArgumentParser(description=prog_description)
parser.add_argument('args', nargs='*', type=str, help='')
parser.add_argument('--number', '-n', type=int, help='')
parser.add_argument('--search', '-s', type=str, nargs='+', help='')
parser.add_argument('--base', type=str, help='')
args = parser.parse_args()
if len(args.args) == 1 and str(args.args[0]).isdecimal():
args.number = args.args[0]
elif len(args.args) > 0:
args.search = args.args
return args
def display_len(text):
text = re.sub(r"\x1b\[(\d*;)*(\d*)m", "", text)
length = len(text)
for char in text:
if unicodedata.east_asian_width(char) in ['W', 'F']:
length += 1
return length
def print_pr_content(title, number, state, body, updatedAt, **kwargs):
color = STATE_COLOR.get(state, GREEN)
timeago = pretty_date(datetime.strptime(updatedAt, '%Y-%m-%dT%H:%M:%SZ'))
lines = PR_CONTENT_TEMPLATE.format(color=color,
number=number,
title=title,
timeago=timeago,
body=body).split('\n')
terminal_width = min(os.get_terminal_size().columns, 120)
print('╭' + '─' * (terminal_width - 3) + '╮')
for line in lines:
wrapped_text = textwrap.wrap(line,
width=terminal_width - 3,
drop_whitespace=False)
for text in wrapped_text:
fill = terminal_width - 3 - display_len(text)
print('│' + text + ' ' * fill + '│')
print('╰' + '─' * (terminal_width - 3) + '╯')
def pretty_date(time: datetime):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
now = datetime.utcnow()
diff = now - time
second_diff = diff.seconds
day_diff = diff.days
if day_diff < 0:
return ''
if day_diff == 0:
if second_diff < 10:
return "刚刚"
if second_diff < 60:
return str(second_diff) + " 秒前"
if second_diff < 3600:
return str(second_diff // 60) + " 分钟前"
if second_diff < 86400:
return str(second_diff // 3600) + " 小时前"
if day_diff < 7:
return str(day_diff) + " 天前"
if day_diff < 31:
return str(day_diff // 7) + " 周前"
if day_diff < 365:
return str(day_diff // 30) + " 月前"
return str(day_diff // 365) + " 年前"
def main():
args = parse_args()
if args.number is not None:
pr_number = int(args.number)
p = subprocess.Popen(
['gh', 'pr', 'view',
str(pr_number), '--json', 'number,title,state,body,headRefName,updatedAt,headRepositoryOwner'],
stdout=subprocess.PIPE,
)
pr_content = json.loads(p.stdout.read())
else:
command = [
'gh', 'pr', 'list', '--json',
'number,title,state,body,headRefName,updatedAt,headRepositoryOwner',
'--state', 'all'
]
if args.search is not None:
command.extend(
['--search', 'in:title {}'.format(' '.join(args.search))])
if args.base is not None:
command.extend(['--base', args.base])
p = subprocess.Popen(command, stdout=subprocess.PIPE)
pr_list = json.loads(p.stdout.read())
if len(pr_list) == 0:
print('Not found available PR.')
sys.exit(1)
for i, pr in enumerate(reversed(pr_list)):
idx = len(pr_list) - i
color = STATE_COLOR.get(pr['state'], GREEN)
print(
PR_LIST_TEMPLATE.format(
idx=idx,
color=color,
number=pr['number'],
title=pr['title'],
timeago=pretty_date(
datetime.strptime(pr['updatedAt'], '%Y-%m-%dT%H:%M:%SZ')),
))
try:
index = int(input("Please select the PR to checkout: ")) - 1
except KeyboardInterrupt:
return
except ValueError:
print('Invalid input.')
return
pr_content = pr_list[index]
print_pr_content(**pr_content)
confirm = str(input('\nCheckout to the branch? (Y / n)'))
if confirm.lower() in ['y', '']:
if pr_content['headRepositoryOwner']['login'] == 'mzr1996':
branch_name = pr_content["headRefName"]
else:
branch_name = f'pr{pr_content["number"]}/{pr_content["headRefName"]}'
subprocess.Popen(['gh', 'pr', 'checkout', str(pr_content['number']), '-b', branch_name]).communicate()
if __name__ == "__main__":
main()