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
def create_repo( self, name: str, description: str, private: bool, team: Optional[plug.Team] = None, ) -> plug.Repo: """See :py:meth:`repobee_plug.PlatformAPI.create_repo`.""" assert not team or team.implementation repo_bucket = self._repos.setdefault(self._org_name, {}) if name in repo_bucket: raise plug.PlatformError(f"{name} already exists") repo_path = self._repodir / self._org_name / name repo_path.mkdir(parents=True, exist_ok=True) git.Repo.init(repo_path, bare=True) repo_bucket[name] = Repo( name=name, description=description, url=repo_path.as_uri(), private=private, path=repo_path, ) repo = repo_bucket[name] if team: self._get_team(team.id).repos.add(repo) return repo.to_plug_repo()
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.PlatformError(str(exc), status=exc.response_code) from exc
def _get_users(self, usernames: Iterable[str]) -> List[_User]: """Get all existing users corresponding to the usernames. Skip users that do not exist. Args: usernames: GitHub usernames. Returns: A list of _User objects. """ existing_users = [] for name in usernames: try: existing_users.append(self._github.get_user(name)) except github.GithubException as exc: if exc.status != 404: raise plug.PlatformError( "Got unexpected response code from the GitHub API", status=exc.status, ) plug.log.warning(f"User {name} does not exist") return existing_users
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)) )
def create_repo( self, name: str, description: str, private: bool, team: Optional[plug.Team] = None, ) -> plug.Repo: """See :py:meth:`repobee_plug.PlatformAPI.create_repo`.""" endpoint = f"/orgs/{self._org_name}/repos" data = dict( name=name, description=description, auto_init=False, private=private, default_branch="master", ) response = self._request(requests.post, endpoint, data=data) if response.status_code == 409: raise plug.PlatformError( f"repository {self._org_name}/{name} already exists", status=response.status_code, ) resp_data = response.json() repo = plug.Repo( name=name, description=description, private=private, url=resp_data["clone_url"], implementation=resp_data, ) if team: self.assign_repo(team, repo, plug.TeamPermission.PUSH) return repo
@pytest.fixture(scope="function", params=iter(repobee_plug.cli.CoreCommand)) def parsed_args_all_subparsers(request): """Parametrized fixture which returns a namespace for each of the subparsers. These arguments are valid for all subparsers, even though many will only use some of the arguments. """ return argparse.Namespace(**request.param.asdict(), **VALID_PARSED_ARGS) @pytest.fixture( scope="function", params=[ exception.PushFailedError("some message", 128, b"error", "someurl"), exception.CloneFailedError("some message", 128, b"error", "someurl"), exception.GitError("some message", 128, b"error"), plug.PlatformError("some message"), ], ) def command_all_raise_mock(command_mock, dummyapi_instance, request): """Mock of _repobee.command where all functions raise expected exceptions (i.e. those caught in _sys_exit_on_expected_error) """ def raise_(*args, **kwargs): raise request.param command_mock.setup_student_repos.side_effect = raise_ command_mock.update_student_repos.side_effect = raise_ command_mock.open_issue.side_effect = raise_ command_mock.close_issue.side_effect = raise_ command_mock.migrate_repos.side_effect = raise_