merge_livy_pr.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. #!/usr/bin/env python
  2. #
  3. # Licensed to the Apache Software Foundation (ASF) under one or more
  4. # contributor license agreements. See the NOTICE file distributed with
  5. # this work for additional information regarding copyright ownership.
  6. # The ASF licenses this file to You under the Apache License, Version 2.0
  7. # (the "License"); you may not use this file except in compliance with
  8. # the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. #
  18. # Utility for creating well-formed pull request merges and pushing them to Apache.
  19. #
  20. # This utility assumes you already have local a incubator-livy git folder and that you
  21. # have added remotes corresponding to both (i) the github apache incubator-livy
  22. # mirror and (ii) the apache git repo.
  23. #
  24. # 1. Adding github apache incubator-livy mirror remote to your local repo with name "apache-github"
  25. # (for example) using "git remote add apache-github ...".
  26. # 2. Adding apache incubator-livy remote to your local repo with name "apache" (for example) using
  27. # "git remote add apache ..."
  28. # 3. Invoke this script from LIVY_HOME (./dev/merge_livy_pr.py) and follow the prompted steps.
  29. # 4. If you want to handle the associated JIRA, JIRA_USERNAME and JIRA_PASSWORD should be set.
  30. #
  31. # usage: ./merge_livy_pr.py (see config env vars below)
  32. #
  33. import json
  34. import os
  35. import re
  36. import subprocess
  37. import sys
  38. import urllib2
  39. try:
  40. import jira.client
  41. JIRA_IMPORTED = True
  42. except ImportError:
  43. JIRA_IMPORTED = False
  44. # Location of your incubator-livy git development area
  45. LIVY_HOME = os.environ.get("LIVY_HOME", os.getcwd())
  46. # Remote name which points to the Gihub site
  47. PR_REMOTE_NAME = os.environ.get("PR_REMOTE_NAME", "apache-github")
  48. # Remote name which points to Apache git
  49. PUSH_REMOTE_NAME = os.environ.get("PUSH_REMOTE_NAME", "apache")
  50. # ASF JIRA username
  51. JIRA_USERNAME = os.environ.get("JIRA_USERNAME", "")
  52. # ASF JIRA password
  53. JIRA_PASSWORD = os.environ.get("JIRA_PASSWORD", "")
  54. # OAuth key used for issuing requests against the GitHub API. If this is not defined, then requests
  55. # will be unauthenticated. You should only need to configure this if you find yourself regularly
  56. # exceeding your IP's unauthenticated request rate limit. You can create an OAuth key at
  57. # https://github.com/settings/tokens. This script only requires the "public_repo" scope.
  58. GITHUB_OAUTH_KEY = os.environ.get("GITHUB_OAUTH_KEY")
  59. GITHUB_BASE = "https://github.com/apache/incubator-livy/pull"
  60. GITHUB_API_BASE = "https://api.github.com/repos/apache/incubator-livy"
  61. JIRA_BASE = "https://issues.apache.org/jira/browse"
  62. JIRA_API_BASE = "https://issues.apache.org/jira"
  63. # Prefix added to temporary branches
  64. BRANCH_PREFIX = "PR_TOOL"
  65. def get_json(url):
  66. try:
  67. request = urllib2.Request(url)
  68. if GITHUB_OAUTH_KEY:
  69. request.add_header('Authorization', 'token %s' % GITHUB_OAUTH_KEY)
  70. return json.load(urllib2.urlopen(request))
  71. except urllib2.HTTPError as e:
  72. if "X-RateLimit-Remaining" in e.headers and e.headers["X-RateLimit-Remaining"] == '0':
  73. print("Exceeded the GitHub API rate limit; see the instructions in " +
  74. "dev/merge_livy_pr.py to configure an OAuth token for making authenticated " +
  75. "GitHub requests.")
  76. else:
  77. print("Unable to fetch URL, exiting: %s" % url)
  78. sys.exit(-1)
  79. def fail(msg):
  80. print(msg)
  81. clean_up()
  82. sys.exit(-1)
  83. def run_cmd(cmd):
  84. print(cmd)
  85. if isinstance(cmd, list):
  86. return subprocess.check_output(cmd)
  87. else:
  88. return subprocess.check_output(cmd.split(" "))
  89. def continue_maybe(prompt):
  90. result = raw_input("\n%s (y/n): " % prompt)
  91. if result.lower() != "y":
  92. fail("Okay, exiting")
  93. def clean_up():
  94. print("Restoring head pointer to %s" % original_head)
  95. run_cmd("git checkout %s" % original_head)
  96. branches = run_cmd("git branch").replace(" ", "").split("\n")
  97. for branch in filter(lambda x: x.startswith(BRANCH_PREFIX), branches):
  98. print("Deleting local branch %s" % branch)
  99. run_cmd("git branch -D %s" % branch)
  100. # merge the requested PR and return the merge hash
  101. def merge_pr(pr_num, target_ref, title, body, pr_repo_desc):
  102. pr_branch_name = "%s_MERGE_PR_%s" % (BRANCH_PREFIX, pr_num)
  103. target_branch_name = "%s_MERGE_PR_%s_%s" % (BRANCH_PREFIX, pr_num, target_ref.upper())
  104. run_cmd("git fetch %s pull/%s/head:%s" % (PR_REMOTE_NAME, pr_num, pr_branch_name))
  105. run_cmd("git fetch %s %s:%s" % (PUSH_REMOTE_NAME, target_ref, target_branch_name))
  106. run_cmd("git checkout %s" % target_branch_name)
  107. had_conflicts = False
  108. try:
  109. run_cmd(['git', 'merge', pr_branch_name, '--squash'])
  110. except Exception as e:
  111. msg = "Error merging: %s\nWould you like to manually fix-up this merge?" % e
  112. continue_maybe(msg)
  113. msg = "Okay, please fix any conflicts and 'git add' conflicting files... Finished?"
  114. continue_maybe(msg)
  115. had_conflicts = True
  116. commit_authors = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name,
  117. '--pretty=format:%an <%ae>']).split("\n")
  118. distinct_authors = sorted(set(commit_authors),
  119. key=lambda x: commit_authors.count(x), reverse=True)
  120. primary_author = raw_input(
  121. "Enter primary author in the format of \"name <email>\" [%s]: " %
  122. distinct_authors[0])
  123. if primary_author == "":
  124. primary_author = distinct_authors[0]
  125. commits = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name,
  126. '--pretty=format:%h [%an] %s']).split("\n\n")
  127. merge_message_flags = []
  128. merge_message_flags += ["-m", title]
  129. if body is not None:
  130. # We remove @ symbols from the body to avoid triggering e-mails
  131. # to people every time someone creates a public fork of incubator-livy.
  132. merge_message_flags += ["-m", body.replace("@", "")]
  133. authors = "\n".join(["Author: %s" % a for a in distinct_authors])
  134. merge_message_flags += ["-m", authors]
  135. if had_conflicts:
  136. committer_name = run_cmd("git config --get user.name").strip()
  137. committer_email = run_cmd("git config --get user.email").strip()
  138. message = "This patch had conflicts when merged, resolved by\nCommitter: %s <%s>" % (
  139. committer_name, committer_email)
  140. merge_message_flags += ["-m", message]
  141. # The string "Closes #%s" string is required for GitHub to correctly close the PR
  142. merge_message_flags += ["-m", "Closes #%s from %s." % (pr_num, pr_repo_desc)]
  143. run_cmd(['git', 'commit', '--author="%s"' % primary_author] + merge_message_flags)
  144. continue_maybe("Merge complete (local ref %s). Push to %s?" % (
  145. target_branch_name, PUSH_REMOTE_NAME))
  146. try:
  147. run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, target_branch_name, target_ref))
  148. except Exception as e:
  149. clean_up()
  150. fail("Exception while pushing: %s" % e)
  151. merge_hash = run_cmd("git rev-parse %s" % target_branch_name)[:8]
  152. clean_up()
  153. print("Pull request #%s merged!" % pr_num)
  154. print("Merge hash: %s" % merge_hash)
  155. return merge_hash
  156. def cherry_pick(pr_num, merge_hash, default_branch):
  157. pick_ref = raw_input("Enter a branch name [%s]: " % default_branch)
  158. if pick_ref == "":
  159. pick_ref = default_branch
  160. pick_branch_name = "%s_PICK_PR_%s_%s" % (BRANCH_PREFIX, pr_num, pick_ref.upper())
  161. run_cmd("git fetch %s %s:%s" % (PUSH_REMOTE_NAME, pick_ref, pick_branch_name))
  162. run_cmd("git checkout %s" % pick_branch_name)
  163. try:
  164. run_cmd("git cherry-pick -sx %s" % merge_hash)
  165. except Exception as e:
  166. msg = "Error cherry-picking: %s\nWould you like to manually fix-up this merge?" % e
  167. continue_maybe(msg)
  168. msg = "Okay, please fix any conflicts and finish the cherry-pick. Finished?"
  169. continue_maybe(msg)
  170. continue_maybe("Pick complete (local ref %s). Push to %s?" % (
  171. pick_branch_name, PUSH_REMOTE_NAME))
  172. try:
  173. run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, pick_branch_name, pick_ref))
  174. except Exception as e:
  175. clean_up()
  176. fail("Exception while pushing: %s" % e)
  177. pick_hash = run_cmd("git rev-parse %s" % pick_branch_name)[:8]
  178. clean_up()
  179. print("Pull request #%s picked into %s!" % (pr_num, pick_ref))
  180. print("Pick hash: %s" % pick_hash)
  181. return pick_ref
  182. def fix_version_from_branch(branch, versions):
  183. # Note: Assumes this is a sorted (newest->oldest) list of un-released versions
  184. if branch == "master":
  185. return versions[0]
  186. else:
  187. branch_ver = branch.replace("branch-", "")
  188. return filter(lambda x: x.name.startswith(branch_ver), versions)[-1]
  189. def resolve_jira_issue(merge_branches, comment, default_jira_id=""):
  190. asf_jira = jira.client.JIRA({'server': JIRA_API_BASE},
  191. basic_auth=(JIRA_USERNAME, JIRA_PASSWORD))
  192. jira_id = raw_input("Enter a JIRA id [%s]: " % default_jira_id)
  193. if jira_id == "":
  194. jira_id = default_jira_id
  195. try:
  196. issue = asf_jira.issue(jira_id)
  197. except Exception as e:
  198. fail("ASF JIRA could not find %s\n%s" % (jira_id, e))
  199. cur_status = issue.fields.status.name
  200. cur_summary = issue.fields.summary
  201. cur_assignee = issue.fields.assignee
  202. if cur_assignee is None:
  203. cur_assignee = "NOT ASSIGNED!!!"
  204. else:
  205. cur_assignee = cur_assignee.displayName
  206. if cur_status == "Resolved" or cur_status == "Closed":
  207. fail("JIRA issue %s already has status '%s'" % (jira_id, cur_status))
  208. print("=== JIRA %s ===" % jira_id)
  209. print("summary\t\t%s\nassignee\t%s\nstatus\t\t%s\nurl\t\t%s/%s\n" %
  210. (cur_summary, cur_assignee, cur_status, JIRA_BASE, jira_id))
  211. versions = asf_jira.project_versions("LIVY")
  212. versions = sorted(versions, key=lambda x: x.name, reverse=True)
  213. versions = filter(lambda x: x.raw['released'] is False, versions)
  214. # Consider only x.y.z versions
  215. versions = filter(lambda x: re.match('\d+\.\d+\.\d+', x.name), versions)
  216. default_fix_versions = map(lambda x: fix_version_from_branch(x, versions).name, merge_branches)
  217. for v in default_fix_versions:
  218. # Handles the case where we have forked a release branch but not yet made the release.
  219. # In this case, if the PR is committed to the master branch and the release branch, we
  220. # only consider the release branch to be the fix version. E.g. it is not valid to have
  221. # both 1.1.0 and 1.0.0 as fix versions.
  222. (major, minor, patch) = v.split(".")
  223. if patch == "0":
  224. previous = "%s.%s.%s" % (major, int(minor) - 1, 0)
  225. if previous in default_fix_versions:
  226. default_fix_versions = filter(lambda x: x != v, default_fix_versions)
  227. default_fix_versions = ",".join(default_fix_versions)
  228. fix_versions = raw_input("Enter comma-separated fix version(s) [%s]: " % default_fix_versions)
  229. if fix_versions == "":
  230. fix_versions = default_fix_versions
  231. fix_versions = fix_versions.replace(" ", "").split(",")
  232. def get_version_json(version_str):
  233. return filter(lambda v: v.name == version_str, versions)[0].raw
  234. jira_fix_versions = map(lambda v: get_version_json(v), fix_versions)
  235. resolve = filter(lambda a: a['name'] == "Resolve Issue", asf_jira.transitions(jira_id))[0]
  236. resolution = filter(lambda r: r.raw['name'] == "Fixed", asf_jira.resolutions())[0]
  237. asf_jira.transition_issue(
  238. jira_id, resolve["id"], fixVersions=jira_fix_versions,
  239. comment=comment, resolution={'id': resolution.raw['id']})
  240. print("Successfully resolved %s with fixVersions=%s!" % (jira_id, fix_versions))
  241. def resolve_jira_issues(title, merge_branches, comment):
  242. jira_ids = re.findall("LIVY-[0-9]{3,6}", title)
  243. if len(jira_ids) == 0:
  244. resolve_jira_issue(merge_branches, comment)
  245. for jira_id in jira_ids:
  246. resolve_jira_issue(merge_branches, comment, jira_id)
  247. def standardize_jira_ref(text):
  248. """
  249. Standardize the [LIVY-XXXXX] [MODULE] prefix
  250. Converts "[LIVY-XXX][repl] Issue", "[Repl] LIVY-XXX. Issue" or "LIVY XXX [REPL]: Issue" to
  251. "[LIVY-XXX][REPL] Issue"
  252. """
  253. jira_refs = []
  254. components = []
  255. # If the string is compliant, no need to process any further
  256. if (re.search(r'^\[LIVY-[0-9]{3,6}\](\[[A-Z0-9_\s,]+\] )+\S+', text)):
  257. return text
  258. # Extract JIRA ref(s):
  259. pattern = re.compile(r'(LIVY[-\s]*[0-9]{3,6})+', re.IGNORECASE)
  260. for ref in pattern.findall(text):
  261. # Add brackets, replace spaces with a dash, & convert to uppercase
  262. jira_refs.append('[' + re.sub(r'\s+', '-', ref.upper()) + ']')
  263. text = text.replace(ref, '')
  264. # Extract livy component(s):
  265. # Look for alphanumeric chars, spaces, dashes, periods, and/or commas
  266. pattern = re.compile(r'(\[[\w\s,-\.]+\])', re.IGNORECASE)
  267. for component in pattern.findall(text):
  268. components.append(component.upper())
  269. text = text.replace(component, '')
  270. # Cleanup any remaining symbols:
  271. pattern = re.compile(r'^\W+(.*)', re.IGNORECASE)
  272. if (pattern.search(text) is not None):
  273. text = pattern.search(text).groups()[0]
  274. # Assemble full text (JIRA ref(s), module(s), remaining text)
  275. clean_text = ''.join(jira_refs).strip() + ''.join(components).strip() + " " + text.strip()
  276. # Replace multiple spaces with a single space, e.g. if no jira refs and/or components were
  277. # included
  278. clean_text = re.sub(r'\s+', ' ', clean_text.strip())
  279. return clean_text
  280. def get_current_ref():
  281. ref = run_cmd("git rev-parse --abbrev-ref HEAD").strip()
  282. if ref == 'HEAD':
  283. # The current ref is a detached HEAD, so grab its SHA.
  284. return run_cmd("git rev-parse HEAD").strip()
  285. else:
  286. return ref
  287. def main():
  288. global original_head
  289. os.chdir(LIVY_HOME)
  290. original_head = get_current_ref()
  291. branches = get_json("%s/branches" % GITHUB_API_BASE)
  292. branch_names = filter(lambda x: x.startswith("branch-"), [x['name'] for x in branches])
  293. # Assumes branch names can be sorted lexicographically
  294. latest_branch = sorted(branch_names, reverse=True)[0]
  295. pr_num = raw_input("Which pull request would you like to merge? (e.g. 34): ")
  296. pr = get_json("%s/pulls/%s" % (GITHUB_API_BASE, pr_num))
  297. pr_events = get_json("%s/issues/%s/events" % (GITHUB_API_BASE, pr_num))
  298. url = pr["url"]
  299. # Decide whether to use the modified title or not
  300. modified_title = standardize_jira_ref(pr["title"])
  301. if modified_title != pr["title"]:
  302. print("I've re-written the title as follows to match the standard format:")
  303. print("Original: %s" % pr["title"])
  304. print("Modified: %s" % modified_title)
  305. result = raw_input("Would you like to use the modified title? (y/n): ")
  306. if result.lower() == "y":
  307. title = modified_title
  308. print("Using modified title:")
  309. else:
  310. title = pr["title"]
  311. print("Using original title:")
  312. print(title)
  313. else:
  314. title = pr["title"]
  315. body = pr["body"]
  316. target_ref = pr["base"]["ref"]
  317. user_login = pr["user"]["login"]
  318. base_ref = pr["head"]["ref"]
  319. pr_repo_desc = "%s/%s" % (user_login, base_ref)
  320. # Merged pull requests don't appear as merged in the GitHub API;
  321. # Instead, they're closed by asfgit.
  322. merge_commits = \
  323. [e for e in pr_events if e["actor"]["login"] == "asfgit" and e["event"] == "closed"]
  324. if merge_commits:
  325. merge_hash = merge_commits[0]["commit_id"]
  326. message = get_json("%s/commits/%s" % (GITHUB_API_BASE, merge_hash))["commit"]["message"]
  327. print("Pull request %s has already been merged, assuming you want to backport" % pr_num)
  328. commit_is_downloaded = run_cmd(['git', 'rev-parse', '--quiet', '--verify',
  329. "%s^{commit}" % merge_hash]).strip() != ""
  330. if not commit_is_downloaded:
  331. fail("Couldn't find any merge commit for #%s, you may need to update HEAD." % pr_num)
  332. print("Found commit %s:\n%s" % (merge_hash, message))
  333. cherry_pick(pr_num, merge_hash, latest_branch)
  334. sys.exit(0)
  335. if not bool(pr["mergeable"]):
  336. msg = "Pull request %s is not mergeable in its current form.\n" % pr_num + \
  337. "Continue? (experts only!)"
  338. continue_maybe(msg)
  339. print("\n=== Pull Request #%s ===" % pr_num)
  340. print("title\t%s\nsource\t%s\ntarget\t%s\nurl\t%s" %
  341. (title, pr_repo_desc, target_ref, url))
  342. continue_maybe("Proceed with merging pull request #%s?" % pr_num)
  343. merged_refs = [target_ref]
  344. merge_hash = merge_pr(pr_num, target_ref, title, body, pr_repo_desc)
  345. pick_prompt = "Would you like to pick %s into another branch?" % merge_hash
  346. while raw_input("\n%s (y/n): " % pick_prompt).lower() == "y":
  347. merged_refs = merged_refs + [cherry_pick(pr_num, merge_hash, latest_branch)]
  348. if JIRA_IMPORTED:
  349. if JIRA_USERNAME and JIRA_PASSWORD:
  350. continue_maybe("Would you like to update an associated JIRA?")
  351. jira_comment = "Issue resolved by pull request %s\n[%s/%s]" % \
  352. (pr_num, GITHUB_BASE, pr_num)
  353. resolve_jira_issues(title, merged_refs, jira_comment)
  354. else:
  355. print("JIRA_USERNAME and JIRA_PASSWORD not set")
  356. print("Exiting without trying to close the associated JIRA.")
  357. else:
  358. print("Could not find jira-python library. Run 'sudo pip install jira' to install.")
  359. print("Exiting without trying to close the associated JIRA.")
  360. if __name__ == "__main__":
  361. import doctest
  362. (failure_count, test_count) = doctest.testmod()
  363. if failure_count:
  364. exit(-1)
  365. try:
  366. main()
  367. except:
  368. clean_up()
  369. raise