Python github.GithubException() Examples

The following are 30 code examples of github.GithubException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module github , or try the search function .
Example #1
Source File: test_gpr.py    From git-pull-request with Apache License 2.0 6 votes vote down vote up
def test_no_message(self):
        e = github.GithubException(
            422,
            {
                "message": "Validation Failed",
                "documentation_url": "https://developer.github.com/v3/pulls/#create-a-pull-request",
                "errors": [
                    {"resource": "PullRequest", "field": "head", "code": "invalid"}
                ],
            },
        )
        self.assertEqual(
            "Unable to create pull request: Validation Failed (422)\n\n"
            "Check "
            "https://developer.github.com/v3/pulls/#create-a-pull-request "
            "for more information.",
            gpr._format_github_exception("create pull request", e),
        ) 
Example #2
Source File: test_github.py    From ogr with MIT License 6 votes vote down vote up
def test_set_commit_status_long_description(self):
        long_description = (
            "Testing the trimming of the description after an argument trim "
            "is added. The argument defaults to False, but in packit-service the"
            " argument trim is set to True."
        )
        with pytest.raises(GithubException):
            self.ogr_project.set_commit_status(
                commit="c891a9e4ac01e6575f3fd66cf1b7db2f52f10128",
                state=CommitStatus.success,
                target_url="https://github.com/packit-service/ogr",
                description=long_description,
                context="test",
            )

        status = self.ogr_project.set_commit_status(
            commit="c891a9e4ac01e6575f3fd66cf1b7db2f52f10128",
            state=CommitStatus.success,
            target_url="https://github.com/packit-service/ogr",
            description=long_description,
            context="test",
            trim=True,
        )
        assert status
        assert len(status.comment) == 140 
Example #3
Source File: util.py    From mycroft-skills-kit with Apache License 2.0 6 votes vote down vote up
def create_or_edit_pr(title: str, body: str, skills_repo: Repository,
                      user, branch: str, repo_branch: str):
    base = repo_branch
    head = '{}:{}'.format(user.login, branch)
    pulls = list(skills_repo.get_pulls(base=base, head=head))
    if pulls:
        pull = pulls[0]
        if 'mycroft-skills-kit' in pull.body:
            pull.edit(title, body)
        else:
            raise PRModified('Not updating description since it was not autogenerated')
        return pull
    else:
        try:
            return skills_repo.create_pull(title, body, base=base, head=head)
        except GithubException as e:
            if e.status == 422:
                raise SkillNameTaken(title) from e
            raise 
Example #4
Source File: test_gpr.py    From git-pull-request with Apache License 2.0 6 votes vote down vote up
def test_issue_12(self):
        e = github.GithubException(
            422,
            {
                u"documentation_url": u"https://developer.github.com/v3/pulls/#create-a-pull-request",
                u"message": u"Validation Failed",
                u"errors": [
                    {
                        u"message": u"No commits between issues-221 and issues-221",
                        u"code": u"custom",
                        u"resource": u"PullRequest",
                    }
                ],
            },
        )
        self.assertEqual(
            "Unable to create pull request: Validation Failed (422)\n"
            "No commits between issues-221 and issues-221\n"
            "Check "
            "https://developer.github.com/v3/pulls/#create-a-pull-request "
            "for more information.",
            gpr._format_github_exception("create pull request", e),
        ) 
Example #5
Source File: app.py    From kle_render with MIT License 6 votes vote down vote up
def index():
    form = InputForm()
    if form.validate_on_submit():
        if len(form.url.data) > 0:
            try:
                files = github_api.get_gist(form.url.data.split('gists/', 1)[1]).files
                layout = next(v for k, v in files.items() if k.endswith('.kbd.json'))
                img = Keyboard(json.loads(layout.content)).render()
                return serve_pil_image(img)
            except (IndexError, github.GithubException):
                flash('Not a valid Keyboard Layout Editor gist')
        elif form.json.data:
            try:
                content = json.loads(form.json.data.read().decode('utf-8'))
                img = Keyboard(content).render()
                return serve_pil_image(img)
            except ValueError:
                flash(Markup('Invalid JSON input - see (?) for help'))
    flash_errors(form)
    return render_template('index.html', form=form) 
Example #6
Source File: connection.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def connect(self, params={}):
        self.logger.info("Connect: Connecting..")
        try:
            self.username = params.get('credentials').get("username")
            self.secret = params.get("credentials").get('password')
            self.basic_auth = (self.username, self.secret)
            self.github_session = requests.Session()
            self.github_user = github.Github(self.username, self.secret)
            user_info = self.github_user.get_user()
            self.user = self.github_user.get_user(self.username)
            self.github_session_user = requests.get(self.api_prefix, auth=(self.username, self.secret), verify=True)
            if str(self.github_session_user.status_code).startswith('2'):
                self.logger.info('Connect: Login successful')
            else:
                self.logger.info('Connect: Login unsuccessful')

        except github.GithubException as err:
            self.logger.error('Github: Connect: error %s', err.data)
            raise Exception('Github: Connect: user could not be authenticated please try again.')

        except requests.exceptions.RequestException as e:
            raise e 
Example #7
Source File: GitWrapper.py    From ngraph-onnx with Apache License 2.0 6 votes vote down vote up
def get_git_time(self):
        """Retrieve time from GitHub.

        Used to reliably determine time during Watchdog run.

        :return:                    Datetime object describing current time
        :rtype:                     datetime
        """
        try:
            datetime_object = self._get_git_time()
        except ValueError as e:
            raise GitWrapperError(str(e))
        except GithubException as e:
            message = 'GitHub Exception during API status retrieval. Exception: {}'.format(str(e))
            raise GitWrapperError(message)
        except timeout_decorator.TimeoutError:
            message = 'GitHub Exception during API status retrieval. Timeout during API request.'
            raise GitWrapperError(message)
        return datetime_object 
Example #8
Source File: views.py    From restful-apis-example with MIT License 6 votes vote down vote up
def github_client(request):
    search_result = {}
    if 'username' in request.GET:
        username = request.GET['username']
        client = Github()

        try:
            user = client.get_user(username)
            search_result['name'] = user.name
            search_result['login'] = user.login
            search_result['public_repos'] = user.public_repos
            search_result['success'] = True
        except GithubException as ge:
            search_result['message'] = ge.data['message']
            search_result['success'] = False

        rate_limit = client.get_rate_limit()
        search_result['rate'] = {
            'limit': rate_limit.rate.limit,
            'remaining': rate_limit.rate.remaining,
        }

    return render(request, 'core/github.html', {'search_result': search_result}) 
Example #9
Source File: github.py    From pyup with MIT License 6 votes vote down vote up
def get_pull_request_permissions(self, user, repo):
        # it's impossible to call this as an integration
        if self.integration:
            return True

        try:
            # first, invite the bot to be a collaborator
            invite = repo.add_to_collaborators(user.login)
            # second, accept the invitation
            if invite:
                user.accept_invitation(invite)
        except GithubException:
            msg = "Unable to add {login} as a collaborator on {repo}.".format(
                login=user.login,
                repo=repo.full_name
            )
            logger.error(msg, exc_info=True)
            raise NoPermissionError(msg) 
Example #10
Source File: github.py    From Lintly with MIT License 6 votes vote down vote up
def translate_github_exception(func):
    """
    Decorator to catch GitHub-specific exceptions and raise them as GitClientError exceptions.
    """

    @functools.wraps(func)
    def _wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except UnknownObjectException as e:
            logger.exception('GitHub API 404 Exception')
            raise NotFoundError(str(e))
        except GithubException as e:
            logger.exception('GitHub API Exception')
            raise GitClientError(str(e))

    return _wrapper 
Example #11
Source File: repo.py    From TagBot with MIT License 6 votes vote down vote up
def handle_error(self, e: Exception) -> None:
        """Handle an unexpected error."""
        allowed = False
        trace = traceback.format_exc()
        if isinstance(e, RequestException):
            logger.warning("TagBot encountered a likely transient HTTP exception")
            logger.info(trace)
            allowed = True
        elif isinstance(e, GithubException):
            if 500 <= e.status < 600:
                logger.warning("GitHub returned a 5xx error code")
                logger.info(trace)
                allowed = True
        if not allowed:
            logger.error("TagBot experienced an unexpected internal failure")
            logger.info(trace)
            try:
                self._report_error(trace)
            except Exception:
                logger.error("Issue reporting failed")
                logger.info(traceback.format_exc()) 
Example #12
Source File: bot_framework.py    From azure-python-devtools with MIT License 5 votes vote down vote up
def manage_comment(self, webhook_data):
        if webhook_data is None:
            return {'message': 'Nothing for me'}
        # Is someone talking to me:
        message = re.search("@{} (.*)".format(self.robot_name), webhook_data.text, re.I)
        response = None
        if message:
            command = message.group(1)
            split_text = command.lower().split()
            orderstr = split_text.pop(0)
            if orderstr == "help":
                response = self.help_order()
            elif orderstr in self.orders():
                try:  # Reaction is fun, but it's preview not prod.
                      # Be careful, don't fail the command if we can't thumbs up...
                    webhook_data.comment.create_reaction("+1")
                except GithubException:
                    pass
                with exception_to_github(webhook_data.issue):  # Just in case
                    response = getattr(self.handler, orderstr)(webhook_data.issue, *split_text)
            else:
                response = "I didn't understand your command:\n```bash\n{}\n```\nin this context, sorry :(\n".format(
                    command
                )
                response += self.help_order()
            if response:
                webhook_data.issue.create_comment(response)
                return {'message': response}
        return {'message': 'Nothing for me or exception'} 
Example #13
Source File: test_repo.py    From TagBot with MIT License 5 votes vote down vote up
def test_handle_error(logger, format_exc):
    r = _repo()
    r._report_error = Mock(side_effect=[None, RuntimeError("!")])
    r.handle_error(RequestException())
    r._report_error.assert_not_called()
    r.handle_error(GithubException(502, "oops"))
    r._report_error.assert_not_called()
    r.handle_error(GithubException(404, "???"))
    r._report_error.assert_called_with("ahh")
    r.handle_error(RuntimeError("?"))
    r._report_error.assert_called_with("ahh")
    logger.error.assert_called_with("Issue reporting failed") 
Example #14
Source File: github_proxy.py    From github-codebuild-logs with MIT License 5 votes vote down vote up
def delete_previous_comments(self, build):
        """Delete previous PR comments."""
        repo = self._get_repo()
        for comment in repo.get_issue(build.get_pr_id()).get_comments():
            if HIDDEN_COMMENT in comment.body:  # Check for hidden comment in body
                try:  # Not critical, catch all GitHub exceptions here
                    LOG.debug('Deleting previous comment: repo=%s/%s, pr_id=%s, comment_id=%s',
                              self._github_owner, self._github_repo, build.get_pr_id(), comment.id)
                    comment.delete()
                except GithubException as e:
                    LOG.warning('Failed to delete previous comment: repo=%s/%s, pr_id=%s, comment_id=%s, error=%s',
                                self._github_owner, self._github_repo, build.get_pr_id(), comment.id, str(e)) 
Example #15
Source File: github_org.py    From github-org-mgmt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def add_members_to_team(self, team, user_names):
        """
        Add the specified users to the specified team

        :param team: :class:`github.Team`
        :param user_names: list of str
        :rtype: None
        """

        for user_name in user_names:
            try:
                user = self._github.get_user(user_name)
                self.add_member_to_team(team, user)
            except GithubException:
                print "%s\tgebruiker niet gevonden" % user_name 
Example #16
Source File: test_github_tools.py    From azure-python-devtools with MIT License 5 votes vote down vote up
def test_get_or_create_pull(self):
        repo = self.g.get_repo("lmazuel/TestingRepo")

        # b1 and b2 should exist and be the same
        with pytest.raises(GithubException):
            get_or_create_pull(repo, "Title", "Body", "b1", "b2")

        prresult = get_or_create_pull(repo, "Title", "Body", "b1", "b2", none_if_no_commit=True)
        assert prresult is None 
Example #17
Source File: github_tools.py    From azure-python-devtools with MIT License 5 votes vote down vote up
def do_pr(gh_token, sdk_git_id, sdk_pr_target_repo_id, branch_name, base_branch, pr_body=""):  # pylint: disable=too-many-arguments
    "Do the PR"
    if not gh_token:
        _LOGGER.info('Skipping the PR, no token found')
        return None
    if not sdk_pr_target_repo_id:
        _LOGGER.info('Skipping the PR, no target repo id')
        return None

    github_con = Github(gh_token)
    sdk_pr_target_repo = github_con.get_repo(sdk_pr_target_repo_id)

    if '/' in sdk_git_id:
        sdk_git_owner = sdk_git_id.split('/')[0]
        _LOGGER.info("Do the PR from %s", sdk_git_owner)
        head_name = "{}:{}".format(sdk_git_owner, branch_name)
    else:
        head_name = branch_name
        sdk_git_repo = github_con.get_repo(sdk_git_id)
        sdk_git_owner = sdk_git_repo.owner.login

    try:
        github_pr = sdk_pr_target_repo.create_pull(
            title='Automatic PR from {}'.format(branch_name),
            body=pr_body,
            head=head_name,
            base=base_branch
        )
    except GithubException as err:
        if err.status == 422 and err.data['errors'][0].get('message', '').startswith('A pull request already exists'):
            matching_pulls = sdk_pr_target_repo.get_pulls(base=base_branch, head=sdk_git_owner+":"+head_name)
            matching_pull = matching_pulls[0]
            _LOGGER.info('PR already exists: %s', matching_pull.html_url)
            return matching_pull
        raise
    _LOGGER.info("Made PR %s", github_pr.html_url)
    return github_pr 
Example #18
Source File: github_org.py    From github-org-mgmt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def read_teams_from_csv(self, csvfile):
        """Read all teams and their users from the specified CSV file.
        A dictionary is returned with team names as key and a list of the team
        members (NamedUser objects) as values e.g.

        {'prj1': [alice, dan], 'prj2': [bob, cathy]}

        If a member does not exist, an exception is raised and the program
        aborts.
        """

        with open(csvfile) as userfile:
            userlist = csv.reader(userfile, delimiter=',')
            header = next(userlist, None)

            assert header.index('login') >= 0, \
                "CSV header should have a login field: %s" % header
            assert header.index('team') >= 0, \
                "CSV header should have a team field: %s" % header

            teams = {}

            for row in userlist:
                team_name = row[header.index('team')]
                login = row[header.index('login')]
                try:
                    user = self._github.get_user(login)

                    if(team_name not in teams):
                        # Add a new key to the teams dict, and
                        # add the first user to the member list
                        teams[team_name] = [user]
                    else:
                        # Append user name to existing team member list
                        teams[team_name].append(user)
                except GithubException:
                    print "%s,%s" % (login, team_name)

        return teams 
Example #19
Source File: github_org.py    From github-org-mgmt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def invite(self, users):
        """
        Invite the specified users to the organization
        :param str user: Name of a user to invite
        """
        for user_name in users:
            try:
                user = self._github.get_user(user_name)
                if not self._organization.has_in_members(user):
                    print "%s\t\t1\t\t\tuitgenodigd" % user_name
                    self.add_member_to_org(user)
                else:
                    print "%s\t\t\t1\t\treeds lid" % user_name
            except GithubException:
                print "%s\t1\t\t\t\tgebruiker niet gevonden" % user_name 
Example #20
Source File: test_github.py    From ogr with MIT License 5 votes vote down vote up
def test_nonexisting_fork(self):
        self.ogr_nonexisting_fork = self.service.get_project(
            repo="omfeprkfmwpefmwpefkmwpeofjwepof", is_fork=True
        )
        with self.assertRaises(GithubException) as ex:
            self.ogr_nonexisting_fork.get_description()
        s = str(ex.value.args)
        assert "Not Found" in s
        assert "404" in s 
Example #21
Source File: github_org.py    From github-org-mgmt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def delete_repo(self, repo_name):
        """Delete the repository with the specified name from the organization.
        If the repository does not exist, a warning is printed"""

        try:
            print "Deleting repo: %s" % repo_name
            repo = self._organization.get_repo(repo_name)
            repo.delete()
        except GithubException:
            print u"    Repo ā€˜%sā€™ already gone. Ignoring..." % repo_name 
Example #22
Source File: github_org.py    From github-org-mgmt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def delete_team(self, team_name):
        """Delete the team with the specified name from the organization.
        If the team does not exist, a warning is printed"""

        try:
            print "Deleting team: %s" % team_name
            team = self._organization.get_team(int(team_name))
            team.delete()
        except GithubException:
            print u"    team ā€˜%sā€™ already gone. Ignoring..." % team_name 
Example #23
Source File: utils.py    From fabric8-analytics-server with Apache License 2.0 5 votes vote down vote up
def fetch_file_from_github_release(url, filename, token, ref=None):
    """Return file content from github release."""
    if token:
        try:
            github_obj = Github(token)
            # TODO: refactor user+repository retrieving into separate function
            if url.endswith('.git'):
                url = url[:-len('.git')]

            user, repo = url.split('/')[-2:]
            user = user.split(':')[-1]
            repository = github_obj.get_repo('/'.join([user, repo]))
            if ref:
                file_content = repository.get_file_contents(filename, ref).decoded_content
            else:
                file_content = repository.get_file_contents(filename).decoded_content
            return [{
                'filename': filename,
                'filepath': '/path',
                'content': file_content.decode('utf-8')
            }]
        except RateLimitExceededException:
            HTTPError(403, "Github API rate limit exceeded")
        except BadCredentialsException:
            HTTPError(401, "Invalid github access token")
        except GithubException as e:
            HTTPError(404, 'Github repository does not exist {}'.format(str(e)))
        except Exception as e:
            current_app.logger.error('An Exception occured while fetching file github release {}'
                                     .format(str(e)))
    else:
        current_app.logger.error("Github access token is not provided") 
Example #24
Source File: github.py    From conda-smithy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_cached_team(org, team_name, description=""):
    cached_file = os.path.expanduser(
        "~/.conda-smithy/{}-{}-team".format(org.login, team_name)
    )
    try:
        with open(cached_file, "r") as fh:
            team_id = int(fh.read().strip())
            return org.get_team(team_id)
    except IOError:
        pass

    try:
        repo = org.get_repo("{}-feedstock".format(team_name))
        team = next(
            (team for team in repo.get_teams() if team.name == team_name), None
        )
        if team:
            return team
    except GithubException:
        pass

    team = next(
        (team for team in org.get_teams() if team.name == team_name), None
    )
    if not team:
        if description:
            team = create_team(org, team_name, description, [])
        else:
            raise RuntimeError("Couldn't find team {}".format(team_name))

    with open(cached_file, "w") as fh:
        fh.write(str(team.id))

    return team 
Example #25
Source File: project.py    From ogr with MIT License 5 votes vote down vote up
def _construct_fork_project(self) -> Optional["GithubProject"]:
        gh_user = self.github_instance.get_user()
        user_login = gh_user.login
        try:
            project = GithubProject(
                self.repo, self.service, namespace=user_login, read_only=self.read_only
            )
            if not project.github_repo:
                # The github_repo attribute is lazy.
                return None
            return project
        except github.GithubException as ex:
            logger.debug(f"Project {self.repo}/{user_login} does not exist: {ex}")
            return None 
Example #26
Source File: project.py    From ogr with MIT License 5 votes vote down vote up
def __get_collaborators(self) -> Set[str]:
        try:
            collaborators = self._get_collaborators_with_permission()
        except github.GithubException:
            logger.debug(
                "Current Github token must have push access to view repository permissions."
            )
            return set()

        usernames = []
        for login, permission in collaborators.items():
            if permission in self.CAN_MERGE_PERMS:
                usernames.append(login)

        return set(usernames) 
Example #27
Source File: project.py    From ogr with MIT License 5 votes vote down vote up
def set_commit_status(
        self,
        commit: str,
        state: Union[CommitStatus, str],
        target_url: str,
        description: str,
        context: str,
        trim: bool = False,
    ):
        """
        Create a status on a commit

        :param commit: The SHA of the commit.
        :param state: The state of the status.
        :param target_url: The target URL to associate with this status.
        :param description: A short description of the status
        :param context: A label to differentiate this status from the status of other systems.
        :param trim: bool Whether to trim the description in order to avoid throwing
            github.GithubException
        :return:
        """
        return GithubCommitFlag.set(
            project=self,
            commit=commit,
            state=state,
            target_url=target_url,
            description=description,
            context=context,
            trim=trim,
        ) 
Example #28
Source File: engine.py    From GSIL with GNU General Public License v3.0 5 votes vote down vote up
def verify(self):
        try:
            ret = self.g.rate_limiting
            return True, 'TOKEN-PASSED: {r}'.format(r=ret)
        except GithubException as e:
            return False, 'TOKEN-FAILED: {r}'.format(r=e) 
Example #29
Source File: github.py    From pyup with MIT License 5 votes vote down vote up
def create_issue(self, repo, title, body):
        try:
            return repo.create_issue(
                title=title,
                body=body,
            )
        except GithubException as e:
            # a 404/410 status code means the repo has issues disabled, return
            # false instead of raising an exception for that
            if e.status in [404, 410]:
                return False
            raise 
Example #30
Source File: inventory.py    From project-dev-kpis with MIT License 5 votes vote down vote up
def monitor_inventory_metrics(synonym_mappings):
    global REPO_SCRAPE_TIMES

    minus_three_months = (datetime.now() - timedelta(3 * 365 / 12)).isoformat().split('.')[0]

    def git():
        return Github(get_access_token())

    for repo in git().search_repositories(
            ('org:%s archived:false pushed:>' % GITHUB_ORGANIZATION) + minus_three_months):
        owner = get_owner(synonym_mappings, repo)

        REPO_SCRAPE_TIMES[(owner, repo.name)] = time.time()

        pulls = list(repo.get_pulls())

        observe_inventory(owner, repo.name, pulls)

        manifests = [None]

        try:
            manifests = list(git().search_code(
                'repo:%s/%s language:json filename:*manifest*.json' % (GITHUB_ORGANIZATION, repo.name)))
        except GithubException:
            logger.error('Could not search repo %s!' % repo.name)

        observe_features(owner, repo.name, manifests)

    # zero-out deleted repos
    dead_repos = {tup: last_time for tup, last_time in REPO_SCRAPE_TIMES.iteritems() if
                  last_time < time.time() - 60 * 60}

    for owner, repo_name in dead_repos.keys():
        del REPO_SCRAPE_TIMES[(owner, repo_name)]
        observe_inventory(owner, repo_name, [])