zk-merge-pr.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. This script is a modified version
  19. # of the one created by the Spark project (https://github.com/apache/spark/blob/master/dev/merge_spark_pr.py).
  20. #
  21. # Usage: ./zk-merge-pr.py (see config env vars below)
  22. #
  23. # This utility assumes you already have a local ZooKeeper git folder and that you
  24. # have added remotes corresponding to both:
  25. # (i) the github apache ZooKeeper mirror and
  26. # (ii) the apache ZooKeeper git repo.
  27. import json
  28. import os
  29. import re
  30. import subprocess
  31. import sys
  32. import urllib.request, urllib.error, urllib.parse
  33. import getpass
  34. import requests
  35. try:
  36. import jira.client
  37. JIRA_IMPORTED = True
  38. except ImportError:
  39. JIRA_IMPORTED = False
  40. PROJECT_NAME = "zookeeper"
  41. CAPITALIZED_PROJECT_NAME = PROJECT_NAME.upper()
  42. # Remote name which points to the GitHub site
  43. PR_REMOTE_NAME = os.environ.get("PR_REMOTE_NAME", "apache-github")
  44. # Remote name which points to Apache git
  45. PUSH_REMOTE_NAME = os.environ.get("PUSH_REMOTE_NAME", "apache")
  46. # ASF JIRA username
  47. JIRA_USERNAME = os.environ.get("JIRA_USERNAME", "")
  48. # ASF JIRA password
  49. JIRA_PASSWORD = os.environ.get("JIRA_PASSWORD", "")
  50. # ASF JIRA access token
  51. # If it is configured, username and password are dismissed
  52. # Go to https://issues.apache.org/jira/secure/ViewProfile.jspa -> Personal Access Tokens for
  53. # your own token management.
  54. JIRA_ACCESS_TOKEN = os.environ.get("JIRA_ACCESS_TOKEN")
  55. # OAuth key used for issuing requests against the GitHub API. If this is not defined, then requests
  56. # will be unauthenticated. You should only need to configure this if you find yourself regularly
  57. # exceeding your IP's unauthenticated request rate limit. You can create an OAuth key at
  58. # https://github.com/settings/tokens. This script only requires the "public_repo" scope.
  59. GITHUB_OAUTH_KEY = os.environ.get("GITHUB_OAUTH_KEY")
  60. GITHUB_USER = os.environ.get("GITHUB_USER", "apache")
  61. GITHUB_BASE = "https://github.com/%s/%s/pull" % (GITHUB_USER, PROJECT_NAME)
  62. GITHUB_API_BASE = "https://api.github.com/repos/%s/%s" % (GITHUB_USER, PROJECT_NAME)
  63. JIRA_BASE = "https://issues.apache.org/jira/browse"
  64. JIRA_API_BASE = "https://issues.apache.org/jira"
  65. # Prefix added to temporary branches
  66. TEMP_BRANCH_PREFIX = "PR_TOOL"
  67. # TODO Introduce a convention as this is too brittle
  68. RELEASE_BRANCH_PREFIX = "branch-"
  69. DEV_BRANCH_NAME = "master"
  70. DEFAULT_FIX_VERSION = os.environ.get("DEFAULT_FIX_VERSION", "branch-3.5")
  71. def get_json(url):
  72. try:
  73. request = urllib.request.Request(url)
  74. if GITHUB_OAUTH_KEY:
  75. request.add_header('Authorization', 'token %s' % GITHUB_OAUTH_KEY)
  76. return json.load(urllib.request.urlopen(request))
  77. except urllib.error.HTTPError as e:
  78. if "X-RateLimit-Remaining" in e.headers and e.headers["X-RateLimit-Remaining"] == '0':
  79. print("Exceeded the GitHub API rate limit; see the instructions in " + \
  80. "zk-merge-pr.py to configure an OAuth token for making authenticated " + \
  81. "GitHub requests.")
  82. else:
  83. print("Unable to fetch URL, exiting: %s" % url)
  84. sys.exit(-1)
  85. def fail(msg):
  86. print(msg)
  87. clean_up()
  88. sys.exit(-1)
  89. def run_cmd(cmd):
  90. print(cmd)
  91. if isinstance(cmd, list):
  92. return subprocess.check_output(cmd, encoding='utf8')
  93. else:
  94. return subprocess.check_output(cmd.split(" "), encoding='utf8')
  95. def continue_maybe(prompt):
  96. result = input("\n%s (y/n): " % prompt)
  97. if result.lower().strip() != "y":
  98. fail("Okay, exiting")
  99. def clean_up():
  100. if original_head != get_current_branch():
  101. print("Restoring head pointer to %s" % original_head)
  102. run_cmd("git checkout %s" % original_head)
  103. branches = run_cmd("git branch").replace(" ", "").split("\n")
  104. for branch in [x for x in branches if x.startswith(TEMP_BRANCH_PREFIX)]:
  105. print("Deleting local branch %s" % branch)
  106. run_cmd("git branch -D %s" % branch)
  107. def get_current_branch():
  108. return run_cmd("git rev-parse --abbrev-ref HEAD").replace("\n", "")
  109. # merge the requested PR and return the merge hash
  110. def merge_pr(pr_num, title, pr_repo_desc):
  111. merge_message = []
  112. result = input("Would you like to squash the commit messages? (y/n): ")
  113. if result.lower().strip() == "y":
  114. # Retrieve the commits separately.
  115. json_commits = get_json(f"https://api.github.com/repos/{PUSH_REMOTE_NAME}/{PROJECT_NAME}/pulls/{pr_num}/commits")
  116. if json_commits and isinstance(json_commits, list):
  117. for commit in json_commits:
  118. commit_message = commit['commit']['message']
  119. # Remove empty lines and lines containing "Change-Id:"
  120. filtered_lines = [line for line in commit_message.split('\n') if 'Change-Id:' not in line and line.strip()]
  121. modified_commit_message = '\n'.join(filtered_lines)
  122. if modified_commit_message.strip() != title.strip():
  123. merge_message += [modified_commit_message]
  124. # Check for disapproval reviews.
  125. json_reviewers = get_json(f"https://api.github.com/repos/{PUSH_REMOTE_NAME}/{PROJECT_NAME}/pulls/{pr_num}/reviews")
  126. disapproval_reviews = [review['user']['login'] for review in json_reviewers if review['state'] == 'CHANGES_REQUESTED']
  127. if disapproval_reviews:
  128. continue_maybe("Warning: There are requested changes. Proceed with merging pull request #%s?" % pr_num)
  129. # Verify if there are no approved reviews.
  130. approved_reviewers = [review['user']['login'] for review in json_reviewers if review['state'] == 'APPROVED']
  131. if not approved_reviewers:
  132. continue_maybe("Warning: Pull Request does not have an approved review. Proceed with merging pull request #%s?" % pr_num)
  133. else:
  134. reviewers_string = ', '.join(approved_reviewers)
  135. merge_message += [f"Reviewers: {reviewers_string}"]
  136. # Check the author and the closing line.
  137. json_pr = get_json(f"https://api.github.com/repos/{PUSH_REMOTE_NAME}/{PROJECT_NAME}/pulls/{pr_num}")
  138. primary_author = json_pr["user"]["login"]
  139. if primary_author != "":
  140. merge_message += [f"Author: {primary_author}"]
  141. close_line = "Closes #%s from %s" % (pr_num, pr_repo_desc)
  142. merge_message += [close_line]
  143. merged_string = '\n'.join(merge_message)
  144. # Get the latest commit SHA.
  145. latest_commit_sha = json_pr["head"]["sha"]
  146. json_status = get_json(f"https://api.github.com/repos/{PUSH_REMOTE_NAME}/{PROJECT_NAME}/commits/{latest_commit_sha}/check-runs")
  147. # Check if all checks have passed on GitHub.
  148. all_checks_passed = all(status["conclusion"] == "success" for status in json_status["check_runs"])
  149. if all_checks_passed:
  150. print("All checks have passed on the github.")
  151. else:
  152. any_in_progress = any(run["status"] == "in_progress" for run in json_status["check_runs"])
  153. if any_in_progress:
  154. continue_maybe("Warning: There are pending checks. Would you like to continue the merge?")
  155. else:
  156. continue_maybe("Warning: Not all checks have passed on GitHub. Would you like to continue the merge?")
  157. headers = {
  158. "Authorization": f"token {GITHUB_OAUTH_KEY}",
  159. "Accept": "application/vnd.github.v3+json"
  160. }
  161. data = {
  162. "commit_title": title,
  163. "commit_message": merged_string,
  164. "merge_method": "squash"
  165. }
  166. response = requests.put(f"https://api.github.com/repos/{PUSH_REMOTE_NAME}/{PROJECT_NAME}/pulls/{pr_num}/merge", headers=headers, json=data)
  167. if response.status_code == 200:
  168. merge_response_json = response.json()
  169. merge_commit_sha = merge_response_json.get("sha")
  170. print(f"Pull request #{pr_num} merged. Sha: #{merge_commit_sha}")
  171. return merge_commit_sha
  172. else:
  173. print(f"Failed to merge pull request #{pr_num}. Status code: {response.status_code}")
  174. print(response.text)
  175. exit()
  176. def cherry_pick(pr_num, merge_hash, default_branch):
  177. pick_ref = input("Enter a branch name [%s]: " % default_branch)
  178. if pick_ref == "":
  179. pick_ref = default_branch
  180. pick_branch_name = "%s_PICK_PR_%s_%s" % (TEMP_BRANCH_PREFIX, pr_num, pick_ref.upper())
  181. run_cmd("git fetch %s" % PR_REMOTE_NAME)
  182. run_cmd("git checkout -b %s %s/%s" % (pick_branch_name, PUSH_REMOTE_NAME, pick_ref))
  183. current_attempt = 0
  184. max_attempts = 6
  185. # Check if the merge hash exists
  186. while not run_cmd("git rev-parse --verify %s" % merge_hash):
  187. if current_attempt >= max_attempts:
  188. print("Error: The commit hash does not exist in the local repository.")
  189. exit()
  190. current_attempt += 1
  191. print("Waiting for the merge hash to become available...(10 sec)")
  192. time.sleep(10)
  193. run_cmd("git fetch %s" % PR_REMOTE_NAME)
  194. try:
  195. run_cmd("git cherry-pick -sx %s" % merge_hash)
  196. except Exception as e:
  197. msg = "Error cherry-picking: %s\nWould you like to manually fix-up this merge?" % e
  198. continue_maybe(msg)
  199. msg = "Okay, please fix any conflicts and finish the cherry-pick. Finished?"
  200. continue_maybe(msg)
  201. continue_maybe("Pick complete (local ref %s). Push to %s?" % (
  202. pick_branch_name, PUSH_REMOTE_NAME))
  203. try:
  204. run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, pick_branch_name, pick_ref))
  205. except Exception as e:
  206. clean_up()
  207. fail("Exception while pushing: %s" % e)
  208. pick_hash = run_cmd("git rev-parse %s" % pick_branch_name)[:8]
  209. clean_up()
  210. print(("Pull request #%s picked into %s!" % (pr_num, pick_ref)))
  211. print(("Pick hash: %s" % pick_hash))
  212. return pick_ref
  213. def fix_version_from_branch(branch, versions):
  214. # Note: Assumes this is a sorted (newest->oldest) list of un-released versions
  215. if branch == DEV_BRANCH_NAME:
  216. versions = [x for x in versions if x == DEFAULT_FIX_VERSION]
  217. if len(versions) > 0:
  218. return versions[0]
  219. else:
  220. return None
  221. else:
  222. versions = [x for x in versions if x.startswith(branch)]
  223. if len(versions) > 0:
  224. return versions[-1]
  225. else:
  226. return None
  227. def resolve_jira_issue(merge_branches, comment, default_jira_id=""):
  228. jira_server = {"server": JIRA_API_BASE}
  229. if JIRA_ACCESS_TOKEN is not None:
  230. asf_jira = jira.client.JIRA(jira_server, token_auth=JIRA_ACCESS_TOKEN)
  231. else:
  232. asf_jira = jira.client.JIRA(jira_server, basic_auth=(JIRA_USERNAME, JIRA_PASSWORD))
  233. jira_id = input("Enter a JIRA id [%s]: " % default_jira_id)
  234. if jira_id == "":
  235. jira_id = default_jira_id
  236. try:
  237. issue = asf_jira.issue(jira_id)
  238. except Exception as e:
  239. fail("ASF JIRA could not find %s\n%s" % (jira_id, e))
  240. cur_status = issue.fields.status.name
  241. cur_summary = issue.fields.summary
  242. cur_assignee = issue.fields.assignee
  243. if cur_assignee is None:
  244. cur_assignee = "NOT ASSIGNED!!!"
  245. else:
  246. cur_assignee = cur_assignee.displayName
  247. if cur_status == "Resolved" or cur_status == "Closed":
  248. fail("JIRA issue %s already has status '%s'" % (jira_id, cur_status))
  249. print(("=== JIRA %s ===" % jira_id))
  250. print(("summary\t\t%s\nassignee\t%s\nstatus\t\t%s\nurl\t\t%s/%s\n" % (
  251. cur_summary, cur_assignee, cur_status, JIRA_BASE, jira_id)))
  252. versions = asf_jira.project_versions(CAPITALIZED_PROJECT_NAME)
  253. versions = sorted(versions, key=lambda x: x.name, reverse=True)
  254. versions = [x for x in versions if x.raw['released'] is False]
  255. version_names = [x.name for x in versions]
  256. default_fix_versions = [fix_version_from_branch(x, version_names) for x in merge_branches]
  257. default_fix_versions = [x for x in default_fix_versions if x != None]
  258. default_fix_versions = ",".join(default_fix_versions)
  259. fix_versions = input("Enter comma-separated fix version(s) [%s]: " % default_fix_versions)
  260. if fix_versions == "":
  261. fix_versions = default_fix_versions
  262. fix_versions = fix_versions.replace(" ", "").split(",")
  263. def get_version_json(version_str):
  264. return [v for v in versions if v.name == version_str][0].raw
  265. jira_fix_versions = [get_version_json(v) for v in fix_versions]
  266. resolve = [a for a in asf_jira.transitions(jira_id) if a['name'] == "Resolve Issue"][0]
  267. resolution = [r for r in asf_jira.resolutions() if r.raw['name'] == "Fixed"][0]
  268. asf_jira.transition_issue(
  269. jira_id, resolve["id"], fixVersions = jira_fix_versions,
  270. comment = comment, resolution = {'id': resolution.raw['id']})
  271. print("Successfully resolved %s with fixVersions=%s!" % (jira_id, fix_versions))
  272. def resolve_jira_issues(title, merge_branches, comment):
  273. jira_ids = re.findall("%s-[0-9]+" % CAPITALIZED_PROJECT_NAME, title)
  274. if len(jira_ids) == 0:
  275. resolve_jira_issue(merge_branches, comment)
  276. for jira_id in jira_ids:
  277. resolve_jira_issue(merge_branches, comment, jira_id)
  278. def standardize_jira_ref(text):
  279. """
  280. Standardize the jira reference commit message prefix to "PROJECT_NAME-XXX: Issue"
  281. >>> standardize_jira_ref("%s-5954: Top by key" % CAPITALIZED_PROJECT_NAME)
  282. 'ZOOKEEPER-5954: Top by key'
  283. >>> standardize_jira_ref("%s-5821: ParquetRelation2 CTAS should check if delete is successful" % PROJECT_NAME)
  284. 'ZOOKEEPER-5821: ParquetRelation2 CTAS should check if delete is successful'
  285. >>> standardize_jira_ref("%s-4123: [WIP] Show new dependencies added in pull requests" % PROJECT_NAME)
  286. 'ZOOKEEPER-4123: [WIP] Show new dependencies added in pull requests'
  287. >>> standardize_jira_ref("%s 5954: Top by key" % PROJECT_NAME)
  288. 'ZOOKEEPER-5954: Top by key'
  289. >>> standardize_jira_ref("%s-979: a LRU scheduler for load balancing in TaskSchedulerImpl" % PROJECT_NAME)
  290. 'ZOOKEEPER-979: a LRU scheduler for load balancing in TaskSchedulerImpl'
  291. >>> standardize_jira_ref("%s-1094: Support MiMa for reporting binary compatibility across versions." % CAPITALIZED_PROJECT_NAME)
  292. 'ZOOKEEPER-1094: Support MiMa for reporting binary compatibility across versions.'
  293. >>> standardize_jira_ref("%s-1146: [WIP] Vagrant support" % CAPITALIZED_PROJECT_NAME)
  294. 'ZOOKEEPER-1146: [WIP] Vagrant support'
  295. >>> standardize_jira_ref("%s-1032: If Yarn app fails before registering, app master stays aroun..." % PROJECT_NAME)
  296. 'ZOOKEEPER-1032: If Yarn app fails before registering, app master stays aroun...'
  297. >>> standardize_jira_ref("%s-6250 %s-6146 %s-5911: Types are now reserved words in DDL parser." % (PROJECT_NAME, PROJECT_NAME, CAPITALIZED_PROJECT_NAME))
  298. 'ZOOKEEPER-6250 ZOOKEEPER-6146 ZOOKEEPER-5911: Types are now reserved words in DDL parser.'
  299. >>> standardize_jira_ref("Additional information for users building from source code")
  300. 'Additional information for users building from source code'
  301. """
  302. jira_refs = []
  303. components = []
  304. # Extract JIRA ref(s):
  305. pattern = re.compile(r'(%s[-\s]*[0-9]{3,6})+' % CAPITALIZED_PROJECT_NAME, re.IGNORECASE)
  306. for ref in pattern.findall(text):
  307. # Add brackets, replace spaces with a dash, & convert to uppercase
  308. jira_refs.append(re.sub(r'\s+', '-', ref.upper()))
  309. text = text.replace(ref, '')
  310. # Extract project name component(s):
  311. # Look for alphanumeric chars, spaces, dashes, periods, and/or commas
  312. pattern = re.compile(r'(\[[\w\s,-\.]+\])', re.IGNORECASE)
  313. for component in pattern.findall(text):
  314. components.append(component.upper())
  315. text = text.replace(component, '')
  316. # Cleanup any remaining symbols:
  317. pattern = re.compile(r'^\W+(.*)', re.IGNORECASE)
  318. if (pattern.search(text) is not None):
  319. text = pattern.search(text).groups()[0]
  320. # Assemble full text (JIRA ref(s), module(s), remaining text)
  321. jira_prefix = ' '.join(jira_refs).strip()
  322. if jira_prefix:
  323. jira_prefix = jira_prefix + ": "
  324. clean_text = jira_prefix + ' '.join(components).strip() + " " + text.strip()
  325. # Replace multiple spaces with a single space, e.g. if no jira refs and/or components were included
  326. clean_text = re.sub(r'\s+', ' ', clean_text.strip())
  327. return clean_text
  328. def get_remote_repos():
  329. repos = run_cmd("git remote -v").split()
  330. dict = {}
  331. for i in range(0, len(repos), 3):
  332. dict[repos[i]] = repos[i+1]
  333. return dict
  334. def check_git_remote():
  335. repos = get_remote_repos()
  336. # check if all remote endpoints' URLs point to project git repo
  337. name = PROJECT_NAME + ".git"
  338. for url in list(repos.values()):
  339. if not url.endswith(name):
  340. fail("Error: not a %s git repo or at least one remote is invalid" % PROJECT_NAME)
  341. if not PR_REMOTE_NAME in repos:
  342. fail("Error: PR_REMOTE_NAME (%s) environment variable has not been set!" % PR_REMOTE_NAME)
  343. if not PUSH_REMOTE_NAME in repos:
  344. fail("Error: PUSH_REMOTE_NAME (%s) environment variable has not been set!" % PUSH_REMOTE_NAME)
  345. def check_jira_env():
  346. global JIRA_PASSWORD
  347. if JIRA_IMPORTED:
  348. if JIRA_ACCESS_TOKEN is None:
  349. if JIRA_USERNAME.strip() != "" and JIRA_PASSWORD.strip() == "":
  350. inform_pwd = input("JIRA_USERNAME set but JIRA_PASSWORD is not. Want to inform it? ")
  351. if inform_pwd.strip() == "y":
  352. JIRA_PASSWORD = getpass.getpass('JIRA PASSWORD: ')
  353. if JIRA_USERNAME.strip() == "" or JIRA_PASSWORD.strip() == "":
  354. msg ="Neither JIRA_ACCESS_TOKEN nor JIRA_USERNAME and/or JIRA_PASSWORD are set. Want to continue? "
  355. continue_maybe(msg)
  356. else:
  357. msg = "JIRA lib not installed. Want to continue? "
  358. continue_maybe(msg)
  359. def main():
  360. global original_head
  361. original_head = get_current_branch()
  362. check_jira_env()
  363. check_git_remote()
  364. branches = get_json("%s/branches" % GITHUB_API_BASE)
  365. branch_names = [x for x in [x['name'] for x in branches] if x.startswith(RELEASE_BRANCH_PREFIX)]
  366. # Assumes branch names can be sorted lexicographically
  367. latest_branch = sorted(branch_names, reverse=True)[0]
  368. pr_num = input("Which pull request would you like to merge? (e.g. 34): ")
  369. pr = get_json("%s/pulls/%s" % (GITHUB_API_BASE, pr_num))
  370. # Check if the pull request has already been closed or merged.
  371. pull_request_state = pr.get("state", "")
  372. if pull_request_state == "closed":
  373. merge_hash = pr.get("merge_commit_sha", "")
  374. merged = pr.get("merged")
  375. # Verify if the pull request has been merged by the GitHub API.
  376. if merged is True:
  377. print(f"Pull request #{pr['number']} has already been merged, assuming you want to backport")
  378. cherry_pick(pr_num, merge_hash, latest_branch)
  379. sys.exit(0)
  380. # Some merged pull requests may not appear as merged in the GitHub API,
  381. # for example, those closed by an older version of this script.
  382. else:
  383. pr_events = get_json("%s/issues/%s/events" % (GITHUB_API_BASE, pr_num))
  384. for event in pr_events:
  385. if event.get("event") == "closed":
  386. commit_id = event.get("commit_id")
  387. if commit_id is not None:
  388. print(f"Pull request #{pr['number']} has already been merged, assuming you want to backport")
  389. cherry_pick(pr_num, merge_hash, latest_branch)
  390. sys.exit(0)
  391. else:
  392. print(f"Pull request #{pr['number']} has already been closed, but not merged, exiting.")
  393. exit()
  394. if not bool(pr["mergeable"]):
  395. print(f"Pull request %s is not mergeable in its current form.\n" % pr_num)
  396. exit()
  397. url = pr["url"]
  398. pr_title = pr["title"]
  399. commit_title = input("Commit title [%s]: " % pr_title)
  400. if commit_title == "":
  401. commit_title = pr_title
  402. # Decide whether to use the modified title or not
  403. modified_title = standardize_jira_ref(commit_title)
  404. if modified_title != commit_title:
  405. print("I've re-written the title as follows to match the standard format:")
  406. print("Original: %s" % commit_title)
  407. print("Modified: %s" % modified_title)
  408. result = input("Would you like to use the modified title? (y/n): ")
  409. if result.lower().strip() == "y":
  410. commit_title = modified_title
  411. print("Using modified title:")
  412. else:
  413. print("Using original title:")
  414. print(commit_title)
  415. target_ref = pr["base"]["ref"]
  416. user_login = pr["user"]["login"]
  417. base_ref = pr["head"]["ref"]
  418. pr_repo_desc = "%s/%s" % (user_login, base_ref)
  419. print(("\n=== Pull Request #%s ===" % pr_num))
  420. print(("PR title\t%s\nCommit title\t%s\nSource\t\t%s\nTarget\t\t%s\nURL\t\t%s" % (
  421. pr_title, commit_title, pr_repo_desc, target_ref, url)))
  422. continue_maybe("Proceed with merging pull request #%s?" % pr_num)
  423. merged_refs = [target_ref]
  424. merge_hash = merge_pr(pr_num, commit_title, pr_repo_desc)
  425. pick_prompt = "Would you like to pick %s into another branch?" % merge_hash
  426. while input("\n%s (y/n): " % pick_prompt).lower().strip() == "y":
  427. merged_refs = merged_refs + [cherry_pick(pr_num, merge_hash, latest_branch)]
  428. if JIRA_IMPORTED:
  429. if (JIRA_ACCESS_TOKEN is not None) or (JIRA_USERNAME and JIRA_PASSWORD):
  430. continue_maybe("Would you like to update an associated JIRA?")
  431. jira_comment = "Issue resolved by pull request %s\n[%s/%s]" % (pr_num, GITHUB_BASE, pr_num)
  432. resolve_jira_issues(commit_title, merged_refs, jira_comment)
  433. else:
  434. print("Neither JIRA_ACCESS_TOKEN nor JIRA_USERNAME and/or JIRA_PASSWORD are set.")
  435. print("Exiting without trying to close the associated JIRA.")
  436. else:
  437. print("Could not find jira-python library. Run 'sudo pip install jira' to install.")
  438. print("Exiting without trying to close the associated JIRA.")
  439. if __name__ == "__main__":
  440. import doctest
  441. (failure_count, test_count) = doctest.testmod()
  442. if (failure_count):
  443. exit(-1)
  444. main()