diff --git a/dev/README.md b/dev/README.md index 519e821f6..1171a8fd9 100644 --- a/dev/README.md +++ b/dev/README.md @@ -26,8 +26,7 @@ Merging a pull request requires being a committer on the project. * How to merge a Pull request: have an apache and apache-github remote setup ``` -git remote add apache-github git@github.com:apache/incubator-parquet-format.git -git remote add apache https://git-wip-us.apache.org/repos/asf/incubator-parquet-format.git +git remote add apache git@github.com:apache/parquet-format.git ``` run the following command ``` diff --git a/dev/merge_parquet_pr.py b/dev/merge_parquet_pr.py index b1a63d417..a42319449 100755 --- a/dev/merge_parquet_pr.py +++ b/dev/merge_parquet_pr.py @@ -17,377 +17,563 @@ # limitations under the License. # -# Utility for creating well-formed pull request merges and pushing them to Apache. -# usage: ./apache-pr-merge.py (see config env vars below) +# Utility for creating well-formed pull request merges and pushing them to +# Apache. +# usage: ./merge_parquet_pr.py (see config env vars below) # -# This utility assumes you already have local a Parquet git folder and that you -# have added remotes corresponding to both (i) the github apache Parquet -# mirror and (ii) the apache git repo. +# This utility assumes you already have a local Parquet git clone and that you +# have added remotes corresponding to both (i) the GitHub Apache Parquet mirror +# and (ii) the apache git repo. +# +# There are several pieces of authorization possibly needed via environment +# variables +# +# APACHE_JIRA_USERNAME: your Apache JIRA id +# APACHE_JIRA_PASSWORD: your Apache JIRA password +# PARQUET_GITHUB_API_TOKEN: a GitHub API token to use for API requests (to avoid +# rate limiting) -import json +import configparser import os +import pprint import re import subprocess import sys -import tempfile -import urllib2 +import requests import getpass +from six.moves import input +import six + try: import jira.client - JIRA_IMPORTED = True except ImportError: - JIRA_IMPORTED = False + print("Could not find jira library. " + "Run 'sudo pip install jira' to install.") + print("Exiting without trying to close the associated JIRA.") + sys.exit(1) -# Location of your Parquet git development area -PARQUET_HOME = os.path.abspath(__file__).rsplit("/", 2)[0] -PROJECT_NAME = PARQUET_HOME.rsplit("/", 1)[1] -print "PARQUET_HOME = " + PARQUET_HOME -print "PROJECT_NAME = " + PROJECT_NAME +# Remote name which points to the GitHub site +PR_REMOTE_NAME = os.environ.get("PR_REMOTE_NAME", "apache") -def lines_from_cmd(cmd): - return subprocess.check_output(cmd.split(" ")).strip().split("\n") +# For testing to avoid accidentally pushing to apache +DEBUG = bool(int(os.environ.get("DEBUG", 0))) -# Remote name which points to the GitHub site -PR_REMOTE_NAME = os.environ.get("PR_REMOTE_NAME") -available_remotes = lines_from_cmd("git remote") -if PR_REMOTE_NAME is not None: - if PR_REMOTE_NAME not in available_remotes: - print "ERROR: git remote '%s' is not defined." % PR_REMOTE_NAME - sys.exit(-1) -else: - remote_candidates = ["github-apache", "apache-github"] - # Get first available remote from the list of candidates - PR_REMOTE_NAME = next((remote for remote in available_remotes if remote in remote_candidates), None) - -# Remote name which points to Apache git -PUSH_REMOTE_NAME = os.environ.get("PUSH_REMOTE_NAME", "apache") -# ASF JIRA username -JIRA_USERNAME = os.environ.get("JIRA_USERNAME") -# ASF JIRA password -JIRA_PASSWORD = os.environ.get("JIRA_PASSWORD") - -GITHUB_BASE = "https://github.com/apache/" + PROJECT_NAME + "/pull" -GITHUB_API_BASE = "https://api.github.com/repos/apache/" + PROJECT_NAME -JIRA_BASE = "https://issues.apache.org/jira/browse" -JIRA_API_BASE = "https://issues.apache.org/jira" -# Prefix added to temporary branches -BRANCH_PREFIX = "PR_TOOL" -os.chdir(PARQUET_HOME) +if DEBUG: + print("**************** DEBUGGING ****************") -def get_json(url): - try: - return json.load(urllib2.urlopen(url)) - except urllib2.HTTPError as e: - print "Unable to fetch URL, exiting: %s" % url - sys.exit(-1) +# Prefix added to temporary branches +BRANCH_PREFIX = "PR_TOOL" +JIRA_API_BASE = "https://issues.apache.org/jira" -def fail(msg): - print msg - clean_up() - sys.exit(-1) +def get_json(url, headers=None): + req = requests.get(url, headers=headers) + return req.json() def run_cmd(cmd): + if isinstance(cmd, six.string_types): + cmd = cmd.split(' ') + try: - if isinstance(cmd, list): - return subprocess.check_output(cmd) - else: - return subprocess.check_output(cmd.split(" ")) + output = subprocess.check_output(cmd) except subprocess.CalledProcessError as e: # this avoids hiding the stdout / stderr of failed processes - print 'Command failed: %s' % cmd - print 'With output:' - print '--------------' - print e.output - print '--------------' + print('Command failed: %s' % cmd) + print('With output:') + print('--------------') + print(e.output) + print('--------------') raise e -def continue_maybe(prompt): - result = raw_input("\n%s (y/n): " % prompt) - if result.lower() != "y": - fail("Okay, exiting") + if isinstance(output, six.binary_type): + output = output.decode('utf-8') + return output original_head = run_cmd("git rev-parse HEAD")[:8] def clean_up(): - print "Restoring head pointer to %s" % original_head + print("Restoring head pointer to %s" % original_head) run_cmd("git checkout %s" % original_head) branches = run_cmd("git branch").replace(" ", "").split("\n") - for branch in filter(lambda x: x.startswith(BRANCH_PREFIX), branches): - print "Deleting local branch %s" % branch + for branch in [x for x in branches + if x.startswith(BRANCH_PREFIX)]: + print("Deleting local branch %s" % branch) run_cmd("git branch -D %s" % branch) -# merge the requested PR and return the merge hash -def merge_pr(pr_num, target_ref): - pr_branch_name = "%s_MERGE_PR_%s" % (BRANCH_PREFIX, pr_num) - target_branch_name = "%s_MERGE_PR_%s_%s" % (BRANCH_PREFIX, pr_num, target_ref.upper()) - run_cmd("git fetch %s pull/%s/head:%s" % (PR_REMOTE_NAME, pr_num, pr_branch_name)) - run_cmd("git fetch %s %s:%s" % (PUSH_REMOTE_NAME, target_ref, target_branch_name)) - run_cmd("git checkout %s" % target_branch_name) +_REGEX_CI_DIRECTIVE = re.compile(r'\[[^\]]*\]') - had_conflicts = False - try: - run_cmd(['git', 'merge', pr_branch_name, '--squash']) - except Exception as e: - msg = "Error merging: %s\nWould you like to manually fix-up this merge?" % e - continue_maybe(msg) - msg = "Okay, please fix any conflicts and 'git add' conflicting files... Finished?" - continue_maybe(msg) - had_conflicts = True - commit_authors = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name, - '--pretty=format:%an <%ae>']).split("\n") - distinct_authors = sorted(set(commit_authors), - key=lambda x: commit_authors.count(x), reverse=True) - primary_author = distinct_authors[0] - commits = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name, - '--pretty=format:%h [%an] %s']).split("\n\n") +def strip_ci_directives(commit_message): + # Remove things like '[force ci]', '[skip appveyor]' from the assembled + # commit message + return _REGEX_CI_DIRECTIVE.sub('', commit_message) - merge_message_flags = [] - merge_message_flags += ["-m", title] - if body != None: - merge_message_flags += ["-m", body] +def fix_version_from_branch(branch, versions): + # Note: Assumes this is a sorted (newest->oldest) list of un-released + # versions + if branch == "master": + return versions[-1] + else: + branch_ver = branch.replace("branch-", "") + return [x for x in versions if x.name.startswith(branch_ver)][-1] - authors = "\n".join(["Author: %s" % a for a in distinct_authors]) - merge_message_flags += ["-m", authors] +# We can merge PARQUET patches +SUPPORTED_PROJECTS = ['PARQUET'] +PR_TITLE_REGEXEN = [(project, re.compile(r'^(' + project + r'-[0-9]+)\b.*$')) + for project in SUPPORTED_PROJECTS] - if had_conflicts: - committer_name = run_cmd("git config --get user.name").strip() - committer_email = run_cmd("git config --get user.email").strip() - message = "This patch had conflicts when merged, resolved by\nCommitter: %s <%s>" % ( - committer_name, committer_email) - merge_message_flags += ["-m", message] - # The string "Closes #%s" string is required for GitHub to correctly close the PR - merge_message_flags += [ - "-m", - "Closes #%s from %s and squashes the following commits:" % (pr_num, pr_repo_desc)] - for c in commits: - merge_message_flags += ["-m", c] +class JiraIssue(object): - run_cmd(['git', 'commit', '--author="%s"' % primary_author] + merge_message_flags) + def __init__(self, jira_con, jira_id, project, cmd): + self.jira_con = jira_con + self.jira_id = jira_id + self.project = project + self.cmd = cmd - continue_maybe("Merge complete (local ref %s). Push to %s?" % ( - target_branch_name, PUSH_REMOTE_NAME)) + try: + self.issue = jira_con.issue(jira_id) + except Exception as e: + self.cmd.fail("ASF JIRA could not find %s\n%s" % (jira_id, e)) - try: - run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, target_branch_name, target_ref)) - except Exception as e: - clean_up() - fail("Exception while pushing: %s" % e) + def get_candidate_fix_versions(self, merge_branches=('master',)): + # Only suggest versions starting with a number, like 0.x but not JS-0.x + all_versions = self.jira_con.project_versions(self.project) + unreleased_versions = [x for x in all_versions + if not x.raw['released']] - merge_hash = run_cmd("git rev-parse %s" % target_branch_name)[:8] - clean_up() - print("Pull request #%s merged!" % pr_num) - print("Merge hash: %s" % merge_hash) - return merge_hash + unreleased_versions = sorted(unreleased_versions, + key=lambda x: x.name, reverse=True) + mainline_versions = self._filter_mainline_versions(unreleased_versions) -def cherry_pick(pr_num, merge_hash, default_branch): - pick_ref = raw_input("Enter a branch name [%s]: " % default_branch) - if pick_ref == "": - pick_ref = default_branch + mainline_non_patch_versions = [] + for v in mainline_versions: + (major, minor, patch) = v.name.split(".") + if patch == "0": + mainline_non_patch_versions.append(v) - pick_branch_name = "%s_PICK_PR_%s_%s" % (BRANCH_PREFIX, pr_num, pick_ref.upper()) + if len(mainline_versions) > len(mainline_non_patch_versions): + # If there is a non-patch release, suggest that instead + mainline_versions = mainline_non_patch_versions - run_cmd("git fetch %s %s:%s" % (PUSH_REMOTE_NAME, pick_ref, pick_branch_name)) - run_cmd("git checkout %s" % pick_branch_name) - run_cmd("git cherry-pick -sx %s" % merge_hash) + default_fix_versions = [ + fix_version_from_branch(x, mainline_versions).name + for x in merge_branches] - continue_maybe("Pick complete (local ref %s). Push to %s?" % ( - pick_branch_name, PUSH_REMOTE_NAME)) + return all_versions, default_fix_versions - try: - run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, pick_branch_name, pick_ref)) - except Exception as e: - clean_up() - fail("Exception while pushing: %s" % e) + def _filter_mainline_versions(self, versions): + if self.project == 'PARQUET': + mainline_regex = re.compile(r'cpp-\d.*') + else: + mainline_regex = re.compile(r'\d.*') - pick_hash = run_cmd("git rev-parse %s" % pick_branch_name)[:8] - clean_up() + return [x for x in versions if mainline_regex.match(x.name)] - print("Pull request #%s picked into %s!" % (pr_num, pick_ref)) - print("Pick hash: %s" % pick_hash) - return pick_ref + def resolve(self, fix_versions, comment): + fields = self.issue.fields + cur_status = fields.status.name + if cur_status == "Resolved" or cur_status == "Closed": + self.cmd.fail("JIRA issue %s already has status '%s'" + % (self.jira_id, cur_status)) -def fix_version_from_branch(branch, versions): - # Note: Assumes this is a sorted (newest->oldest) list of un-released versions - if branch == "master": - return versions[0] + resolve = [x for x in self.jira_con.transitions(self.jira_id) + if x['name'] == "Resolve Issue"][0] + self.jira_con.transition_issue(self.jira_id, resolve["id"], + comment=comment, + fixVersions=fix_versions) + + print("Successfully resolved %s!" % (self.jira_id)) + + self.issue = self.jira_con.issue(self.jira_id) + self.show() + + def show(self): + fields = self.issue.fields + print(format_jira_output(self.jira_id, fields.status.name, + fields.summary, fields.assignee, + fields.components)) + + +def format_jira_output(jira_id, status, summary, assignee, components): + if assignee is None: + assignee = "NOT ASSIGNED!!!" else: - branch_ver = branch.replace("branch-", "") - return filter(lambda x: x.name.startswith(branch_ver), versions)[-1] + assignee = assignee.displayName -def exctract_jira_id(title): - m = re.search(r'^(PARQUET-[0-9]+)\b.*$', title, re.IGNORECASE) - if m and m.groups > 0: - return m.group(1).upper() + if len(components) == 0: + components = 'NO COMPONENTS!!!' else: - fail("PR title should be prefixed by a jira id \"PARQUET-XXX: ...\", found: \"%s\"" % title) + components = ', '.join((x.name for x in components)) -def check_jira(title): - jira_id = exctract_jira_id(title) - asf_jira = jira.client.JIRA({'server': JIRA_API_BASE}, - basic_auth=(JIRA_USERNAME, JIRA_PASSWORD)) - try: - issue = asf_jira.issue(jira_id) - except Exception as e: - fail("ASF JIRA could not find %s\n%s" % (jira_id, e)) + return """=== JIRA {} === +Summary\t\t{} +Assignee\t{} +Components\t{} +Status\t\t{} +URL\t\t{}/{}""".format(jira_id, summary, assignee, components, status, + '/'.join((JIRA_API_BASE, 'browse')), jira_id) -def resolve_jira(title, merge_branches, comment): - asf_jira = jira.client.JIRA({'server': JIRA_API_BASE}, - basic_auth=(JIRA_USERNAME, JIRA_PASSWORD)) - default_jira_id = exctract_jira_id(title) +class GitHubAPI(object): - jira_id = raw_input("Enter a JIRA id [%s]: " % default_jira_id) - if jira_id == "": - jira_id = default_jira_id + def __init__(self, project_name): + self.github_api = ("https://api.github.com/repos/apache/{0}" + .format(project_name)) - try: - issue = asf_jira.issue(jira_id) - except Exception as e: - fail("ASF JIRA could not find %s\n%s" % (jira_id, e)) - - cur_status = issue.fields.status.name - cur_summary = issue.fields.summary - cur_assignee = issue.fields.assignee - if cur_assignee is None: - cur_assignee = "NOT ASSIGNED!!!" - else: - cur_assignee = cur_assignee.displayName - - if cur_status == "Resolved" or cur_status == "Closed": - fail("JIRA issue %s already has status '%s'" % (jira_id, cur_status)) - print ("=== JIRA %s ===" % jira_id) - print ("summary\t\t%s\nassignee\t%s\nstatus\t\t%s\nurl\t\t%s/%s\n" % ( - cur_summary, cur_assignee, cur_status, JIRA_BASE, jira_id)) - - versions = asf_jira.project_versions("PARQUET") - versions = sorted(versions, key=lambda x: x.name, reverse=True) - versions = filter(lambda x: x.raw['released'] is False, versions) - - default_fix_versions = map(lambda x: fix_version_from_branch(x, versions).name, merge_branches) - for v in default_fix_versions: - # Handles the case where we have forked a release branch but not yet made the release. - # In this case, if the PR is committed to the master branch and the release branch, we - # only consider the release branch to be the fix version. E.g. it is not valid to have - # both 1.1.0 and 1.0.0 as fix versions. - (major, minor, patch) = v.split(".") - if patch == "0": - previous = "%s.%s.%s" % (major, int(minor) - 1, 0) - if previous in default_fix_versions: - default_fix_versions = filter(lambda x: x != v, default_fix_versions) - default_fix_versions = ",".join(default_fix_versions) + token = os.environ.get('PARQUET_GITHUB_API_TOKEN', None) + if token: + self.headers = {'Authorization': 'token {0}'.format(token)} + else: + self.headers = None - fix_versions = raw_input("Enter comma-separated fix version(s) [%s]: " % default_fix_versions) - if fix_versions == "": - fix_versions = default_fix_versions - fix_versions = fix_versions.replace(" ", "").split(",") + def get_pr_data(self, number): + return get_json("%s/pulls/%s" % (self.github_api, number), + headers=self.headers) - def get_version_json(version_str): - return filter(lambda v: v.name == version_str, versions)[0].raw - jira_fix_versions = map(lambda v: get_version_json(v), fix_versions) +class CommandInput(object): + """ + Interface to input(...) to enable unit test mocks to be created + """ + + def fail(self, msg): + clean_up() + raise Exception(msg) + + def prompt(self, prompt): + return input(prompt) + + def getpass(self, prompt): + return getpass.getpass(prompt) + + def continue_maybe(self, prompt): + while True: + result = input("\n%s (y/n): " % prompt) + if result.lower() == "y": + return + elif result.lower() == "n": + self.fail("Okay, exiting") + else: + prompt = "Please input 'y' or 'n'" - resolve = filter(lambda a: a['name'] == "Resolve Issue", asf_jira.transitions(jira_id))[0] - asf_jira.transition_issue( - jira_id, resolve["id"], fixVersions=jira_fix_versions, comment=comment) - print "Succesfully resolved %s with fixVersions=%s!" % (jira_id, fix_versions) +class PullRequest(object): -if JIRA_IMPORTED: - jira_login_accepted = False - while not jira_login_accepted: - if JIRA_USERNAME: - print "JIRA username: %s" % JIRA_USERNAME + def __init__(self, cmd, github_api, git_remote, jira_con, number): + self.cmd = cmd + self.git_remote = git_remote + self.con = jira_con + self.number = number + self._pr_data = github_api.get_pr_data(number) + try: + self.url = self._pr_data["url"] + self.title = self._pr_data["title"] + self.body = self._pr_data["body"] + self.target_ref = self._pr_data["base"]["ref"] + self.user_login = self._pr_data["user"]["login"] + self.base_ref = self._pr_data["head"]["ref"] + except KeyError: + pprint.pprint(self._pr_data) + raise + self.description = "%s/%s" % (self.user_login, self.base_ref) + + self.jira_issue = self._get_jira() + + def show(self): + print("\n=== Pull Request #%s ===" % self.number) + print("title\t%s\nsource\t%s\ntarget\t%s\nurl\t%s" + % (self.title, self.description, self.target_ref, self.url)) + self.jira_issue.show() + + @property + def is_merged(self): + return bool(self._pr_data["merged"]) + + @property + def is_mergeable(self): + return bool(self._pr_data["mergeable"]) + + def _get_jira(self): + jira_id = None + for project, regex in PR_TITLE_REGEXEN: + m = regex.search(self.title) + if m: + jira_id = m.group(1) + break + + if jira_id is None: + options = ' or '.join('{0}-XXX'.format(project) + for project in SUPPORTED_PROJECTS) + self.cmd.fail("PR title should be prefixed by a jira id " + "{0}, but found {1}".format(options, self.title)) + + return JiraIssue(self.con, jira_id, project, self.cmd) + + def merge(self): + """ + merge the requested PR and return the merge hash + """ + pr_branch_name = "%s_MERGE_PR_%s" % (BRANCH_PREFIX, self.number) + target_branch_name = "%s_MERGE_PR_%s_%s" % (BRANCH_PREFIX, + self.number, + self.target_ref.upper()) + run_cmd("git fetch %s pull/%s/head:%s" % (self.git_remote, + self.number, + pr_branch_name)) + run_cmd("git fetch %s %s:%s" % (self.git_remote, self.target_ref, + target_branch_name)) + run_cmd("git checkout %s" % target_branch_name) + + had_conflicts = False + try: + run_cmd(['git', 'merge', pr_branch_name, '--ff', '--squash']) + except Exception as e: + msg = ("Error merging: %s\nWould you like to " + "manually fix-up this merge?" % e) + self.cmd.continue_maybe(msg) + msg = ("Okay, please fix any conflicts and 'git add' " + "conflicting files... Finished?") + self.cmd.continue_maybe(msg) + had_conflicts = True + + commit_authors = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name, + '--pretty=format:%an <%ae>']).split("\n") + distinct_authors = sorted(set(commit_authors), + key=lambda x: commit_authors.count(x), + reverse=True) + + for i, author in enumerate(distinct_authors): + print("Author {}: {}".format(i + 1, author)) + + if len(distinct_authors) > 1: + primary_author, distinct_authors = get_primary_author( + self.cmd, distinct_authors) else: - JIRA_USERNAME = raw_input("Enter JIRA username: ") + # If there is only one author, do not prompt for a lead author + primary_author = distinct_authors[0] + + commits = run_cmd(['git', 'log', 'HEAD..%s' % pr_branch_name, + '--pretty=format:%h <%an> %s']).split("\n\n") + + merge_message_flags = [] + + merge_message_flags += ["-m", self.title] + if self.body is not None: + merge_message_flags += ["-m", self.body] - if not JIRA_PASSWORD: - JIRA_PASSWORD = getpass.getpass("Enter JIRA password: ") + committer_name = run_cmd("git config --get user.name").strip() + committer_email = run_cmd("git config --get user.email").strip() + + authors = ("Authored-by:" if len(distinct_authors) == 1 + else "Lead-authored-by:") + authors += " %s" % (distinct_authors.pop(0)) + if len(distinct_authors) > 0: + authors += "\n" + "\n".join(["Co-authored-by: %s" % a + for a in distinct_authors]) + authors += "\n" + "Signed-off-by: %s <%s>" % (committer_name, + committer_email) + + if had_conflicts: + committer_name = run_cmd("git config --get user.name").strip() + committer_email = run_cmd("git config --get user.email").strip() + message = ("This patch had conflicts when merged, " + "resolved by\nCommitter: %s <%s>" % + (committer_name, committer_email)) + merge_message_flags += ["-m", message] + + # The string "Closes #%s" string is required for GitHub to correctly + # close the PR + merge_message_flags += [ + "-m", + "Closes #%s from %s and squashes the following commits:" + % (self.number, self.description)] + for c in commits: + stripped_message = strip_ci_directives(c).strip() + merge_message_flags += ["-m", stripped_message] + + merge_message_flags += ["-m", authors] + + if DEBUG: + print("\n".join(merge_message_flags)) + + run_cmd(['git', 'commit', + '--no-verify', # do not run commit hooks + '--author="%s"' % primary_author] + + merge_message_flags) + + self.cmd.continue_maybe("Merge complete (local ref %s). Push to %s?" + % (target_branch_name, self.git_remote)) try: - asf_jira = jira.client.JIRA({'server': JIRA_API_BASE}, - basic_auth=(JIRA_USERNAME, JIRA_PASSWORD)) - jira_login_accepted = True + push_cmd = ('git push %s %s:%s' % (self.git_remote, + target_branch_name, + self.target_ref)) + if DEBUG: + print(push_cmd) + else: + run_cmd(push_cmd) except Exception as e: - print "\nJIRA login failed, try again\n" - JIRA_USERNAME = None - JIRA_PASSWORD = None -else: - print "WARNING: Could not find jira python library. Run 'sudo pip install jira' to install." - print "The tool will continue to run but won't handle the JIRA." - print - -branches = get_json("%s/branches" % GITHUB_API_BASE) -branch_names = filter(lambda x: x.startswith("branch-"), [x['name'] for x in branches]) -# Assumes branch names can be sorted lexicographically -# Julien: I commented this out as we don't have any "branch-*" branch yet -#latest_branch = sorted(branch_names, reverse=True)[0] - -pr_num = raw_input("Which pull request would you like to merge? (e.g. 34): ") -pr = get_json("%s/pulls/%s" % (GITHUB_API_BASE, pr_num)) - -url = pr["url"] -title = pr["title"] -if JIRA_IMPORTED: - check_jira(title) -body = pr["body"] -target_ref = pr["base"]["ref"] -user_login = pr["user"]["login"] -base_ref = pr["head"]["ref"] -pr_repo_desc = "%s/%s" % (user_login, base_ref) - -if pr["merged"] is True: - print "Pull request %s has already been merged, assuming you want to backport" % pr_num - merge_commit_desc = run_cmd([ - 'git', 'log', '--merges', '--first-parent', - '--grep=pull request #%s' % pr_num, '--oneline']).split("\n")[0] - if merge_commit_desc == "": - fail("Couldn't find any merge commit for #%s, you may need to update HEAD." % pr_num) - - merge_hash = merge_commit_desc[:7] - message = merge_commit_desc[8:] - - print "Found: %s" % message - maybe_cherry_pick(pr_num, merge_hash, latest_branch) - sys.exit(0) - -if not bool(pr["mergeable"]): - msg = "Pull request %s is not mergeable in its current form.\n" % pr_num + \ - "Continue? (experts only!)" - continue_maybe(msg) - -print ("\n=== Pull Request #%s ===" % pr_num) -print ("title\t%s\nsource\t%s\ntarget\t%s\nurl\t%s" % ( - title, pr_repo_desc, target_ref, url)) -continue_maybe("Proceed with merging pull request #%s?" % pr_num) - -merged_refs = [target_ref] - -merge_hash = merge_pr(pr_num, target_ref) - -pick_prompt = "Would you like to pick %s into another branch?" % merge_hash -while raw_input("\n%s (y/n): " % pick_prompt).lower() == "y": - merged_refs = merged_refs + [cherry_pick(pr_num, merge_hash, latest_branch)] - -if JIRA_IMPORTED: - continue_maybe("Would you like to update the associated JIRA?") - jira_comment = "Issue resolved by pull request %s\n[%s/%s]" % (pr_num, GITHUB_BASE, pr_num) - resolve_jira(title, merged_refs, jira_comment) -else: - print "WARNING: Could not find jira python library. Run 'sudo pip install jira' to install." - print "Exiting without trying to close the associated JIRA." + clean_up() + self.cmd.fail("Exception while pushing: %s" % e) + + merge_hash = run_cmd("git rev-parse %s" % target_branch_name)[:8] + clean_up() + print("Pull request #%s merged!" % self.number) + print("Merge hash: %s" % merge_hash) + return merge_hash + + +def get_primary_author(cmd, distinct_authors): + author_pat = re.compile(r'(.*) <(.*)>') + + while True: + primary_author = cmd.prompt( + "Enter primary author in the format of " + "\"name \" [%s]: " % distinct_authors[0]) + + if primary_author == "": + return distinct_authors[0], distinct_authors + + if author_pat.match(primary_author): + break + print('Bad author "{}", please try again'.format(primary_author)) + + # When primary author is specified manually, de-dup it from + # author list and put it at the head of author list. + distinct_authors = [x for x in distinct_authors + if x != primary_author] + distinct_authors = [primary_author] + distinct_authors + return primary_author, distinct_authors + + +def prompt_for_fix_version(cmd, jira_issue): + (all_versions, + default_fix_versions) = jira_issue.get_candidate_fix_versions() + + default_fix_versions = ",".join(default_fix_versions) + + issue_fix_versions = cmd.prompt("Enter comma-separated " + "fix version(s) [%s]: " + % default_fix_versions) + if issue_fix_versions == "": + issue_fix_versions = default_fix_versions + issue_fix_versions = issue_fix_versions.replace(" ", "").split(",") + + def get_version_json(version_str): + return [x for x in all_versions if x.name == version_str][0].raw + + return [get_version_json(v) for v in issue_fix_versions] + + +CONFIG_FILE = "~/.config/parquet/merge.conf" + + +def load_configuration(): + config = configparser.ConfigParser() + config.read(os.path.expanduser(CONFIG_FILE)) + return config + + +def get_credentials(cmd): + username, password = None, None + + config = load_configuration() + if "jira" in config.sections(): + username = config["jira"].get("username") + password = config["jira"].get("password") + + # Fallback to environment variables + if not username: + username = os.environ.get("APACHE_JIRA_USERNAME") + + if not password: + password = os.environ.get("APACHE_JIRA_PASSWORD") + + # Fallback to user tty prompt + if not username: + username = cmd.prompt("Env APACHE_JIRA_USERNAME not set, " + "please enter your JIRA username:") + + if not password: + password = cmd.getpass("Env APACHE_JIRA_PASSWORD not set, " + "please enter your JIRA password:") + + return (username, password) + + +def connect_jira(cmd): + return jira.client.JIRA({'server': JIRA_API_BASE}, + basic_auth=get_credentials(cmd)) + + +def get_pr_num(): + if len(sys.argv) == 2: + return sys.argv[1] + + return input("Which pull request would you like to merge? (e.g. 34): ") + + +def cli(): + # Location of your Parquet git clone + PARQUET_HOME = os.path.abspath(os.path.dirname(__file__)) + PROJECT_NAME = os.environ.get('PARQUET_PROJECT_NAME') or 'parquet-format' + print("PARQUET_HOME = " + PARQUET_HOME) + print("PROJECT_NAME = " + PROJECT_NAME) + + cmd = CommandInput() + + pr_num = get_pr_num() + + os.chdir(PARQUET_HOME) + + github_api = GitHubAPI(PROJECT_NAME) + + jira_con = connect_jira(cmd) + pr = PullRequest(cmd, github_api, PR_REMOTE_NAME, jira_con, pr_num) + + if pr.is_merged: + print("Pull request %s has already been merged") + sys.exit(0) + + if not pr.is_mergeable: + msg = ("Pull request %s is not mergeable in its current form.\n" + % pr_num + "Continue? (experts only!)") + cmd.continue_maybe(msg) + + pr.show() + + cmd.continue_maybe("Proceed with merging pull request #%s?" % pr_num) + + # merged hash not used + pr.merge() + + cmd.continue_maybe("Would you like to update the associated JIRA?") + jira_comment = ( + "Issue resolved by pull request %s\n[%s/%s]" + % (pr_num, + "https://github.com/apache/" + PROJECT_NAME + "/pull", + pr_num)) + + fix_versions_json = prompt_for_fix_version(cmd, pr.jira_issue) + pr.jira_issue.resolve(fix_versions_json, jira_comment) + + +if __name__ == '__main__': + try: + cli() + except Exception: + raise