zk-merge-pr.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. try:
  35. import jira.client
  36. JIRA_IMPORTED = True
  37. except ImportError:
  38. JIRA_IMPORTED = False
  39. PROJECT_NAME = "zookeeper"
  40. CAPITALIZED_PROJECT_NAME = PROJECT_NAME.upper()
  41. # Remote name which points to the GitHub site
  42. PR_REMOTE_NAME = os.environ.get("PR_REMOTE_NAME", "apache-github")
  43. # Remote name which points to Apache git
  44. PUSH_REMOTE_NAME = os.environ.get("PUSH_REMOTE_NAME", "apache")
  45. # ASF JIRA username
  46. JIRA_USERNAME = os.environ.get("JIRA_USERNAME", "")
  47. # ASF JIRA password
  48. JIRA_PASSWORD = os.environ.get("JIRA_PASSWORD", "")
  49. # OAuth key used for issuing requests against the GitHub API. If this is not defined, then requests
  50. # will be unauthenticated. You should only need to configure this if you find yourself regularly
  51. # exceeding your IP's unauthenticated request rate limit. You can create an OAuth key at
  52. # https://github.com/settings/tokens. This script only requires the "public_repo" scope.
  53. GITHUB_OAUTH_KEY = os.environ.get("GITHUB_OAUTH_KEY")
  54. GITHUB_USER = os.environ.get("GITHUB_USER", "apache")
  55. GITHUB_BASE = "https://github.com/%s/%s/pull" % (GITHUB_USER, PROJECT_NAME)
  56. GITHUB_API_BASE = "https://api.github.com/repos/%s/%s" % (GITHUB_USER, PROJECT_NAME)
  57. JIRA_BASE = "https://issues.apache.org/jira/browse"
  58. JIRA_API_BASE = "https://issues.apache.org/jira"
  59. # Prefix added to temporary branches
  60. TEMP_BRANCH_PREFIX = "PR_TOOL"
  61. # TODO Introduce a convention as this is too brittle
  62. RELEASE_BRANCH_PREFIX = "branch-"
  63. DEV_BRANCH_NAME = "master"
  64. DEFAULT_FIX_VERSION = os.environ.get("DEFAULT_FIX_VERSION", "branch-3.5")
  65. def get_json(url):
  66. try:
  67. request = urllib.request.Request(url)
  68. if GITHUB_OAUTH_KEY:
  69. request.add_header('Authorization', 'token %s' % GITHUB_OAUTH_KEY)
  70. return json.load(urllib.request.urlopen(request))
  71. except urllib.error.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. "zk-merge-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, encoding='utf8')
  87. else:
  88. return subprocess.check_output(cmd.split(" "), encoding='utf8')
  89. def continue_maybe(prompt):
  90. result = input("\n%s (y/n): " % prompt)
  91. if result.lower().strip() != "y":
  92. fail("Okay, exiting")
  93. def clean_up():
  94. if original_head != get_current_branch():
  95. print("Restoring head pointer to %s" % original_head)
  96. run_cmd("git checkout %s" % original_head)
  97. branches = run_cmd("git branch").replace(" ", "").split("\n")
  98. for branch in [x for x in branches if x.startswith(TEMP_BRANCH_PREFIX)]:
  99. print("Deleting local branch %s" % branch)
  100. run_cmd("git branch -D %s" % branch)
  101. def get_current_branch():
  102. return run_cmd("git rev-parse --abbrev-ref HEAD").replace("\n", "")
  103. # merge the requested PR and return the merge hash
  104. def merge_pr(pr_num, target_ref, title, body, pr_repo_desc):
  105. pr_branch_name = "%s_MERGE_PR_%s" % (TEMP_BRANCH_PREFIX, pr_num)
  106. target_branch_name = "%s_MERGE_PR_%s_%s" % (TEMP_BRANCH_PREFIX, pr_num, target_ref.upper())
  107. run_cmd("git fetch %s pull/%s/head:%s" % (PR_REMOTE_NAME, pr_num, pr_branch_name))
  108. run_cmd("git fetch %s %s:%s" % (PUSH_REMOTE_NAME, target_ref, target_branch_name))
  109. run_cmd("git checkout %s" % target_branch_name)
  110. had_conflicts = False
  111. try:
  112. run_cmd(['git', 'merge', pr_branch_name, '--squash'])
  113. except Exception as e:
  114. msg = "Error merging: %s\nWould you like to manually fix-up this merge?" % e
  115. continue_maybe(msg)
  116. msg = "Okay, please fix any conflicts and 'git add' conflicting files... Finished?"
  117. continue_maybe(msg)
  118. had_conflicts = True
  119. commit_authors = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name,
  120. '--pretty=format:%an <%ae>']).split("\n")
  121. distinct_authors = sorted(set(commit_authors),
  122. key=lambda x: commit_authors.count(x), reverse=True)
  123. primary_author = input(
  124. "Enter primary author in the format of \"name <email>\" [%s]: " %
  125. distinct_authors[0])
  126. if primary_author == "":
  127. primary_author = distinct_authors[0]
  128. reviewers = input(
  129. "Enter reviewers in the format of \"name1 <email1>, name2 <email2>\": ").strip()
  130. commits = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name,
  131. '--pretty=format:%h [%an] %s']).split("\n")
  132. if len(commits) > 1:
  133. result = input("List pull request commits in squashed commit message? (y/n): ")
  134. if result.lower().strip() == "y":
  135. should_list_commits = True
  136. else:
  137. should_list_commits = False
  138. else:
  139. should_list_commits = False
  140. merge_message_flags = []
  141. merge_message_flags += ["-m", title]
  142. if body is not None:
  143. # We remove @ symbols from the body to avoid triggering e-mails
  144. # to people every time someone creates a public fork of the project.
  145. merge_message_flags += ["-m", body.replace("@", "")]
  146. authors = "\n".join(["Author: %s" % a for a in distinct_authors])
  147. merge_message_flags += ["-m", authors]
  148. if (reviewers != ""):
  149. merge_message_flags += ["-m", "Reviewers: %s" % reviewers]
  150. if had_conflicts:
  151. committer_name = run_cmd("git config --get user.name").strip()
  152. committer_email = run_cmd("git config --get user.email").strip()
  153. message = "This patch had conflicts when merged, resolved by\nCommitter: %s <%s>" % (
  154. committer_name, committer_email)
  155. merge_message_flags += ["-m", message]
  156. # The string "Closes #%s" string is required for GitHub to correctly close the PR
  157. close_line = "Closes #%s from %s" % (pr_num, pr_repo_desc)
  158. if should_list_commits:
  159. close_line += " and squashes the following commits:"
  160. merge_message_flags += ["-m", close_line]
  161. if should_list_commits:
  162. merge_message_flags += ["-m", "\n".join(commits)]
  163. run_cmd(['git', 'commit', '--author="%s"' % primary_author] + merge_message_flags)
  164. continue_maybe("Merge complete (local ref %s). Push to %s?" % (
  165. target_branch_name, PUSH_REMOTE_NAME))
  166. try:
  167. run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, target_branch_name, target_ref))
  168. except Exception as e:
  169. clean_up()
  170. fail("Exception while pushing: %s" % e)
  171. merge_hash = run_cmd("git rev-parse %s" % target_branch_name)[:8]
  172. clean_up()
  173. print(("Pull request #%s merged!" % pr_num))
  174. print(("Merge hash: %s" % merge_hash))
  175. return merge_hash
  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 %s:%s" % (PUSH_REMOTE_NAME, pick_ref, pick_branch_name))
  182. run_cmd("git checkout %s" % pick_branch_name)
  183. try:
  184. run_cmd("git cherry-pick -sx %s" % merge_hash)
  185. except Exception as e:
  186. msg = "Error cherry-picking: %s\nWould you like to manually fix-up this merge?" % e
  187. continue_maybe(msg)
  188. msg = "Okay, please fix any conflicts and finish the cherry-pick. Finished?"
  189. continue_maybe(msg)
  190. continue_maybe("Pick complete (local ref %s). Push to %s?" % (
  191. pick_branch_name, PUSH_REMOTE_NAME))
  192. try:
  193. run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, pick_branch_name, pick_ref))
  194. except Exception as e:
  195. clean_up()
  196. fail("Exception while pushing: %s" % e)
  197. pick_hash = run_cmd("git rev-parse %s" % pick_branch_name)[:8]
  198. clean_up()
  199. print(("Pull request #%s picked into %s!" % (pr_num, pick_ref)))
  200. print(("Pick hash: %s" % pick_hash))
  201. return pick_ref
  202. def fix_version_from_branch(branch, versions):
  203. # Note: Assumes this is a sorted (newest->oldest) list of un-released versions
  204. if branch == DEV_BRANCH_NAME:
  205. versions = [x for x in versions if x == DEFAULT_FIX_VERSION]
  206. if len(versions) > 0:
  207. return versions[0]
  208. else:
  209. return None
  210. else:
  211. versions = [x for x in versions if x.startswith(branch)]
  212. if len(versions) > 0:
  213. return versions[-1]
  214. else:
  215. return None
  216. def resolve_jira_issue(merge_branches, comment, default_jira_id=""):
  217. asf_jira = jira.client.JIRA({'server': JIRA_API_BASE},
  218. basic_auth=(JIRA_USERNAME, JIRA_PASSWORD))
  219. jira_id = input("Enter a JIRA id [%s]: " % default_jira_id)
  220. if jira_id == "":
  221. jira_id = default_jira_id
  222. try:
  223. issue = asf_jira.issue(jira_id)
  224. except Exception as e:
  225. fail("ASF JIRA could not find %s\n%s" % (jira_id, e))
  226. cur_status = issue.fields.status.name
  227. cur_summary = issue.fields.summary
  228. cur_assignee = issue.fields.assignee
  229. if cur_assignee is None:
  230. cur_assignee = "NOT ASSIGNED!!!"
  231. else:
  232. cur_assignee = cur_assignee.displayName
  233. if cur_status == "Resolved" or cur_status == "Closed":
  234. fail("JIRA issue %s already has status '%s'" % (jira_id, cur_status))
  235. print(("=== JIRA %s ===" % jira_id))
  236. print(("summary\t\t%s\nassignee\t%s\nstatus\t\t%s\nurl\t\t%s/%s\n" % (
  237. cur_summary, cur_assignee, cur_status, JIRA_BASE, jira_id)))
  238. versions = asf_jira.project_versions(CAPITALIZED_PROJECT_NAME)
  239. versions = sorted(versions, key=lambda x: x.name, reverse=True)
  240. versions = [x for x in versions if x.raw['released'] is False]
  241. version_names = [x.name for x in versions]
  242. default_fix_versions = [fix_version_from_branch(x, version_names) for x in merge_branches]
  243. default_fix_versions = [x for x in default_fix_versions if x != None]
  244. default_fix_versions = ",".join(default_fix_versions)
  245. fix_versions = input("Enter comma-separated fix version(s) [%s]: " % default_fix_versions)
  246. if fix_versions == "":
  247. fix_versions = default_fix_versions
  248. fix_versions = fix_versions.replace(" ", "").split(",")
  249. def get_version_json(version_str):
  250. return [v for v in versions if v.name == version_str][0].raw
  251. jira_fix_versions = [get_version_json(v) for v in fix_versions]
  252. resolve = [a for a in asf_jira.transitions(jira_id) if a['name'] == "Resolve Issue"][0]
  253. resolution = [r for r in asf_jira.resolutions() if r.raw['name'] == "Fixed"][0]
  254. asf_jira.transition_issue(
  255. jira_id, resolve["id"], fixVersions = jira_fix_versions,
  256. comment = comment, resolution = {'id': resolution.raw['id']})
  257. print("Successfully resolved %s with fixVersions=%s!" % (jira_id, fix_versions))
  258. def resolve_jira_issues(title, merge_branches, comment):
  259. jira_ids = re.findall("%s-[0-9]{4,5}" % CAPITALIZED_PROJECT_NAME, title)
  260. if len(jira_ids) == 0:
  261. resolve_jira_issue(merge_branches, comment)
  262. for jira_id in jira_ids:
  263. resolve_jira_issue(merge_branches, comment, jira_id)
  264. def standardize_jira_ref(text):
  265. """
  266. Standardize the jira reference commit message prefix to "PROJECT_NAME-XXX: Issue"
  267. >>> standardize_jira_ref("%s-5954: Top by key" % CAPITALIZED_PROJECT_NAME)
  268. 'ZOOKEEPER-5954: Top by key'
  269. >>> standardize_jira_ref("%s-5821: ParquetRelation2 CTAS should check if delete is successful" % PROJECT_NAME)
  270. 'ZOOKEEPER-5821: ParquetRelation2 CTAS should check if delete is successful'
  271. >>> standardize_jira_ref("%s-4123: [WIP] Show new dependencies added in pull requests" % PROJECT_NAME)
  272. 'ZOOKEEPER-4123: [WIP] Show new dependencies added in pull requests'
  273. >>> standardize_jira_ref("%s 5954: Top by key" % PROJECT_NAME)
  274. 'ZOOKEEPER-5954: Top by key'
  275. >>> standardize_jira_ref("%s-979: a LRU scheduler for load balancing in TaskSchedulerImpl" % PROJECT_NAME)
  276. 'ZOOKEEPER-979: a LRU scheduler for load balancing in TaskSchedulerImpl'
  277. >>> standardize_jira_ref("%s-1094: Support MiMa for reporting binary compatibility across versions." % CAPITALIZED_PROJECT_NAME)
  278. 'ZOOKEEPER-1094: Support MiMa for reporting binary compatibility across versions.'
  279. >>> standardize_jira_ref("%s-1146: [WIP] Vagrant support" % CAPITALIZED_PROJECT_NAME)
  280. 'ZOOKEEPER-1146: [WIP] Vagrant support'
  281. >>> standardize_jira_ref("%s-1032: If Yarn app fails before registering, app master stays aroun..." % PROJECT_NAME)
  282. 'ZOOKEEPER-1032: If Yarn app fails before registering, app master stays aroun...'
  283. >>> standardize_jira_ref("%s-6250 %s-6146 %s-5911: Types are now reserved words in DDL parser." % (PROJECT_NAME, PROJECT_NAME, CAPITALIZED_PROJECT_NAME))
  284. 'ZOOKEEPER-6250 ZOOKEEPER-6146 ZOOKEEPER-5911: Types are now reserved words in DDL parser.'
  285. >>> standardize_jira_ref("Additional information for users building from source code")
  286. 'Additional information for users building from source code'
  287. """
  288. jira_refs = []
  289. components = []
  290. # Extract JIRA ref(s):
  291. pattern = re.compile(r'(%s[-\s]*[0-9]{3,6})+' % CAPITALIZED_PROJECT_NAME, re.IGNORECASE)
  292. for ref in pattern.findall(text):
  293. # Add brackets, replace spaces with a dash, & convert to uppercase
  294. jira_refs.append(re.sub(r'\s+', '-', ref.upper()))
  295. text = text.replace(ref, '')
  296. # Extract project name component(s):
  297. # Look for alphanumeric chars, spaces, dashes, periods, and/or commas
  298. pattern = re.compile(r'(\[[\w\s,-\.]+\])', re.IGNORECASE)
  299. for component in pattern.findall(text):
  300. components.append(component.upper())
  301. text = text.replace(component, '')
  302. # Cleanup any remaining symbols:
  303. pattern = re.compile(r'^\W+(.*)', re.IGNORECASE)
  304. if (pattern.search(text) is not None):
  305. text = pattern.search(text).groups()[0]
  306. # Assemble full text (JIRA ref(s), module(s), remaining text)
  307. jira_prefix = ' '.join(jira_refs).strip()
  308. if jira_prefix:
  309. jira_prefix = jira_prefix + ": "
  310. clean_text = jira_prefix + ' '.join(components).strip() + " " + text.strip()
  311. # Replace multiple spaces with a single space, e.g. if no jira refs and/or components were included
  312. clean_text = re.sub(r'\s+', ' ', clean_text.strip())
  313. return clean_text
  314. def get_remote_repos():
  315. repos = run_cmd("git remote -v").split()
  316. dict = {}
  317. for i in range(0, len(repos), 3):
  318. dict[repos[i]] = repos[i+1]
  319. return dict
  320. def check_git_remote():
  321. repos = get_remote_repos()
  322. # check if all remote endpoints' URLs point to project git repo
  323. name = PROJECT_NAME + ".git"
  324. for url in list(repos.values()):
  325. if not url.endswith(name):
  326. fail("Error: not a %s git repo or at least one remote is invalid" % PROJECT_NAME)
  327. if not PR_REMOTE_NAME in repos:
  328. fail("Error: PR_REMOTE_NAME (%s) environment variable has not been set!" % PR_REMOTE_NAME)
  329. if not PUSH_REMOTE_NAME in repos:
  330. fail("Error: PUSH_REMOTE_NAME (%s) environment variable has not been set!" % PUSH_REMOTE_NAME)
  331. def check_jira_env():
  332. global JIRA_PASSWORD
  333. if JIRA_IMPORTED:
  334. if JIRA_USERNAME.strip() != "" and JIRA_PASSWORD.strip() == "":
  335. inform_pwd = input("JIRA_USERNAME set but JIRA_PASSWORD is not. Want to inform it? ")
  336. if inform_pwd.strip() == "y":
  337. JIRA_PASSWORD = getpass.getpass('JIRA PASSWORD: ')
  338. if JIRA_USERNAME.strip() == "" or JIRA_PASSWORD.strip() == "":
  339. msg ="JIRA_USERNAME and/or JIRA_PASSWORD are not set. Want to continue? "
  340. continue_maybe(msg)
  341. else:
  342. msg = "JIRA lib not installed. Want to continue? "
  343. continue_maybe(msg)
  344. def main():
  345. global original_head
  346. original_head = get_current_branch()
  347. check_jira_env()
  348. check_git_remote()
  349. branches = get_json("%s/branches" % GITHUB_API_BASE)
  350. branch_names = [x for x in [x['name'] for x in branches] if x.startswith(RELEASE_BRANCH_PREFIX)]
  351. # Assumes branch names can be sorted lexicographically
  352. latest_branch = sorted(branch_names, reverse=True)[0]
  353. pr_num = input("Which pull request would you like to merge? (e.g. 34): ")
  354. pr = get_json("%s/pulls/%s" % (GITHUB_API_BASE, pr_num))
  355. pr_events = get_json("%s/issues/%s/events" % (GITHUB_API_BASE, pr_num))
  356. url = pr["url"]
  357. pr_title = pr["title"]
  358. commit_title = input("Commit title [%s]: " % pr_title)
  359. if commit_title == "":
  360. commit_title = pr_title
  361. # Decide whether to use the modified title or not
  362. modified_title = standardize_jira_ref(commit_title)
  363. if modified_title != commit_title:
  364. print("I've re-written the title as follows to match the standard format:")
  365. print("Original: %s" % commit_title)
  366. print("Modified: %s" % modified_title)
  367. result = input("Would you like to use the modified title? (y/n): ")
  368. if result.lower().strip() == "y":
  369. commit_title = modified_title
  370. print("Using modified title:")
  371. else:
  372. print("Using original title:")
  373. print(commit_title)
  374. body = pr["body"]
  375. target_ref = pr["base"]["ref"]
  376. user_login = pr["user"]["login"]
  377. base_ref = pr["head"]["ref"]
  378. pr_repo_desc = "%s/%s" % (user_login, base_ref)
  379. # Merged pull requests don't appear as merged in the GitHub API;
  380. # Instead, they're closed by asfgit.
  381. merge_commits = \
  382. [e for e in pr_events if e["actor"]["login"] == "asfgit" and e["event"] == "closed"]
  383. if merge_commits:
  384. merge_hash = merge_commits[0]["commit_id"]
  385. message = get_json("%s/commits/%s" % (GITHUB_API_BASE, merge_hash))["commit"]["message"]
  386. print("Pull request %s has already been merged, assuming you want to backport" % pr_num)
  387. commit_is_downloaded = run_cmd(['git', 'rev-parse', '--quiet', '--verify',
  388. "%s^{commit}" % merge_hash]).strip() != ""
  389. if not commit_is_downloaded:
  390. fail("Couldn't find any merge commit for #%s, you may need to update HEAD." % pr_num)
  391. print("Found commit %s:\n%s" % (merge_hash, message))
  392. cherry_pick(pr_num, merge_hash, latest_branch)
  393. sys.exit(0)
  394. if not bool(pr["mergeable"]):
  395. msg = "Pull request %s is not mergeable in its current form.\n" % pr_num + \
  396. "Continue? (experts only!)"
  397. continue_maybe(msg)
  398. print(("\n=== Pull Request #%s ===" % pr_num))
  399. print(("PR title\t%s\nCommit title\t%s\nSource\t\t%s\nTarget\t\t%s\nURL\t\t%s" % (
  400. pr_title, commit_title, pr_repo_desc, target_ref, url)))
  401. continue_maybe("Proceed with merging pull request #%s?" % pr_num)
  402. merged_refs = [target_ref]
  403. merge_hash = merge_pr(pr_num, target_ref, commit_title, body, pr_repo_desc)
  404. pick_prompt = "Would you like to pick %s into another branch?" % merge_hash
  405. while input("\n%s (y/n): " % pick_prompt).lower().strip() == "y":
  406. merged_refs = merged_refs + [cherry_pick(pr_num, merge_hash, latest_branch)]
  407. if JIRA_IMPORTED:
  408. if JIRA_USERNAME and JIRA_PASSWORD:
  409. continue_maybe("Would you like to update an associated JIRA?")
  410. jira_comment = "Issue resolved by pull request %s\n[%s/%s]" % (pr_num, GITHUB_BASE, pr_num)
  411. resolve_jira_issues(commit_title, merged_refs, jira_comment)
  412. else:
  413. print("JIRA_USERNAME and JIRA_PASSWORD not set")
  414. print("Exiting without trying to close the associated JIRA.")
  415. else:
  416. print("Could not find jira-python library. Run 'sudo pip install jira' to install.")
  417. print("Exiting without trying to close the associated JIRA.")
  418. if __name__ == "__main__":
  419. import doctest
  420. (failure_count, test_count) = doctest.testmod()
  421. if (failure_count):
  422. exit(-1)
  423. main()