-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit-update-pr
executable file
·183 lines (134 loc) · 5.15 KB
/
git-update-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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#!/usr/bin/env python
import re
import os
import sys
from time import sleep
from subprocess import check_output
from subprocess import call
from subprocess import Popen
from subprocess import PIPE
from getpass import getpass
from tempfile import NamedTemporaryFile
from git import Repo
from github import Github
from github.GithubException import UnknownObjectException
import github
#github.enable_console_debug_logging()
# Approximate value of the magic length that GitHub will allow
# for the length of a new comment:
PATCH_MAX_LENGTH = 6144
PR_REGEX = re.compile("``` diff.*```", re.DOTALL)
GITHUB_TOKEN = os.path.expanduser("~/.git_pull_req_auth")
github = None
if not os.path.exists(GITHUB_TOKEN):
print 'Script requires GitHub login/password (only once)...'
user = raw_input("GitHub username: ")
pw = getpass("GitHub password: ")
github = Github(user, pw)
user = github.get_user()
print 'Creating authorization token...'
auth = user.create_authorization(
scopes=["repo"],
note="git-update-pr",
note_url="https://github.com/cozybit/cozyreview")
open(GITHUB_TOKEN, 'w').write(auth.token)
token = auth.token
else:
token = open(GITHUB_TOKEN, 'r').read()
github = Github(token)
user = github.get_user()
print 'Token resolved to GitHub username:', user.login
try:
print 'Getting repo for current directory...'
gitrepo = Repo(os.getcwd())
except:
sys.stderr.write('ERROR: Failed to find git repository\n')
sys.exit(1)
try:
print 'Finding URL of remote named \'origin\' (which must use the SSH protocol)...'
remote_url = gitrepo.config_reader().get('remote "origin"', "url")
except:
sys.stderr.write("ERROR: Failed to find remote named 'origin'\n")
sys.exit(1)
if not remote_url.startswith("[email protected]"):
sys.stderr.write("ERROR: Expected remote to start with '[email protected]'\n")
sys.exit(1)
if not remote_url.endswith(".git"):
sys.stderr.write("ERROR: Expected remote to end with '.git'\n")
sys.exit(1)
if ':' not in remote_url:
sys.stderr.write("ERROR: Expected remote contain ':'\n")
sys.exit(1)
_, orgprojgit = remote_url.split(":")
orgname, projgit = orgprojgit.split('/')
projname = projgit[:-4]
try:
org = github.get_organization(orgname)
except UnknownObjectException:
org = github.get_user(orgname)
print 'Getting repo name for:', projname
ghrepo = org.get_repo(projname)
print 'Repository found:', ghrepo.html_url
print 'Updating remote \'origin\' to find new commits...'
os.spawnvp(os.P_WAIT, "git", ["git", "remote", "update", "origin"])
active_branch_name = gitrepo.active_branch.name
print 'Using branch name for pull request:', active_branch_name
cmd = ["git", "cherry", "origin/" + active_branch_name, active_branch_name]
has_new_commits = 0 < len(check_output(cmd).splitlines())
if not ('UPR_FORCE' in os.environ and os.environ['UPR_FORCE'] == '1'):
if not has_new_commits:
sys.stderr.write("ERROR: No new commits found, aborting\n")
sys.exit(1)
print 'Finding pull request for branch name:', active_branch_name
for pr in ghrepo.get_pulls():
org_name, branch_name = pr.head.label.split(":")
if branch_name != active_branch_name:
continue
updated_patch = check_output(
["git", "format-patch", "--stdout", "origin/master"])
#["git", "format-patch", "--stdout", "origin/" + active_branch_name])
if len(updated_patch) > PATCH_MAX_LENGTH:
sys.stderr.write("***************************************\n")
sys.stderr.write("* WARNING: Patch too big, truncating! *\n")
sys.stderr.write("***************************************\n")
new_pr_diff = "``` diff\n" + updated_patch[:PATCH_MAX_LENGTH] + "\n```"
updated_pr_body = PR_REGEX.sub(new_pr_diff, pr.body)
updated_pr_body = updated_pr_body.replace("\r\n", "\n")
editor = "vi"
if 'EDITOR' in os.environ:
editor = os.environ['EDITOR']
fp, fp_orig = NamedTemporaryFile(), NamedTemporaryFile()
title = pr.title + "\n\n"
fp.write(title)
fp.write(updated_pr_body)
fp.flush()
fp.seek(0)
fp_orig.write(fp.read())
fp_orig.flush()
exit_code = os.spawnvp(os.P_WAIT, editor, [editor, fp.name])
if exit_code != 0:
sys.stderr.write("ERROR: Editor was aborted\n")
sys.exit(1)
exit_code = Popen(["diff", "-w", fp_orig.name, fp.name],
stdout=PIPE, stderr=PIPE).wait()
if exit_code == 0:
sys.stderr.write("ERROR: Pull request body not modified\n")
sys.exit(1)
fp.seek(0)
lines = fp.read().splitlines()
updated_title, updated_pr_body = lines[0], str.join("\n", lines[1:]).strip()
print 'Updating pull request, adding new issue comment with new diff (len=%d)...' % (len(updated_title+updated_pr_body),)
pr.edit(title=updated_title, body=updated_pr_body)
sleep(1)
pr.create_issue_comment(updated_pr_body)
#pr.create_issue_comment(new_pr_diff)
print
print '*** NOTE ********************************************'
print
print 'Please run:'
print '\tgit push -f origin ', active_branch_name
print
print '... to finish updating pull-request'
print
print '*****************************************************'
print