Skip to content

Commit 191bc20

Browse files
committed
BLD: add merge-pr.py script
1 parent 431923f commit 191bc20

File tree

1 file changed

+283
-0
lines changed

1 file changed

+283
-0
lines changed

merge-py.py

+283
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,283 @@
1+
#!/usr/bin/env python
2+
3+
#
4+
# Licensed to the Apache Software Foundation (ASF) under one or more
5+
# contributor license agreements. See the NOTICE file distributed with
6+
# this work for additional information regarding copyright ownership.
7+
# The ASF licenses this file to You under the Apache License, Version 2.0
8+
# (the "License"); you may not use this file except in compliance with
9+
# the License. You may obtain a copy of the License at
10+
#
11+
# http://www.apache.org/licenses/LICENSE-2.0
12+
#
13+
# Unless required by applicable law or agreed to in writing, software
14+
# distributed under the License is distributed on an "AS IS" BASIS,
15+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
# See the License for the specific language governing permissions and
17+
# limitations under the License.
18+
#
19+
20+
# Utility for creating well-formed pull request merges and pushing them to Apache.
21+
# usage: ./apache-pr-merge.py (see config env vars below)
22+
#
23+
# Lightly modified from version of this script in incubator-parquet-format
24+
25+
from __future__ import print_function
26+
27+
from requests.auth import HTTPBasicAuth
28+
import requests
29+
30+
import os
31+
import six
32+
import subprocess
33+
import sys
34+
import textwrap
35+
36+
PANDAS_HOME = '.'
37+
PROJECT_NAME = 'pandas'
38+
print("PANDAS_HOME = " + PANDAS_HOME)
39+
40+
# Remote name with the PR
41+
PR_REMOTE_NAME = os.environ.get("PR_REMOTE_NAME", "upstream")
42+
43+
# Remote name where results pushed
44+
PUSH_REMOTE_NAME = os.environ.get("PUSH_REMOTE_NAME", "upstream")
45+
46+
GITHUB_BASE = "https://github.com/pydata/" + PROJECT_NAME + "/pull"
47+
GITHUB_API_BASE = "https://api.github.com/repos/pydata/" + PROJECT_NAME
48+
49+
# Prefix added to temporary branches
50+
BRANCH_PREFIX = "PR_TOOL"
51+
52+
os.chdir(PANDAS_HOME)
53+
54+
auth_required = False
55+
56+
if auth_required:
57+
GITHUB_USERNAME = os.environ['GITHUB_USER']
58+
import getpass
59+
GITHUB_PASSWORD = getpass.getpass('Enter github.com password for %s:'
60+
% GITHUB_USERNAME)
61+
62+
def get_json_auth(url):
63+
auth = HTTPBasicAuth(GITHUB_USERNAME, GITHUB_PASSWORD)
64+
req = requests.get(url, auth=auth)
65+
return req.json()
66+
67+
get_json = get_json_auth
68+
else:
69+
def get_json_no_auth(url):
70+
req = requests.get(url)
71+
return req.json()
72+
73+
get_json = get_json_no_auth
74+
75+
76+
def fail(msg):
77+
print(msg)
78+
clean_up()
79+
sys.exit(-1)
80+
81+
82+
def run_cmd(cmd):
83+
# py2.6 does not have subprocess.check_output
84+
if isinstance(cmd, six.string_types):
85+
cmd = cmd.split(' ')
86+
87+
popenargs = [cmd]
88+
kwargs = {}
89+
90+
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs)
91+
output, unused_err = process.communicate()
92+
retcode = process.poll()
93+
if retcode:
94+
cmd = kwargs.get("args")
95+
if cmd is None:
96+
cmd = popenargs[0]
97+
raise subprocess.CalledProcessError(retcode, cmd, output=output)
98+
return output
99+
100+
101+
def continue_maybe(prompt):
102+
result = raw_input("\n%s (y/n): " % prompt)
103+
if result.lower() != "y":
104+
fail("Okay, exiting")
105+
106+
107+
original_head = run_cmd("git rev-parse HEAD")[:8]
108+
109+
110+
def clean_up():
111+
print("Restoring head pointer to %s" % original_head)
112+
run_cmd("git checkout %s" % original_head)
113+
114+
branches = run_cmd("git branch").replace(" ", "").split("\n")
115+
116+
for branch in filter(lambda x: x.startswith(BRANCH_PREFIX), branches):
117+
print("Deleting local branch %s" % branch)
118+
run_cmd("git branch -D %s" % branch)
119+
120+
121+
# merge the requested PR and return the merge hash
122+
def merge_pr(pr_num, target_ref):
123+
pr_branch_name = "%s_MERGE_PR_%s" % (BRANCH_PREFIX, pr_num)
124+
target_branch_name = "%s_MERGE_PR_%s_%s" % (BRANCH_PREFIX, pr_num, target_ref.upper())
125+
run_cmd("git fetch %s pull/%s/head:%s" % (PR_REMOTE_NAME, pr_num, pr_branch_name))
126+
run_cmd("git fetch %s %s:%s" % (PUSH_REMOTE_NAME, target_ref, target_branch_name))
127+
run_cmd("git checkout %s" % target_branch_name)
128+
129+
had_conflicts = False
130+
try:
131+
run_cmd(['git', 'merge', pr_branch_name, '--squash'])
132+
except Exception as e:
133+
msg = "Error merging: %s\nWould you like to manually fix-up this merge?" % e
134+
continue_maybe(msg)
135+
msg = "Okay, please fix any conflicts and 'git add' conflicting files... Finished?"
136+
continue_maybe(msg)
137+
had_conflicts = True
138+
139+
commit_authors = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name,
140+
'--pretty=format:%an <%ae>']).split("\n")
141+
distinct_authors = sorted(set(commit_authors),
142+
key=lambda x: commit_authors.count(x), reverse=True)
143+
primary_author = distinct_authors[0]
144+
commits = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name,
145+
'--pretty=format:%h [%an] %s']).split("\n\n")
146+
147+
merge_message_flags = []
148+
149+
merge_message_flags += ["-m", title]
150+
if body != None:
151+
merge_message_flags += ["-m", '\n'.join(textwrap.wrap(body))]
152+
153+
authors = "\n".join(["Author: %s" % a for a in distinct_authors])
154+
155+
merge_message_flags += ["-m", authors]
156+
157+
if had_conflicts:
158+
committer_name = run_cmd("git config --get user.name").strip()
159+
committer_email = run_cmd("git config --get user.email").strip()
160+
message = "This patch had conflicts when merged, resolved by\nCommitter: %s <%s>" % (
161+
committer_name, committer_email)
162+
merge_message_flags += ["-m", message]
163+
164+
# The string "Closes #%s" string is required for GitHub to correctly close the PR
165+
merge_message_flags += [
166+
"-m",
167+
"Closes #%s from %s and squashes the following commits:" % (pr_num, pr_repo_desc)]
168+
for c in commits:
169+
merge_message_flags += ["-m", c]
170+
171+
run_cmd(['git', 'commit', '--author="%s"' % primary_author] +
172+
merge_message_flags)
173+
174+
continue_maybe("Merge complete (local ref %s). Push to %s?" % (
175+
target_branch_name, PUSH_REMOTE_NAME))
176+
177+
try:
178+
run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, target_branch_name,
179+
target_ref))
180+
except Exception as e:
181+
clean_up()
182+
fail("Exception while pushing: %s" % e)
183+
184+
merge_hash = run_cmd("git rev-parse %s" % target_branch_name)[:8]
185+
clean_up()
186+
print("Pull request #%s merged!" % pr_num)
187+
print("Merge hash: %s" % merge_hash)
188+
return merge_hash
189+
190+
191+
def cherry_pick(pr_num, merge_hash, default_branch):
192+
pick_ref = raw_input("Enter a branch name [%s]: " % default_branch)
193+
if pick_ref == "":
194+
pick_ref = default_branch
195+
196+
pick_branch_name = "%s_PICK_PR_%s_%s" % (BRANCH_PREFIX, pr_num,
197+
pick_ref.upper())
198+
199+
run_cmd("git fetch %s %s:%s" % (PUSH_REMOTE_NAME, pick_ref,
200+
pick_branch_name))
201+
run_cmd("git checkout %s" % pick_branch_name)
202+
run_cmd("git cherry-pick -sx %s" % merge_hash)
203+
204+
continue_maybe("Pick complete (local ref %s). Push to %s?" % (
205+
pick_branch_name, PUSH_REMOTE_NAME))
206+
207+
try:
208+
run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, pick_branch_name,
209+
pick_ref))
210+
except Exception as e:
211+
clean_up()
212+
fail("Exception while pushing: %s" % e)
213+
214+
pick_hash = run_cmd("git rev-parse %s" % pick_branch_name)[:8]
215+
clean_up()
216+
217+
print("Pull request #%s picked into %s!" % (pr_num, pick_ref))
218+
print("Pick hash: %s" % pick_hash)
219+
return pick_ref
220+
221+
222+
def fix_version_from_branch(branch, versions):
223+
# Note: Assumes this is a sorted (newest->oldest) list of un-released
224+
# versions
225+
if branch == "master":
226+
return versions[0]
227+
else:
228+
branch_ver = branch.replace("branch-", "")
229+
return filter(lambda x: x.name.startswith(branch_ver), versions)[-1]
230+
231+
232+
branches = get_json("%s/branches" % GITHUB_API_BASE)
233+
branch_names = filter(lambda x: x.startswith("branch-"),
234+
[x['name'] for x in branches])
235+
# Assumes branch names can be sorted lexicographically
236+
latest_branch = sorted(branch_names, reverse=True)[0]
237+
238+
pr_num = raw_input("Which pull request would you like to merge? (e.g. 34): ")
239+
pr = get_json("%s/pulls/%s" % (GITHUB_API_BASE, pr_num))
240+
241+
url = pr["url"]
242+
title = pr["title"]
243+
body = pr["body"]
244+
target_ref = pr["base"]["ref"]
245+
user_login = pr["user"]["login"]
246+
base_ref = pr["head"]["ref"]
247+
pr_repo_desc = "%s/%s" % (user_login, base_ref)
248+
249+
if pr["merged"] is True:
250+
print("Pull request {0} has already been merged, assuming "
251+
"you want to backport".format(pr_num))
252+
merge_commit_desc = run_cmd([
253+
'git', 'log', '--merges', '--first-parent',
254+
'--grep=pull request #%s' % pr_num, '--oneline']).split("\n")[0]
255+
if merge_commit_desc == "":
256+
fail("Couldn't find any merge commit for #{0}"
257+
", you may need to update HEAD.".format(pr_num))
258+
259+
merge_hash = merge_commit_desc[:7]
260+
message = merge_commit_desc[8:]
261+
262+
print("Found: %s" % message)
263+
maybe_cherry_pick(pr_num, merge_hash, latest_branch)
264+
sys.exit(0)
265+
266+
if not bool(pr["mergeable"]):
267+
msg = ("Pull request {0} is not mergeable in its current form.\n"
268+
"Continue? (experts only!)".format(pr_num))
269+
continue_maybe(msg)
270+
271+
print ("\n=== Pull Request #%s ===" % pr_num)
272+
print ("title\t%s\nsource\t%s\ntarget\t%s\nurl\t%s" % (
273+
title, pr_repo_desc, target_ref, url))
274+
continue_maybe("Proceed with merging pull request #%s?" % pr_num)
275+
276+
merged_refs = [target_ref]
277+
278+
merge_hash = merge_pr(pr_num, target_ref)
279+
280+
pick_prompt = "Would you like to pick %s into another branch?" % merge_hash
281+
while raw_input("\n%s (y/n): " % pick_prompt).lower() == "y":
282+
merged_refs = merged_refs + [cherry_pick(pr_num, merge_hash,
283+
latest_branch)]

0 commit comments

Comments
 (0)