Example #1
0
    def verify_settings(
        user: str,
        org_name: str,
        base_url: str,
        token: str,
        template_org_name: Optional[str] = None,
    ) -> None:
        """See :py:meth:`repobee_plug.PlatformAPI.verify_settings`."""
        plug.echo("Verifying settings ...")

        plug.echo("Testing Internet connection")
        if not http.is_internet_connection_available():
            raise plug.InternetConnectionUnavailable()

        if not token:
            raise plug.BadCredentials(
                msg="token is empty. Check that REPOBEE_TOKEN environment "
                "variable is properly set, or supply the `--token` option.")

        g = github.Github(login_or_token=token, base_url=base_url)

        plug.echo("Trying to fetch user information ...")

        user_not_found_msg = (
            f"user {user} could not be found. Possible reasons: "
            "bad base url, bad username or bad access token permissions")
        with _convert_404_to_not_found_error(user_not_found_msg):
            user_ = g.get_user(user)
            msg = (f"Specified login is {user}, "
                   f"but the fetched user's login is {user_.login}.")
            if user_.login is None:
                msg = ("{msg} Possible reasons: bad api url that points to a "
                       "GitHub instance, but not to the api endpoint.")
                raise plug.UnexpectedException(msg=msg)
            elif user_.login != user:
                msg = (
                    f"{msg} Possible reasons: unknown, rerun with -tb and open an "
                    "issue on GitHub.")
                raise plug.UnexpectedException(msg=msg)
        plug.echo(
            f"SUCCESS: found user {user}, user exists and base url looks okay")

        plug.echo("Verifying access token scopes ...")
        scopes = g.oauth_scopes
        assert scopes is not None
        if not REQUIRED_TOKEN_SCOPES.issubset(scopes):
            raise plug.BadCredentials(
                "missing one or more access token scopes. "
                f"Actual: {scopes}. Required {REQUIRED_TOKEN_SCOPES}")
        plug.echo("SUCCESS: access token scopes look okay")

        GitHubAPI._verify_org(org_name, user, g)
        if template_org_name:
            GitHubAPI._verify_org(template_org_name, user, g)

        plug.echo("GREAT SUCCESS: all settings check out!")
Example #2
0
def _try_api_request(ignore_statuses: Optional[Iterable[int]] = None):
    """Context manager for trying API requests.

    Args:
        ignore_statuses: One or more status codes to ignore (only
        applicable if the exception is a gitlab.exceptions.GitlabError).
    """
    try:
        yield
    except gitlab.exceptions.GitlabError as e:
        if ignore_statuses and e.response_code in ignore_statuses:
            return

        if e.response_code == 404:
            raise plug.NotFoundError(str(e), status=404) from e
        elif e.response_code == 401:
            raise plug.BadCredentials(
                "credentials rejected, verify that token has correct access.",
                status=401,
            ) from e
        else:
            raise plug.PlatformError(str(e), status=e.response_code) from e
    except (exception.RepoBeeException, plug.PlugError):
        raise
    except Exception as e:
        raise plug.UnexpectedException(
            f"a {type(e).__name__} occured unexpectedly: {str(e)}") from e
Example #3
0
def _convert_404_to_not_found_error(msg):
    try:
        yield
    except gitlab.exceptions.GitlabError as exc:
        if exc.response_code == 404:
            raise plug.NotFoundError(msg)
        raise plug.UnexpectedException(
            f"An unexpected exception occured. {type(exc).__name__}: {exc}")
Example #4
0
def _convert_404_to_not_found_error(msg):
    """Catch a github.GithubException with status 404 and convert to
    plug.NotFoundError with the provided message. If the GithubException
    does not have status 404, instead raise plug.UnexpectedException.
    """
    try:
        yield
    except github.GithubException as exc:
        if exc.status == 404:
            raise plug.NotFoundError(msg)
        raise plug.UnexpectedException(
            f"An unexpected exception occured. {type(exc).__name__}: {exc}")
Example #5
0
def _try_api_request(ignore_statuses: Optional[Iterable[int]] = None):
    """Context manager for trying API requests.

    Args:
        ignore_statuses: One or more status codes to ignore (only
        applicable if the exception is a github.GithubException).

    Raises:
        plug.NotFoundError
        plug.BadCredentials
        plug.PlatformError
        plug.ServiceNotFoundError
        plug.UnexpectedException
    """
    try:
        yield
    except plug.PlugError:
        raise
    except github.GithubException as e:
        if ignore_statuses and e.status in ignore_statuses:
            return

        if e.status == 404:
            raise plug.NotFoundError(str(e), status=404)
        elif e.status == 401:
            raise plug.BadCredentials(
                "credentials rejected, verify that token has correct access.",
                status=401,
            )
        else:
            raise plug.PlatformError(str(e), status=e.status)
    except gaierror:
        raise plug.ServiceNotFoundError(
            "GitHub service could not be found, check the url"
        )
    except Exception as e:
        raise plug.UnexpectedException(
            "a {} occured unexpectedly: {}".format(type(e).__name__, str(e))
        )