Python github.UnknownObjectException() Examples

The following are 30 code examples of github.UnknownObjectException(). 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: tests.py    From statuspage with MIT License 6 votes vote down vote up
def test_update_index_does_not_exist(self):
        """
        self.gh().get_user().get_repo().update_file.side_effect = UnknownObjectException(status=404, data="foo")

        runner = CliRunner()
        result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
        self.assertEqual(result.exit_code, 0)

        self.gh.assert_called_with("token")

        self.gh().get_user().get_repo.assert_called_with(name="testrepo")
        self.gh().get_user().get_repo().get_labels.assert_called_once_with()
        self.gh().get_user().get_repo().create_file.assert_called_once_with(
            branch='gh-pages',
            content='some foo',
            message='initial',
            path='/index.html'
        )
        """ 
Example #2
Source File: common.py    From core with GNU General Public License v3.0 6 votes vote down vote up
def ensure_label_present(repo, name, color, current_labels, description=''):
    present_labels = []

    for label in current_labels:
        present_labels.append(label.name)

    if name not in present_labels:
        logger.info(f"adding '{name}' label to {repo.name}")

        try:
            repo.create_label(name, color, description)

        except UnknownObjectException as e:
            logger.error(e)

            repo.create_issue(f"can't create '{name}' label")
            logger.info('issue created!')
    else:
        logger.debug(f"label '{name}' was present") 
Example #3
Source File: test_github.py    From ogr with MIT License 6 votes vote down vote up
def test_project_create(self):
        """
        Remove https://github.com/$USERNAME/repo_created_for_test repository before regeneration

        """
        name_of_the_repo = "repo_created_for_test"
        project = self.service.get_project(
            repo=name_of_the_repo, namespace=self.service.user.get_username()
        )
        with self.assertRaises(UnknownObjectException):
            project.github_repo

        new_project = self.service.project_create(name_of_the_repo)
        assert new_project.repo == name_of_the_repo
        assert new_project.github_repo

        project = self.service.get_project(
            repo=name_of_the_repo, namespace=self.service.user.get_username()
        )
        assert project.github_repo 
Example #4
Source File: service.py    From ogr with MIT License 6 votes vote down vote up
def project_create(self, repo: str, namespace: str = None) -> "GithubProject":
        if namespace:
            try:
                owner = self.github.get_organization(namespace)
            except UnknownObjectException:
                raise GithubAPIException(f"Group {namespace} not found.")
        else:
            owner = self.github.get_user()

        new_repo = owner.create_repo(name=repo)
        return GithubProject(
            repo=repo,
            namespace=namespace or owner.login,
            service=self,
            github_repo=new_repo,
        ) 
Example #5
Source File: pull_request.py    From ogr with MIT License 6 votes vote down vote up
def get_list(
        project: "ogr_github.GithubProject", status: PRStatus = PRStatus.open
    ) -> List["PullRequest"]:
        prs = project.github_repo.get_pulls(
            # Github API has no status 'merged', just 'closed'/'opened'/'all'
            state=status.name if status != PRStatus.merged else "closed",
            sort="updated",
            direction="desc",
        )

        if status == PRStatus.merged:
            prs = list(prs)  # Github PaginatedList into list()
            for pr in prs:
                if not pr.is_merged():  # parse merged PRs
                    prs.remove(pr)
        try:
            return [GithubPullRequest(pr, project) for pr in prs]
        except UnknownObjectException:
            return [] 
Example #6
Source File: github.py    From cmake_format with GNU General Public License v3.0 6 votes vote down vote up
def create_pseudorelease_tag(reposlug, branch):
  access_token = os.environ.get("GITHUB_ACCESS_TOKEN")
  if access_token is None:
    raise RuntimeError("GITHUB_ACCESS_TOKEN missing from environment")

  # TODO(josh): get title out of the script so that it can be reusable
  hub = github.Github(access_token)
  repo = hub.get_repo(reposlug)
  branchobj = repo.get_branch(branch)
  logger.info("Creating tag pseudo-%s -> %s", branch, branchobj.commit.sha)
  refname = "tags/pseudo-" + branch
  try:
    existing_ref = repo.get_git_ref(refname)
    logger.info("Updating existing ref for %s", refname)
    existing_ref.edit(branchobj.commit.sha, force=True)
    return
  except github.UnknownObjectException:
    pass

  logger.info("Creating ref %s", refname)
  refname = "refs/" + refname
  repo.create_git_ref(refname, branchobj.commit.sha) 
Example #7
Source File: test_repo.py    From TagBot with MIT License 6 votes vote down vote up
def test_commit_sha_of_tag():
    r = _repo()
    r._repo.get_git_ref = Mock()
    r._repo.get_git_ref.return_value.object.type = "commit"
    r._repo.get_git_ref.return_value.object.sha = "c"
    assert r._commit_sha_of_tag("v1.2.3") == "c"
    r._repo.get_git_ref.assert_called_with("tags/v1.2.3")
    r._repo.get_git_ref.return_value.object.type = "tag"
    r._repo.get_git_tag = Mock()
    r._repo.get_git_tag.return_value.object.sha = "t"
    assert r._commit_sha_of_tag("v2.3.4") == "t"
    r._repo.get_git_tag.assert_called_with("c")
    r._repo.get_git_ref.return_value.object = None
    assert r._commit_sha_of_tag("v3.4.5") is None
    r._repo.get_git_ref.side_effect = UnknownObjectException(404, "???")
    assert r._commit_sha_of_tag("v4.5.6") is None 
Example #8
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 #9
Source File: fork_conda_forge.py    From build-tools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def fork_repo(gh, *, org, package_name, source_org):
    repo_full_name = f'{org.login}/{package_name}-feedstock'
    forked_repo = gh.get_repo(repo_full_name)
    print(f'Checking to see if {repo_full_name} exists on Github')
    try:
        # Check that the repo actually exists
        # Printing the name or any property of the repo issues this check
        print(f'{forked_repo.full_name} already exists, not forking it again.')
        return forked_repo
    except UnknownObjectException:
        print(f'{repo_full_name} does not exists on Github, will fork')
        pass

    # Else, now try to fork it from the origin
    feedstock_repo = gh.get_repo(f'{source_org}/{package_name}-feedstock')
    try:
        org.create_fork(feedstock_repo)
    except UnknownObjectException as e:
        if e.status == 404:
            raise RuntimeError(f'Repository not found: {e.data["message"]}')
        else:
            raise e 
Example #10
Source File: notify_codeowners.py    From addons with Apache License 2.0 6 votes vote down vote up
def check_user(user: str, line_idx: int):
    if user[0] != "@":
        raise ValueError(
            f"User '{user}' at line {line_idx} of CODEOWNERS "
            f"doesn't start with '@' "
        )
    user = user[1:]
    user = user.lower()  # in github, user names are case insensitive
    if user in WRITE_ACCESS_LIST:
        return None
    try:
        CLIENT.get_user(user)
    except github.UnknownObjectException:
        raise KeyError(
            f"User '{user}' line {line_idx} does not exist. Did you make a typo?"
        )
    return user 
Example #11
Source File: test_github.py    From pyup with MIT License 6 votes vote down vote up
def test_close_pull_request(self):

        pr = Mock()
        pr.head.ref = "bla"
        self.repo.get_pull.return_value = pr
        with self.assertRaises(AssertionError):
            self.provider.close_pull_request(self.repo, self.repo, pr, "comment", prefix="pyup-")

        pr.head.ref = "pyup-bla"
        self.provider.close_pull_request(self.repo, self.repo, pr, "comment", prefix="pyup-")
        self.assertEqual(self.repo.get_git_ref().delete.call_count, 1)

        self.repo.get_pull.side_effect = UnknownObjectException(data="", status=1)
        data = self.provider.close_pull_request(self.repo, self.repo, Mock(), "comment",
                                                prefix="pyup-")
        self.assertEqual(data, False) 
Example #12
Source File: test_repo.py    From TagBot with MIT License 5 votes vote down vote up
def test_project():
    r = _repo()
    r._repo.get_contents = Mock(
        return_value=Mock(decoded_content=b"""name = "FooBar"\nuuid="abc-def"\n""")
    )
    assert r._project("name") == "FooBar"
    assert r._project("uuid") == "abc-def"
    assert r._project("name") == "FooBar"
    r._repo.get_contents.assert_called_once_with("Project.toml")
    r._repo.get_contents.side_effect = UnknownObjectException(404, "???")
    r._Repo__project = None
    with pytest.raises(InvalidProject):
        r._project("name") 
Example #13
Source File: gitgot.py    From GitGot with GNU Lesser General Public License v3.0 5 votes vote down vote up
def should_parse(repo, state, is_gist=False):
    owner_login = repo.owner.login if is_gist else repo.repository.owner.login
    if owner_login in state.bad_users:
        print(bcolors.FAIL + "Failed check: Ignore User" + bcolors.ENDC)
        return False
    if not is_gist and repo.repository.name in state.bad_repos:
        print(bcolors.FAIL + "Failed check: Ignore Repo" + bcolors.ENDC)
        return False
    if not is_gist and repo.name in state.bad_files:
        print(bcolors.FAIL + "Failed check: Ignore File" + bcolors.ENDC)
        return False

    # Fuzzy Hash Comparison
    try:
        if not is_gist:
            # Temporary fix for PyGithub until fixed upstream (PyGithub#1178)
            repo._url.value = repo._url.value.replace(
                repo._path.value,
                urllib.parse.quote(repo._path.value))

        candidate_sig = ssdeep.hash(repo.decoded_content)
        for sig in state.bad_signatures:
            similarity = ssdeep.compare(candidate_sig, sig)
            if similarity > SIMILARITY_THRESHOLD:
                print(
                    bcolors.FAIL +
                    "Failed check: Ignore Fuzzy Signature on Contents "
                    "({}% Similarity)".format(similarity) +
                    bcolors.ENDC)
                return False
    except github.UnknownObjectException:
        print(
            bcolors.FAIL +
            "API Error: File no longer exists on github.com" +
            bcolors.ENDC)
        return False
    return True 
Example #14
Source File: statuspage.py    From statuspage with MIT License 5 votes vote down vote up
def run_remove_system(name, token, org, system, prompt):
    """
    Removes a system from the repo.
    """
    repo = get_repo(token=token, org=org, name=name)
    try:
        label = repo.get_label(name=system.strip())
        label.delete()
        click.secho("Successfully deleted {}".format(system), fg="green")
        if prompt and click.confirm("Run update to re-generate the page?"):
            run_update(name=name, token=token, org=org)
    except UnknownObjectException:
        click.secho("Unable to remove system {}, it does not exist.".format(system), fg="yellow") 
Example #15
Source File: issue.py    From ogr with MIT License 5 votes vote down vote up
def get_list(
        project: "ogr_github.GithubProject",
        status: IssueStatus = IssueStatus.open,
        author: Optional[str] = None,
        assignee: Optional[str] = None,
        labels: Optional[List[str]] = None,
    ) -> List["Issue"]:
        parameters: Dict[str, Union[str, List[str]]] = {
            "state": status.name,
            "sort": "updated",
            "direction": "desc",
        }
        if author:
            parameters["creator"] = author
        if assignee:
            parameters["assignee"] = assignee
        if labels:
            parameters["labels"] = [
                project.github_repo.get_label(label) for label in labels
            ]

        issues = project.github_repo.get_issues(**parameters)
        try:
            return [
                GithubIssue(issue, project)
                for issue in issues
                if not issue.pull_request
            ]
        except UnknownObjectException:
            return [] 
Example #16
Source File: githubbot.py    From shamer with MIT License 5 votes vote down vote up
def get_pr_by_number_or_id(self, number_or_id):
    number_or_id = int(number_or_id)
    try:
      return self.get_pr_by_number(number_or_id)
    except UnknownObjectException:
      return self.get_pr_by_id(number_or_id) 
Example #17
Source File: flag.py    From ogr with MIT License 5 votes vote down vote up
def get(project: "ogr_github.GithubProject", commit: str) -> List["CommitFlag"]:
        statuses = project.github_repo.get_commit(commit).get_statuses()

        try:
            return [
                GithubCommitFlag(
                    raw_commit_flag=raw_status, project=project, commit=commit
                )
                for raw_status in statuses
            ]
        except UnknownObjectException:
            return [] 
Example #18
Source File: github.py    From pyup with MIT License 5 votes vote down vote up
def get_default_branch(self, repo):
        try:
            return repo.default_branch
        except UnknownObjectException:
            # we can't use repo.name here because the repo object is lazy!
            # If we try to access one of the properties that is not completed,
            # we'll run into the next exception.
            logger.error("Repo does not exist", exc_info=True)
            raise RepoDoesNotExistError() 
Example #19
Source File: github_org.py    From github-org-mgmt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def read_members_from_txt(self, txtfile):
        """Read member names from the specified text file (one member
        per line). An array is returned with NamedUSer objects."""

        user_names = []
        users = []
        failed_users = []
        with open(txtfile) as userfile:
            user_names = userfile.readlines()
        print "Reading users:"
        for name in user_names:
            # strip the \n from the right
            name = name.rstrip()
            print " - %s" % name
            # Convert user name into Github NamedUser object
            try:
                user = self._github.get_user(name)
                users.append(user)
            except UnknownObjectException:
                failed_users.append(name)

        print "Failed users:"
        for failed_user in failed_users:
            print " - %s" % failed_user

        return users 
Example #20
Source File: github_access.py    From yotta with Apache License 2.0 5 votes vote down vote up
def _getTags(self):
        if self.tags is None:
            try:
                self.tags = _getTags(self.repo).items()
            except github.UnknownObjectException as e:
                raise access_common.Unavailable(
                    'could not locate github component "%s", either the name is misspelt, you do not have access to it, or it does not exist' % self.repo
                )
        return self.tags 
Example #21
Source File: release.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def get_repo(github_token: str, github_owner: str) -> Repository:
    """
    Get a GitHub repository.
    """
    github_client = Github(github_token)
    try:
        github_user_or_org = github_client.get_organization(github_owner)
    except UnknownObjectException:
        github_user_or_org = github_client.get_user(github_owner)

    return github_user_or_org.get_repo('dcos-e2e') 
Example #22
Source File: github.py    From pyup with MIT License 5 votes vote down vote up
def get_pull_request_committer(self, repo, pull_request):
        try:
            return [
                commit.committer
                for commit in repo.get_pull(pull_request.number).get_commits()
            ]
        except UnknownObjectException:
            return [] 
Example #23
Source File: repo.py    From TagBot with MIT License 5 votes vote down vote up
def _versions(self, min_age: Optional[timedelta] = None) -> Dict[str, str]:
        """Get all package versions from the registry."""
        root = self._registry_path
        if not root:
            logger.debug("Package is not registered")
            return {}
        kwargs = {}
        if min_age:
            # Get the most recent commit from before min_age.
            until = datetime.now() - min_age
            commits = self._registry.get_commits(until=until)
            # Get the first value like this because the iterator has no `next` method.
            for commit in commits:
                kwargs["ref"] = commit.commit.sha
                break
            else:
                logger.debug("No registry commits were found")
                return {}
        try:
            contents = self._only(
                self._registry.get_contents(f"{root}/Versions.toml", **kwargs)
            )
        except UnknownObjectException:
            logger.debug(f"Versions.toml was not found ({kwargs})")
            return {}
        versions = toml.loads(contents.decoded_content.decode())
        return {v: versions[v]["git-tree-sha1"] for v in versions} 
Example #24
Source File: repo.py    From TagBot with MIT License 5 votes vote down vote up
def _commit_sha_of_tag(self, version: str) -> Optional[str]:
        """Look up the commit SHA of a given tag."""
        try:
            ref = self._repo.get_git_ref(f"tags/{version}")
        except UnknownObjectException:
            return None
        ref_type = getattr(ref.object, "type", None)
        if ref_type == "commit":
            return ref.object.sha
        elif ref_type == "tag":
            tag = self._repo.get_git_tag(ref.object.sha)
            return tag.object.sha
        else:
            return None 
Example #25
Source File: repo.py    From TagBot with MIT License 5 votes vote down vote up
def _project(self, k: str) -> str:
        """Get a value from the Project.toml."""
        if self.__project is not None:
            return str(self.__project[k])
        for name in ["Project.toml", "JuliaProject.toml"]:
            try:
                contents = self._only(self._repo.get_contents(name))
                break
            except UnknownObjectException:
                pass
        else:
            raise InvalidProject("Project file was not found")
        self.__project = toml.loads(contents.decoded_content.decode())
        return str(self.__project[k]) 
Example #26
Source File: github.py    From pyup with MIT License 5 votes vote down vote up
def close_pull_request(self, bot_repo, user_repo, pull_request, comment, prefix):
        try:
            pull_request = bot_repo.get_pull(pull_request.number)
            pull_request.create_issue_comment(comment)
            pull_request.edit(state="closed")
            # make sure that the name of the branch begins with pyup.
            assert pull_request.head.ref.startswith(prefix)
            ref = user_repo.get_git_ref("/".join(["heads", pull_request.head.ref]))
            ref.delete()
        except UnknownObjectException:
            return False 
Example #27
Source File: bot_framework.py    From azure-python-devtools with MIT License 5 votes vote down vote up
def build_from_issue_comment(gh_token, body):
    """Create a WebhookMetadata from a comment added to an issue.
    """
    if body["action"] in ["created", "edited"]:
        github_con = Github(gh_token)
        repo = github_con.get_repo(body['repository']['full_name'])
        issue = repo.get_issue(body['issue']['number'])
        text = body['comment']['body']
        try:
            comment = issue.get_comment(body['comment']['id'])
        except UnknownObjectException:
            # If the comment has already disapeared, skip the command
            return None
        return WebhookMetadata(repo, issue, text, comment)
    return None 
Example #28
Source File: utils.py    From commcare-cloud with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tag_setup_release(self):
        if _github_auth_provided():
            try:
                self.repo.create_git_ref(
                    ref='refs/tags/' + '{}-{}-setup_release'.format(self.timestamp, self._environment),
                    sha=self.deploy_ref,
                )
            except UnknownObjectException:
                raise Exception(
                    'Github API key does not have the right settings. '
                    'Please create an API key with the public_repo scope enabled.'
                )
            return True
        return False 
Example #29
Source File: github.py    From pyup with MIT License 5 votes vote down vote up
def get_or_create_label(self, repo, name):
        try:
            label = repo.get_label(name=name)
        except UnknownObjectException:
            logger.info("Label {} does not exist, creating.".format(name))
            try:
                label = repo.create_label(name=name, color="1BB0CE")
            except GithubException:
                logger.warning(
                    "Unable to create label {} due to permissions".format(name), exc_info=True)
                return None
        return label 
Example #30
Source File: utils_tests.py    From codesy with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_issue_state_catches_UnknownObjectException(self):
        url = 'https://github.com/codesy/codesy/issues/158'

        fake_gh_client = fudge.Fake()
        (fake_gh_client.expects('get_repo').with_args('codesy/codesy')
                       .raises(UnknownObjectException(404,
                                                      "Cannot find repo.")))

        self.assertEqual(None, issue_state(url, fake_gh_client))