Python github3.GitHubError() Examples

The following are 9 code examples of github3.GitHubError(). 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 github3 , or try the search function .
Example #1
Source File: test_helpers.py    From farcy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_get_session__authenticate_with_exceptions(
            self, mock_path, mock_prompt, mock_getpass, mock_authorize):
        mock_path.isfile.return_value = False

        mock_response = MockResponse(content='', status_code=401)
        mock_authorize.side_effect = GitHubError(mock_response)
        self.assertRaises(exceptions.FarcyException, helpers.get_session)

        self.assertTrue(mock_prompt.called)
        self.assertTrue(mock_getpass.called)

        mock_response = MockResponse(content='', status_code=101)
        mock_authorize.side_effect = GitHubError(mock_response)
        self.assertRaises(GitHubError, helpers.get_session)

        mock_authorize.side_effect = TypeError
        self.assertRaises(TypeError, helpers.get_session) 
Example #2
Source File: test_merge.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_feature_branch_merge_github_error(self):
        self._mock_repo()
        self._mock_branch(self.branch)
        self.mock_pulls()
        branch_name = "feature/a-test"
        branches = []
        branches.append(self._get_expected_branch(branch_name))
        branches = self._mock_branches(branches)
        self._mock_compare(
            base=branches[1]["name"],
            head=self.project_config.repo_commit,
            files=[{"filename": "test.txt"}],
        )
        self._mock_merge(http.client.INTERNAL_SERVER_ERROR)
        task = self._create_task()
        with self.assertRaises(GitHubError):
            task() 
Example #3
Source File: github.py    From osspolice with GNU General Public License v3.0 5 votes vote down vote up
def get_commits(self, repo_owner, repo_name):
        from github3 import GitHubError
        attempts = self.__retries
        while attempts:
            try:
                # github handler
                g = self.get_github_handler()
                if not g:
                    raise Exception("No github handler")

                repo = g.repository(repo_owner, repo_name)
                commits = repo.iter_commits()  # [commit for commit in repo.iter_commits()]
                # for commit in commits:
                #    print commits[0].to_json()['commit']['committer']['date']
                return repo, commits

            except GitHubError as ghe:
                if str(ghe.code) == '403':
                    logger.error("get_tags: %s", str(ghe))
                    attempts -= 1
                    continue
                else:
                    logger.error("get_tags: %s, giving up!", str(ghe))
                    break

            # timed out
            except utils.TimeoutException as te:
                logger.error("Error getting github repo commits for repo %s: %s", repo_name, str(te))
                # try again
                attempts -= 1
                continue

            except Exception as e:
                logger.error("Failed to get github repo commits for repo %s: %s", repo_name, str(e))
                return None

        logger.error("Giving up on getting github repo releases for repo %s!", repo_name)
        return None 
Example #4
Source File: github.py    From osspolice with GNU General Public License v3.0 5 votes vote down vote up
def get_tags(self, repo_owner, repo_name):
        from github3 import GitHubError
        attempts = self.__retries
        while attempts:
            try:
                # github handler
                g = self.get_github_handler()
                if not g:
                    raise Exception("No github handler")

                repo = g.repository(repo_owner, repo_name)
                if not repo:
                    logger.error("repo doesn't exist: %s/%s, giving up!", repo_owner, repo_name)
                    break

                tags = repo.iter_tags()
                return repo, tags

            except GitHubError as ghe:
                if str(ghe.code) == '403':
                    logger.error("get_tags: %s", str(ghe))
                    attempts -= 1
                    continue
                else:
                    logger.error("get_tags: %s, giving up!", str(ghe))
                    break

            # timed out
            except utils.TimeoutException as te:
                logger.error("Error getting github repo tags for repo %s: %s", repo_name, str(te))
                # try again
                attempts -= 1
                continue

            except Exception as e:
                logger.error("Failed to get github repo tags for repo %s: %s", repo_name, str(e))
                return None, None

        logger.error("Giving up on getting github repo releases for repo %s!", repo_name)
        return None, None 
Example #5
Source File: test_helpers.py    From farcy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_get_session__from_credentials_file__handled_exception(
            self, mock_path, mock_open, mock_is_starred, mock_stderr,
            mock_prompt, mock_getpass, mock_authorize):
        mock_path.expanduser.return_value = 'mock_path'
        mock_path.isfile.return_value = True
        mock_open.return_value = MagicMock(spec=IOBase)

        mock_response = MockResponse(content='', status_code=401)
        mock_is_starred.side_effect = GitHubError(mock_response)
        self.assertTrue(isinstance(helpers.get_session(), GitHub))
        self.assertTrue(mock_stderr.write.called)
        self.assertTrue(mock_prompt.called)
        self.assertTrue(mock_getpass.called)
        self.assertTrue(mock_open.called) 
Example #6
Source File: github_api.py    From ob2 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _assign_repo(repo_name, members=[]):
    """
    (PRIVATE method, use the repomanager instead) Creates the repository and adds the members as
    contributors, idempotently.

    """
    if config.github_read_only_mode:
        raise RuntimeError("Cannot assign repo because of GitHub read-only mode")
    github = _get_github_admin()
    fq_repo_name = "%s/%s" % (config.github_organization, repo_name)
    organization = github.organization(config.github_organization)
    try:
        repo = organization.create_repo(repo_name, private=config.github_private_repos)
    except github3.GitHubError as e:
        if e.args and hasattr(e.args[0], "status_code") and e.args[0].status_code == 422:
            repo = github.repository(config.github_organization, repo_name)
            assert repo, "Unable to get repository object for GitHub (check API key permissions?)"
        else:
            raise

    collaborators = {user.login for user in repo.iter_collaborators()}

    for member in members:
        if member not in collaborators:
            successfully_added = repo.add_collaborator(member)
            assert successfully_added, "Unable to add member %s to %s" % (repr(member),
                                                                          repr(fq_repo_name)) 
Example #7
Source File: github_login.py    From maintainer-tools with GNU Affero General Public License v3.0 4 votes vote down vote up
def authorize_token(user):
    config = read_config()
    if config.get('GitHub', 'token'):
        print("The token already exists.")
        sys.exit()

    password = getpass('Password for {0}: '.format(user))

    note = 'OCA (odoo community association) Maintainers Tools'
    note_url = 'https://github.com/OCA/maintainers-tools'
    scopes = ['repo', 'read:org', 'write:org', 'admin:org']

    try:
        # Python 2
        prompt = raw_input
    except NameError:
        # Python 3
        prompt = input

    def two_factor_prompt():
        code = ''
        while not code:
            # The user could accidentally press Enter before being ready,
            # let's protect them from doing that.
            code = prompt('Enter 2FA code: ')
        return code
    try:
        auth = github3.authorize(user, password, scopes, note, note_url,
                                 two_factor_callback=two_factor_prompt)
    except github3.GitHubError as err:
        if err.code == 422:
            for error in err.errors:
                if error['code'] == 'already_exists':
                    msg = ("The 'OCA (odoo community association) Maintainers "
                           "Tools' token already exists. You will find it at "
                           "https://github.com/settings/tokens and can "
                           "revoke it or set the token manually in the "
                           "configuration file.")
                    sys.exit(msg)
        raise

    config.set("GitHub", "token", auth.token)
    write_config(config)
    print("Token stored in configuration file") 
Example #8
Source File: github.py    From osspolice with GNU General Public License v3.0 4 votes vote down vote up
def get_tags_commits(self, repo_owner, repo_name, insertdb=False, gh_id=None):
        from github3 import GitHubError
        attempts = self.__retries
        repo = None
        tags_commits = []
        count = 0

        # for large repos we limit querying the server
        while attempts or (main.MAX_REPO_TAGS_QUERY and count < main.MAX_REPO_TAGS_QUERY):
            idx = 0
            try:
                # github handler
                g = self.get_github_handler()
                if not g:
                    raise Exception("No github handler")

                repo = g.repository(repo_owner, repo_name)
                if not repo:
                    logger.error("repo doesn't exist: %s/%s, giving up!", repo_owner, repo_name)
                    break

                for tag in repo.iter_tags():

                    # for large repos we limit querying the server
                    if main.MAX_REPO_TAGS_QUERY and idx > main.MAX_REPO_TAGS_QUERY:
                        break
                    if idx <= count:
                        idx += 1
                        continue
                    else:
                        tags_commits.append((tag, repo.commit(tag.to_json()['commit']['sha'])))
                        idx += 1
                        count += 1

                # insertdb
                if insertdb:
                    self.insert_tags_db(gh_id=gh_id, repo_owner=repo_owner, repo_name=repo_name,
                                        tags_commits=tags_commits)
                return repo, tags_commits

            except GitHubError as ghe:
                if str(ghe.code) == '403':
                    logger.error("get_tags_commits count %d idx %d: %s", count, idx, str(ghe))
                    attempts -= 1
                    continue
                else:
                    logger.error("get_tags_commits count %d idx %d: %s, giving up!", count, idx, str(ghe))
                    break

            except Exception as e:
                logger.error("failed to get tags for repo %s after collecting %d tags: %s", repo_name, count, str(e))
                return None, None

        logger.error("Giving up on collecting tags/commits for repo %s after %d tags/commits", repo_name, count)
        return repo, tags_commits 
Example #9
Source File: merge.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _merge(self, branch, source, commit, children=None):
        if not children:
            children = []
        branch_type = "branch"
        if children:
            branch_type = "parent branch"
        if self.options["children_only"]:
            branch_type = "child branch"

        compare = self.repo.compare_commits(branch, commit)
        if not compare or not compare.files:
            self.logger.info(
                "Skipping {} {}: no file diffs found".format(branch_type, branch)
            )
            return

        try:
            self.repo.merge(branch, commit)
            self.logger.info(
                "Merged {} commits into {} {}".format(
                    compare.behind_by, branch_type, branch
                )
            )
            if children and not self.options["children_only"]:
                self.logger.info("  Skipping merge into the following child branches:")
                for child in children:
                    self.logger.info("    {}".format(child.name))

        except GitHubError as e:
            if e.code != http.client.CONFLICT:
                raise

            if branch in self.existing_prs:
                self.logger.info(
                    "Merge conflict on {} {}: merge PR already exists".format(
                        branch_type, branch
                    )
                )
                return

            pull = self.repo.create_pull(
                title="Merge {} into {}".format(source, branch),
                base=branch,
                head=source,
                body="This pull request was automatically generated because "
                "an automated merge hit a merge conflict",
            )

            self.logger.info(
                "Merge conflict on {} {}: created pull request #{}".format(
                    branch_type, branch, pull.number
                )
            )