def fixPullRequestTitle(pullRequestId): gho = GitHub(githubUser, githubPassword) oPull = gho.pull_request(githubOwner, githubRepository, str(pullRequestId)) branchName = oPull.head.ref issueKey = extractIssueKey(branchName) title = oPull.title foundIndex = title.find(issueKey) updateRequired = 0 if foundIndex == 0: if issueKey == title: updateRequired = 1 print 'Issue Key ' + issueKey + ' Found in Title but Update Required for ' + title else: print 'Issue Key ' + issueKey + ' found in Title for ' + title return else: updateRequired = 1 print 'Issue Key ' + issueKey + ' NOT Found in Title for ' + title if updateRequired == 1: jiraIssue = jiraGetIssueInfo(issueKey, config) title = issueKey + ' ' + jiraIssue.fields.summary print title oPull.update(title) print 'Updated the Title for the Pull Request ' + oPull.html_url
def set_pull_request_status(pr, state, target_url="", description='', user=None, credfile='gh.cred'): """Sets a state for every commit associated ith a pull request. Parameters ---------- pr : PullRequest or len-3 sequence A github3 pull request object or a tuple of (owner, repository, number). state : str Accepted values are 'pending', 'success', 'error', 'failure'. target_url : str, optional URL to link with this status. description : str, optional Flavor text. user : str, None, or NotSpecified, optional The username to log into github with. credfile : str, optional The github credentials file name. """ gh = GitHub() ensure_logged_in(gh, user=user, credfile=credfile) if isinstance(pr, Sequence): r = gh.repository(*pr[:2]) pr = gh.pull_request(*pr) else: #r = gh.repository(*pr.repository) Broken on github3.py v0.8+ r = gh.repository(*pr.base.repo) status = r.create_status(pr.head.sha, state=state, target_url=target_url, description=description)
class GitHubApi: """ GitHub API interaction using github3 """ def __init__(self, repo_owner, repo_name, token): self.repo_owner = repo_owner self.repo_name = repo_name self.gh = GitHub(token=token) def get_issues(self, label=None): """Returns all issues (matching label)""" return self.gh.iter_repo_issues(self.repo_owner, self.repo_name, labels=label) def get_issue(self, issue_id): """Returns issue""" return self.gh.issue(self.repo_owner, self.repo_name, issue_id) def get_matching_pull_requests(self, label=None): """ Returns all matching issues Pull requests are treated as issues """ pull_request_list = [] for issue in self.get_issues(label): # Get Pull Request pull_request_list.append(self.pull_request_information(issue.number)) return pull_request_list def get_pull_request_status(self, label=None): """Returns string containing status of pull requests""" pull_requests = self.get_matching_pull_requests(label) pull_requests_information = "Pull Requests - %s\n\n" % label for pr in pull_requests: pull_requests_information += "Title: %s\nBranch: %s\nLink: %s\nMergeable: %s\n\n"\ % (pr.title, pr.head.ref, pr.html_url, pr.mergeable) return pull_requests_information def pull_request_information(self, pull_request_id): """Returns specified pull request""" pull_request = self.gh.pull_request(self.repo_owner, self.repo_name, pull_request_id) return pull_request def assign_new_label_to_issue(self, branch, label, who): """Update issue label""" # Find issue issue = self.filter_on_branch(self.get_matching_pull_requests(), branch) # Remove all existing labels issue.remove_all_labels() # Add label 'release' issue.add_labels(label) # Add comment for tracking issue.create_comment("%s assigned label '%s' via hipchat" % (who, label)) def filter_on_branch(self, pull_requests, branch): for pull_request in pull_requests: if pull_request.head.ref == branch: # Get issue return self.get_issue(pull_request.number)
def response(self, rc): rawdata = json.loads(request.data) if 'pull_request' not in rawdata: return "\n", None action = rawdata['action'] if action not in self._action_to_event: # Can be one of 'opened', 'closed', 'synchronize', or 'reopened', # but we only care about "opened" and "synchronize". return "\n", None gh = GitHub() pr = gh.pull_request(rc.github_owner, rc.github_repo, rawdata['number']) event = Event(name=self._action_to_event[action], data=pr) return request.method + ": github\n", event
class GitHubRepository(): """Wrapper around GitHub API. Used to access public data.""" def __init__(self, owner, repo_name, token=''): """Build the GitHub API URL which points to the definition of the repository. Args: owner (str): the owner's GitHub username repo_name (str): the name of the repository token (str): the GitHub API token Returns: dict: a representation of the repo definition """ self._github_repository = GitHub(token=token).repository(owner, repo_name) @property def definition(self): """Fetch the definition of the repository, exposed by the GitHub API. Returns: dict: a representation of the repo definition """ return self._github_repository.as_dict() def get_commit(self, commit_hash): """Fetch the definition of the commit, exposed by the GitHub API. Args: commit_hash (str): the hash of the git commit Returns: dict: a representation of the commit """ return self._github_repository.commit(commit_hash).as_dict() def get_pull_request(self, pull_request_number): """Fetch the definition of the pull request, exposed by the GitHub API. Args: pull_request_number (int): the ID of the pull request Returns: dict: a representation of the pull request """ return self._github_repository.pull_request(pull_request_number).as_dict() def get_release(self, tag_name): """Fetch the definition of the release matching the tag name. Args: tag_name (str): the tag linked to the release Returns: dict: a representation of the tag """ return self._github_repository.release_from_tag(tag_name).as_dict() def get_tag_hash(self, tag_name): """Fetch the commit hash that was tagged with ``tag_name``. Args: tag_name (str): the name of the tag Returns: str: the commit hash linked by the tag """ tag_object = get_single_item_from_sequence( sequence=self._github_repository.tags(), condition=lambda tag: tag.name == tag_name, no_item_error_message='No tag "{}" exist'.format(tag_name), too_many_item_error_message='Too many tags "{}" found'.format(tag_name), ) return tag_object.commit.sha async def has_commit_landed_on_repository(self, context, revision): """Tell if a commit was landed on the repository or if it just comes from a pull request. Args: context (scriptworker.context.Context): the scriptworker context. revision (str): the commit hash or the tag name. Returns: bool: True if the commit is present in one of the branches of the main repository """ # Revision may be a tag name. `branch_commits` doesn't work on tags if not _is_git_full_hash(revision): revision = self.get_tag_hash(tag_name=revision) repo = self._github_repository.html_url url = '/'.join([repo.rstrip('/'), 'branch_commits', revision]) html_data = await retry_request(context, url) html_text = html_data.strip() # https://github.com/{repo_owner}/{repo_name}/branch_commits/{revision} just returns some \n # when the commit hasn't landed on the origin repo. Otherwise, some HTML data is returned - it # represents the branches on which the given revision is present. return html_text != ''
class GitHubRepository: """Wrapper around GitHub API. Used to access public data.""" def __init__(self, owner, repo_name, token=""): """Build the GitHub API URL which points to the definition of the repository. Args: owner (str): the owner's GitHub username repo_name (str): the name of the repository token (str): the GitHub API token Returns: dict: a representation of the repo definition """ self._github_repository = GitHub(token=token).repository( owner, repo_name) @property def definition(self): """Fetch the definition of the repository, exposed by the GitHub API. Returns: dict: a representation of the repo definition """ return self._github_repository.as_dict() @retry_async_decorator(retry_exceptions=GitHubException) async def get_commit(self, commit_hash): """Fetch the definition of the commit, exposed by the GitHub API. Args: commit_hash (str): the hash of the git commit Returns: dict: a representation of the commit """ return self._github_repository.commit(commit_hash).as_dict() @retry_async_decorator(retry_exceptions=GitHubException) async def get_pull_request(self, pull_request_number): """Fetch the definition of the pull request, exposed by the GitHub API. Args: pull_request_number (int): the ID of the pull request Returns: dict: a representation of the pull request """ return self._github_repository.pull_request( pull_request_number).as_dict() @retry_async_decorator(retry_exceptions=GitHubException) async def get_release(self, tag_name): """Fetch the definition of the release matching the tag name. Args: tag_name (str): the tag linked to the release Returns: dict: a representation of the tag """ return self._github_repository.release_from_tag(tag_name).as_dict() @retry_async_decorator(retry_exceptions=GitHubException) async def get_tag_hash(self, tag_name): """Fetch the commit hash that was tagged with ``tag_name``. Args: tag_name (str): the name of the tag Returns: str: the commit hash linked by the tag """ tag_object = get_single_item_from_sequence( sequence=self._github_repository.tags(), condition=lambda tag: tag.name == tag_name, no_item_error_message='No tag "{}" exist'.format(tag_name), too_many_item_error_message='Too many tags "{}" found'.format( tag_name), ) return tag_object.commit.sha async def has_commit_landed_on_repository(self, context, revision): """Tell if a commit was landed on the repository or if it just comes from a pull request. Args: context (scriptworker.context.Context): the scriptworker context. revision (str): the commit hash or the tag name. Returns: bool: True if the commit is present in one of the branches of the main repository """ if any( vcs_rule.get("require_secret") for vcs_rule in context.config["trusted_vcs_rules"]): # This check uses unofficial API on github, which we can't easily # check for private repos, assume its true in the private case. log.info( "has_commit_landed_on_repository() not implemented for private" "repositories, assume True") return True # Revision may be a tag name. `branch_commits` doesn't work on tags if not _is_git_full_hash(revision): revision = await self.get_tag_hash(tag_name=revision) html_text = await _fetch_github_branch_commits_data( context, self._github_repository.html_url, revision) # https://github.com/{repo_owner}/{repo_name}/branch_commits/{revision} just returns some \n # when the commit hasn't landed on the origin repo. Otherwise, some HTML data is returned - it # represents the branches on which the given revision is present. return html_text != ""
class GitHubRepository(): """Wrapper around GitHub API. Used to access public data.""" def __init__(self, owner, repo_name, token=''): """Build the GitHub API URL which points to the definition of the repository. Args: owner (str): the owner's GitHub username repo_name (str): the name of the repository token (str): the GitHub API token Returns: dict: a representation of the repo definition """ self._github_repository = GitHub(token=token).repository( owner, repo_name) @property def definition(self): """Fetch the definition of the repository, exposed by the GitHub API. Returns: dict: a representation of the repo definition """ return self._github_repository.as_dict() def get_commit(self, commit_hash): """Fetch the definition of the commit, exposed by the GitHub API. Args: commit_hash (str): the hash of the git commit Returns: dict: a representation of the commit """ return self._github_repository.commit(commit_hash).as_dict() def get_pull_request(self, pull_request_number): """Fetch the definition of the pull request, exposed by the GitHub API. Args: pull_request_number (int): the ID of the pull request Returns: dict: a representation of the pull request """ return self._github_repository.pull_request( pull_request_number).as_dict() def get_release(self, tag_name): """Fetch the definition of the release matching the tag name. Args: tag_name (str): the tag linked to the release Returns: dict: a representation of the tag """ return self._github_repository.release_from_tag(tag_name).as_dict() def get_tag_hash(self, tag_name): """Fetch the commit hash that was tagged with ``tag_name``. Args: tag_name (str): the name of the tag Returns: str: the commit hash linked by the tag """ tag_object = get_single_item_from_sequence( sequence=self._github_repository.tags(), condition=lambda tag: tag.name == tag_name, no_item_error_message='No tag "{}" exist'.format(tag_name), too_many_item_error_message='Too many tags "{}" found'.format( tag_name), ) return tag_object.commit.sha async def has_commit_landed_on_repository(self, context, revision): """Tell if a commit was landed on the repository or if it just comes from a pull request. Args: context (scriptworker.context.Context): the scriptworker context. revision (str): the commit hash or the tag name. Returns: bool: True if the commit is present in one of the branches of the main repository """ # Revision may be a tag name. `branch_commits` doesn't work on tags if not _is_git_full_hash(revision): revision = self.get_tag_hash(tag_name=revision) repo = self._github_repository.html_url url = '/'.join([repo.rstrip('/'), 'branch_commits', revision]) from scriptworker.task import get_decision_task_id cache_key = '{}-{}'.format(get_decision_task_id(context.task), url) async with _branch_commits_cache_lock: if cache_key in _branch_commits_cache: html_text = _branch_commits_cache[cache_key] else: html_data = await retry_request(context, url) html_text = html_data.strip() _branch_commits_cache[cache_key] = html_text # https://github.com/{repo_owner}/{repo_name}/branch_commits/{revision} just returns some \n # when the commit hasn't landed on the origin repo. Otherwise, some HTML data is returned - it # represents the branches on which the given revision is present. return html_text != ''
if len(sys.argv) > 1: pullRequestId = sys.argv[1] else: pullRequestId = raw_input("Enter the Pull Request number: ") if len(sys.argv) > 2: repositoryName = sys.argv[2] # Project Key for JIRA if len(sys.argv) > 3: projectKey = sys.argv[3] # Get the Pull Request Information gho = GitHub(githubUser, githubPassword) oPullRequest = gho.pull_request(githubOwner, githubRepository, str(pullRequestId)) oGithubIssue = gho.issue(githubOwner, githubRepository, str(pullRequestId)) branchName = oPullRequest.head.ref revisionNo = oPullRequest.head.sha issueKey = extractIssueKey(branchName) print "Issue Key is", issueKey # oGitHub = GitHub(githubUser, githubPassword) issue = jira.issue(issueKey) print "Information about Issue:", issueKey print 'summary:', issue.fields.summary print 'Reporter:', issue.fields.reporter.name print 'Assignee:', issue.fields.assignee.name print 'Description:', issue.fields.description
if len(sys.argv) > 1: pullRequestId = sys.argv[1] else: pullRequestId = raw_input("Enter the Pull Request number: ") if len(sys.argv) > 2: repositoryName = sys.argv[2] # Project Key for JIRA if len(sys.argv) > 3: projectKey = sys.argv[3] # Get the Pull Request Information gho = GitHub(githubUser, githubPassword) oPullRequest = gho.pull_request(githubOwner, githubRepository, str(pullRequestId)) oGithubIssue = gho.issue(githubOwner, githubRepository, str(pullRequestId)) branchName = oPullRequest.head.ref revisionNo = oPullRequest.head.sha issueKey = extractIssueKey(branchName) print "Issue Key is", issueKey # oGitHub = GitHub(githubUser, githubPassword) issue = jira.issue(issueKey) print "Information about Issue:", issueKey print 'summary:', issue.fields.summary print 'Reporter:', issue.fields.reporter.name print 'Assignee:', issue.fields.assignee.name print 'Description:', issue.fields.description