From 00a71408178e9b28bb8520ad9bdc9a5f9caf3635 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 18:44:45 +0200 Subject: [PATCH 01/16] ci: add ruff Signed-off-by: Matej Focko --- .pre-commit-config.yaml | 6 ++++++ pyproject.toml | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 98d4a08c..92fbdcb7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -63,3 +63,9 @@ repos: - id: requre-purge # Do not run in pre-commit.ci as it requires too much time stages: [manual, push] + - repo: https://github.com/astral-sh/ruff-pre-commit + # Ruff version. + rev: v0.0.291 + hooks: + - id: ruff + args: [--fix, --exit-non-zero-on-fix] diff --git a/pyproject.toml b/pyproject.toml index b1d6a6d6..6e2d405f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -65,3 +65,30 @@ source = "vcs" # - post-release (no-guess-dev): # 0.20.0.post1.dev1+g0abcdef < 0.20.1 raw-options.version_scheme = "no-guess-dev" + +[tool.ruff] +select = [ + # "B", # flake8-bugbear + # "C4", # flake8-comprehensions + # "COM", # flake8-commas + # "E", # pycodestyle Error + # "F", # Pyflakes + # "I", # isort + # "PERF",# Perflint + # "PIE", # flake8-pie +# "PT", # flake8-pytest-style, would be nice to enable + # "RET", # flake8-return + # "RUF", # Ruff-specific rules + # "SIM", # flake8-simplify + # "UP", # pyupgrade + # "W", # pycodestyle Warning +] + +ignore = [ + "B017", # assert-raises-exception + "B022", # useless-contextlib-suppress + "RUF003"# Comment contains ambiguous character +] + +line-length = 100 +target-version = "py39" From 4bc7645e76ab064cf32f4822e2de5c91e86b4bc6 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 18:46:23 +0200 Subject: [PATCH 02/16] ci(ruff): enable flake8-bugbear Signed-off-by: Matej Focko --- pyproject.toml | 2 +- tests/integration/github/test_issues.py | 2 +- tests/integration/github/test_retries.py | 2 +- tests/integration/github/test_service.py | 8 ++++---- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 6e2d405f..f87f2d97 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,7 +68,7 @@ raw-options.version_scheme = "no-guess-dev" [tool.ruff] select = [ - # "B", # flake8-bugbear + "B", # flake8-bugbear # "C4", # flake8-comprehensions # "COM", # flake8-commas # "E", # pycodestyle Error diff --git a/tests/integration/github/test_issues.py b/tests/integration/github/test_issues.py index 319e15a5..9eaf3417 100644 --- a/tests/integration/github/test_issues.py +++ b/tests/integration/github/test_issues.py @@ -158,7 +158,7 @@ def test_functions_fail_for_pr(self): with pytest.raises(GithubAPIException): self.ogr_project.get_issue(1).close() with pytest.raises(GithubAPIException): - self.ogr_project.get_issue(1).labels + _ = self.ogr_project.get_issue(1).labels with pytest.raises(GithubAPIException): self.ogr_project.get_issue(1).add_label("should fail") diff --git a/tests/integration/github/test_retries.py b/tests/integration/github/test_retries.py index 8087976a..f61c9342 100644 --- a/tests/integration/github/test_retries.py +++ b/tests/integration/github/test_retries.py @@ -26,4 +26,4 @@ def test_bad_credentials(max_retries): service = GithubService(token="invalid_token", max_retries=max_retries) project = service.get_project(namespace="mmuzila", repo="playground") - project.github_repo + _ = project.github_repo diff --git a/tests/integration/github/test_service.py b/tests/integration/github/test_service.py index e4642b76..24b4ddd8 100644 --- a/tests/integration/github/test_service.py +++ b/tests/integration/github/test_service.py @@ -22,7 +22,7 @@ def test_project_create(self): repo=name_of_the_repo, namespace=self.service.user.get_username() ) with self.assertRaises(GithubException): - project.github_repo + _ = project.github_repo new_project = self.service.project_create(name_of_the_repo) assert new_project.repo == name_of_the_repo @@ -45,7 +45,7 @@ def test_project_create_with_description(self): repo=name_of_the_repo, namespace=self.service.user.get_username() ) with self.assertRaises(GithubException): - project.github_repo + _ = project.github_repo new_project = self.service.project_create( name_of_the_repo, @@ -72,7 +72,7 @@ def test_project_create_in_the_group(self): repo=name_of_the_repo, namespace=namespace_of_the_repo ) with self.assertRaises(UnknownObjectException): - project.github_repo + _ = project.github_repo new_project = self.service.project_create( repo=name_of_the_repo, namespace=namespace_of_the_repo @@ -96,7 +96,7 @@ def test_project_create_duplicate(self): repo=name_of_the_repo, namespace=self.service.user.get_username() ) with self.assertRaises(GithubException): - project.github_repo + _ = project.github_repo self.service.project_create(name_of_the_repo) with pytest.raises(GithubAPIException): From 0dfefb7383e735fefefd0ef74532b73c667bca2c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 18:46:53 +0200 Subject: [PATCH 03/16] ci(ruff): enable flake8-comprehensions Signed-off-by: Matej Focko --- ogr/services/github/project.py | 2 +- pyproject.toml | 2 +- tests/integration/github/test_generic_commands.py | 4 ++-- tests/integration/pagure/test_project_token.py | 4 +--- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/ogr/services/github/project.py b/ogr/services/github/project.py index 3bbdd68b..8cc00368 100644 --- a/ogr/services/github/project.py +++ b/ogr/services/github/project.py @@ -541,7 +541,7 @@ def get_contributors(self) -> Set[str]: Returns: Logins of contributors to the project. """ - return set(map(lambda c: c.login, self.github_repo.get_contributors())) + return {c.login for c in self.github_repo.get_contributors()} def users_with_write_access(self) -> Set[str]: return self.__get_collaborators() diff --git a/pyproject.toml b/pyproject.toml index f87f2d97..c0e06d1e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -69,7 +69,7 @@ raw-options.version_scheme = "no-guess-dev" [tool.ruff] select = [ "B", # flake8-bugbear - # "C4", # flake8-comprehensions + "C4", # flake8-comprehensions # "COM", # flake8-commas # "E", # pycodestyle Error # "F", # Pyflakes diff --git a/tests/integration/github/test_generic_commands.py b/tests/integration/github/test_generic_commands.py index 7aceb6d6..2817126a 100644 --- a/tests/integration/github/test_generic_commands.py +++ b/tests/integration/github/test_generic_commands.py @@ -131,7 +131,7 @@ def test_get_tags(self): names = {f"0.{i}.0" for i in range(1, 10)} names.update({"0.0.1", "0.0.2", "0.0.3", "0.3.1"}) - assert names <= set(map(lambda tag: tag.name, tags)) + assert names <= {tag.name for tag in tags} commits = { "ef947cd637f5fa0c28ffca71798d9e61b24880d8", @@ -140,7 +140,7 @@ def test_get_tags(self): "059d21080a7849acff4626b6e0ec61830d537ac4", "088158211481a025a20f3abe716359624615b66e", } - assert commits < set(map(lambda tag: tag.commit_sha, tags)) + assert commits < {tag.commit_sha for tag in tags} def test_get_owners(self): owners = self.ogr_project.get_owners() diff --git a/tests/integration/pagure/test_project_token.py b/tests/integration/pagure/test_project_token.py index fd0acc2f..cbf063a2 100644 --- a/tests/integration/pagure/test_project_token.py +++ b/tests/integration/pagure/test_project_token.py @@ -207,6 +207,4 @@ def test_create_release(self): message="# v0\n\n• added README", ref="2988640e03ddee8385a2acb827a36c8e50b1be1a", ) - assert "v0" in map( - lambda release: release.tag_name, self.ogr_project.get_releases() - ) + assert "v0" in (release.tag_name for release in self.ogr_project.get_releases()) From 11459d4970bbcfbf0792a3e6a5c5e1476084731c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 18:47:36 +0200 Subject: [PATCH 04/16] ci(ruff): enable flake8-commas Signed-off-by: Matej Focko --- ogr/abstract.py | 29 ++++++-- ogr/deprecation.py | 3 +- ogr/exceptions.py | 3 +- ogr/factory.py | 15 ++-- ogr/parsing.py | 2 +- ogr/read_only.py | 26 +++++-- ogr/services/base.py | 15 +++- .../github/auth_providers/github_app.py | 8 ++- ogr/services/github/auth_providers/token.py | 4 +- ogr/services/github/auth_providers/tokman.py | 2 +- ogr/services/github/check_run.py | 13 ++-- ogr/services/github/comments.py | 3 +- ogr/services/github/flag.py | 9 ++- ogr/services/github/issue.py | 11 ++- ogr/services/github/project.py | 43 ++++++++---- ogr/services/github/pull_request.py | 21 ++++-- ogr/services/github/release.py | 10 ++- ogr/services/github/service.py | 11 ++- ogr/services/gitlab/comments.py | 3 +- ogr/services/gitlab/flag.py | 5 +- ogr/services/gitlab/issue.py | 2 +- ogr/services/gitlab/project.py | 68 ++++++++++++------- ogr/services/gitlab/pull_request.py | 16 +++-- ogr/services/gitlab/release.py | 4 +- ogr/services/gitlab/service.py | 11 ++- ogr/services/pagure/flag.py | 14 ++-- ogr/services/pagure/issue.py | 37 +++++++--- ogr/services/pagure/project.py | 63 +++++++++++++---- ogr/services/pagure/pull_request.py | 25 +++++-- ogr/services/pagure/service.py | 39 ++++++++--- ogr/services/pagure/user.py | 2 +- ogr/utils.py | 5 +- pyproject.toml | 2 +- tests/integration/conftest.py | 3 +- tests/integration/factory/test_factory.py | 5 +- tests/integration/github/base.py | 12 ++-- tests/integration/github/base_app.py | 9 +-- tests/integration/github/test_app.py | 9 ++- tests/integration/github/test_check_run.py | 26 ++++--- tests/integration/github/test_comments.py | 25 ++++--- tests/integration/github/test_forks.py | 6 +- .../github/test_generic_commands.py | 30 +++++--- tests/integration/github/test_issues.py | 28 +++++--- .../integration/github/test_pull_requests.py | 9 ++- tests/integration/github/test_readonly.py | 7 +- tests/integration/github/test_releases.py | 9 ++- tests/integration/github/test_service.py | 24 ++++--- tests/integration/gitlab/base.py | 9 ++- tests/integration/gitlab/test_comments.py | 6 +- tests/integration/gitlab/test_forks.py | 3 +- .../gitlab/test_generic_commands.py | 23 ++++--- tests/integration/gitlab/test_issues.py | 33 ++++++--- .../integration/gitlab/test_pull_requests.py | 20 ++++-- tests/integration/gitlab/test_service.py | 24 ++++--- tests/integration/pagure/base.py | 13 ++-- tests/integration/pagure/test_comments.py | 4 +- .../pagure/test_generic_commands.py | 6 +- tests/integration/pagure/test_issues.py | 35 +++++++--- .../integration/pagure/test_project_token.py | 27 +++++--- tests/integration/pagure/test_service.py | 3 +- tests/unit/test_factory.py | 58 ++++++++++------ tests/unit/test_github.py | 17 +++-- 62 files changed, 697 insertions(+), 310 deletions(-) diff --git a/ogr/abstract.py b/ogr/abstract.py index 868787e0..aeeddde7 100644 --- a/ogr/abstract.py +++ b/ogr/abstract.py @@ -61,7 +61,7 @@ def __check_for_internal_failure(ex: APIException): def __wrap_exception( - ex: Union[github.GithubException, gitlab.GitlabError] + ex: Union[github.GithubException, gitlab.GitlabError], ) -> APIException: """ Wraps uncaught exception in one of ogr exceptions. @@ -112,7 +112,7 @@ def wrapper(*args, **kwargs): raise GitlabAPIException("Invalid Gitlab credentials") from ex except requests.exceptions.ConnectionError as ex: raise OgrNetworkError( - "Could not perform the request due to a network error" + "Could not perform the request due to a network error", ) from ex except APIException as ex: __check_for_internal_failure(ex) @@ -443,7 +443,10 @@ def _get_all_comments(self) -> List[IssueComment]: raise NotImplementedError() def get_comments( - self, filter_regex: str = None, reverse: bool = False, author: str = None + self, + filter_regex: str = None, + reverse: bool = False, + author: str = None, ) -> List[IssueComment]: """ Get list of issue comments. @@ -756,7 +759,9 @@ def get_list(project: Any, status: PRStatus = PRStatus.open) -> List["PullReques raise NotImplementedError() def update_info( - self, title: Optional[str] = None, description: Optional[str] = None + self, + title: Optional[str] = None, + description: Optional[str] = None, ) -> "PullRequest": """ Update pull request information. @@ -817,7 +822,10 @@ def get_all_commits(self) -> List[str]: raise NotImplementedError() def search( - self, filter_regex: str, reverse: bool = False, description: bool = True + self, + filter_regex: str, + reverse: bool = False, + description: bool = True, ) -> Optional[Match[str]]: """ Find match in pull request description or comments. @@ -1739,7 +1747,11 @@ def get_releases(self) -> List[Release]: raise NotImplementedError() def create_release( - self, tag: str, name: str, message: str, ref: Optional[str] = None + self, + tag: str, + name: str, + message: str, + ref: Optional[str] = None, ) -> Release: """ Create new release. @@ -1914,7 +1926,10 @@ def get_file_content(self, path: str, ref: str = None) -> str: raise NotImplementedError def get_files( - self, ref: str = None, filter_regex: str = None, recursive: bool = False + self, + ref: str = None, + filter_regex: str = None, + recursive: bool = False, ) -> List[str]: """ Get a list of file paths of the repo. diff --git a/ogr/deprecation.py b/ogr/deprecation.py index 810a24cb..3417b47e 100644 --- a/ogr/deprecation.py +++ b/ogr/deprecation.py @@ -17,5 +17,6 @@ def deprecate_and_set_removal(since: str, remove_in: str, message: str): Decorator. """ return deprecated( - version=since, reason=f"will be removed in {remove_in}: {message}" + version=since, + reason=f"will be removed in {remove_in}: {message}", ) diff --git a/ogr/exceptions.py b/ogr/exceptions.py index 48b1f93b..8d1a6021 100644 --- a/ogr/exceptions.py +++ b/ogr/exceptions.py @@ -51,7 +51,8 @@ class GithubAPIException(APIException): @property def response_code(self): if self.__cause__ is None or not isinstance( - self.__cause__, github.GithubException + self.__cause__, + github.GithubException, ): return None return self.__cause__.status diff --git a/ogr/factory.py b/ogr/factory.py index 7f7de24d..5296b349 100644 --- a/ogr/factory.py +++ b/ogr/factory.py @@ -102,7 +102,7 @@ def get_project( if force_custom_instance: raise OgrException( f"Instance of type {kls.__name__} " - f"matching instance url '{url}' was not provided." + f"matching instance url '{url}' was not provided.", ) if not service: service = kls(instance_url=parsed_repo_url.get_instance_url(), **kwargs) @@ -110,7 +110,8 @@ def get_project( def get_service_class_or_none( - url: str, service_mapping_update: Dict[str, Type[GitService]] = None + url: str, + service_mapping_update: Dict[str, Type[GitService]] = None, ) -> Optional[Type[GitService]]: """ Get the matching service class from the URL. @@ -139,7 +140,8 @@ def get_service_class_or_none( def get_service_class( - url: str, service_mapping_update: Dict[str, Type[GitService]] = None + url: str, + service_mapping_update: Dict[str, Type[GitService]] = None, ) -> Type[GitService]: """ Get the matching service class from the URL. @@ -155,7 +157,8 @@ def get_service_class( Matched class (subclass of `GitService`). """ service_kls = get_service_class_or_none( - url=url, service_mapping_update=service_mapping_update + url=url, + service_mapping_update=service_mapping_update, ) if service_kls: return service_kls @@ -213,12 +216,12 @@ def get_instances_from_dict(instances: Dict) -> Set[GitService]: if "type" not in value: raise OgrException( f"No matching service was found for url '{key}'. " - f"Add the service name as a `type` attribute." + f"Add the service name as a `type` attribute.", ) service_type = value["type"] if service_type not in _SERVICE_MAPPING: raise OgrException( - f"No matching service was found for type '{service_type}'." + f"No matching service was found for type '{service_type}'.", ) service_kls = _SERVICE_MAPPING[service_type] diff --git a/ogr/parsing.py b/ogr/parsing.py index 2c484aea..9e00c277 100644 --- a/ogr/parsing.py +++ b/ogr/parsing.py @@ -89,7 +89,7 @@ def _prepare_url(potential_url: str) -> Optional[ParseResult]: # make it parsable by urlparse if it doesn't contain scheme if not potential_url.startswith( - ("http://", "https://", "git://", "git+https://") + ("http://", "https://", "git://", "git+https://"), ): potential_url = "https://" + potential_url diff --git a/ogr/read_only.py b/ogr/read_only.py index c4e29016..c47880b4 100644 --- a/ogr/read_only.py +++ b/ogr/read_only.py @@ -20,7 +20,9 @@ def log_output( - text: str, default_prefix: str = DEFAULT_RO_PREFIX_STRING, namespace: str = __name__ + text: str, + default_prefix: str = DEFAULT_RO_PREFIX_STRING, + namespace: str = __name__, ) -> None: """ Logs output. @@ -79,7 +81,7 @@ def readonly_func(self, *args, **kwargs): kwargs_str = ", " + kwargs_str log_output( f"{log_message} {self.__class__.__name__}." - f"{func.__name__}({args_str}{kwargs_str})" + f"{func.__name__}({args_str}{kwargs_str})", ) if return_function: return return_function(self, *args, **kwargs) @@ -220,7 +222,10 @@ def pr_merge(cls, original_object: Any, pr_id: int) -> "PullRequest": @classmethod def issue_comment( - cls, original_object: Any, issue_id: int, body: str + cls, + original_object: Any, + issue_id: int, + body: str, ) -> "IssueComment": issue = original_object.get_issue(issue_id) log_output(issue) @@ -234,18 +239,27 @@ def issue_comment( @classmethod def fork_create( - cls, original_object: Any, namespace: Optional[str] = None + cls, + original_object: Any, + namespace: Optional[str] = None, ) -> "GitProject": return original_object @classmethod def commit_comment( - cls, original_object: Any, commit: str, body: str + cls, + original_object: Any, + commit: str, + body: str, ) -> "CommitComment": return CommitComment(sha=commit, body=body, author=cls.author) @classmethod def set_commit_status( - cls, original_object: Any, commit: str, state: CommitStatus, context: str + cls, + original_object: Any, + commit: str, + state: CommitStatus, + context: str, ) -> "CommitFlag": return CommitFlag(commit=commit, state=state, context=context) diff --git a/ogr/services/base.py b/ogr/services/base.py index 1e39e703..22a565c6 100644 --- a/ogr/services/base.py +++ b/ogr/services/base.py @@ -53,13 +53,19 @@ def target_branch_head_commit(self) -> str: return self.target_project.get_sha_from_branch(self.target_branch) def get_comments( - self, filter_regex: str = None, reverse: bool = False, author: str = None + self, + filter_regex: str = None, + reverse: bool = False, + author: str = None, ): all_comments = self._get_all_comments() return filter_comments(all_comments, filter_regex, reverse, author) def search( - self, filter_regex: str, reverse: bool = False, description: bool = True + self, + filter_regex: str, + reverse: bool = False, + description: bool = True, ): all_comments: List[Any] = self.get_comments(reverse=reverse) if description: @@ -82,7 +88,10 @@ class BaseGitUser(GitUser): class BaseIssue(Issue): def get_comments( - self, filter_regex: str = None, reverse: bool = False, author: str = None + self, + filter_regex: str = None, + reverse: bool = False, + author: str = None, ) -> List[IssueComment]: all_comments: List[IssueComment] = self._get_all_comments() return filter_comments(all_comments, filter_regex, reverse, author) diff --git a/ogr/services/github/auth_providers/github_app.py b/ogr/services/github/auth_providers/github_app.py index b43b2fc4..4cd60c09 100644 --- a/ogr/services/github/auth_providers/github_app.py +++ b/ogr/services/github/auth_providers/github_app.py @@ -54,7 +54,7 @@ def private_key(self) -> str: raise OgrException( f"File with the github-app private key " f"({self._private_key_path}) " - f"does not exist." + f"does not exist.", ) return Path(self._private_key_path).read_text() @@ -97,7 +97,7 @@ def get_token(self, namespace: str, repo: str) -> str: if not inst_id: raise OgrException( f"No installation ID provided for {namespace}/{repo}: " - "please make sure that you provided correct credentials of your GitHub app." + "please make sure that you provided correct credentials of your GitHub app.", ) inst_auth = self.integration.get_access_token(inst_id) # type: ignore return inst_auth.token @@ -111,7 +111,9 @@ def try_create( ) -> Optional["GithubApp"]: return ( GithubApp( - github_app_id, github_app_private_key, github_app_private_key_path + github_app_id, + github_app_private_key, + github_app_private_key_path, ) if github_app_id else None diff --git a/ogr/services/github/auth_providers/token.py b/ogr/services/github/auth_providers/token.py index 51a83d03..39991f21 100644 --- a/ogr/services/github/auth_providers/token.py +++ b/ogr/services/github/auth_providers/token.py @@ -34,6 +34,8 @@ def get_token(self, namespace: str, repo: str) -> str: @staticmethod def try_create( - token: str = None, max_retries: Union[int, Retry] = 0, **_ + token: str = None, + max_retries: Union[int, Retry] = 0, + **_, ) -> Optional["TokenAuthentication"]: return TokenAuthentication(token, max_retries=max_retries) diff --git a/ogr/services/github/auth_providers/tokman.py b/ogr/services/github/auth_providers/tokman.py index f5268682..0978ba39 100644 --- a/ogr/services/github/auth_providers/tokman.py +++ b/ogr/services/github/auth_providers/tokman.py @@ -37,7 +37,7 @@ def get_token(self, namespace: str, repo: str) -> str: cls = OgrNetworkError if response.status_code >= 500 else OgrException raise cls( - f"Couldn't retrieve token from Tokman: ({response.status_code}) {response.text}" + f"Couldn't retrieve token from Tokman: ({response.status_code}) {response.text}", ) return response.json().get("access_token", None) diff --git a/ogr/services/github/check_run.py b/ogr/services/github/check_run.py index 480de1c0..30bdf327 100644 --- a/ogr/services/github/check_run.py +++ b/ogr/services/github/check_run.py @@ -91,7 +91,9 @@ def create_github_check_run_output( class GithubCheckRun(OgrAbstractClass): def __init__( - self, project: "ogr_github.GithubProject", raw_check_run: CheckRun + self, + project: "ogr_github.GithubProject", + raw_check_run: CheckRun, ) -> None: self.raw_check_run = raw_check_run self.project = project @@ -219,7 +221,7 @@ def change_status( ) and conclusion is None: raise OperationNotSupported( "When provided completed status or completed at," - " you need to provide conclusion." + " you need to provide conclusion.", ) self.raw_check_run.edit( @@ -286,14 +288,15 @@ def get( """ if check_run_id is not None and commit_sha: raise OperationNotSupported( - "Cannot retrieve check run by both ID and commit hash" + "Cannot retrieve check run by both ID and commit hash", ) elif not (check_run_id is not None or commit_sha): raise OperationNotSupported("Cannot retrieve check run by no criteria") if check_run_id is not None: return GithubCheckRun( - project, project.github_repo.get_check_run(check_run_id) + project, + project.github_repo.get_check_run(check_run_id), ) check_runs = project.github_repo.get_commit(commit_sha).get_check_runs() @@ -358,7 +361,7 @@ def create( ) and conclusion is None: raise OperationNotSupported( "When provided completed_at or completed status, " - "you need to provide conclusion." + "you need to provide conclusion.", ) created_check_run = project.github_repo.create_check_run( diff --git a/ogr/services/github/comments.py b/ogr/services/github/comments.py index 4e62f787..a6ffd4e0 100644 --- a/ogr/services/github/comments.py +++ b/ogr/services/github/comments.py @@ -23,7 +23,8 @@ def delete(self) -> None: class GithubComment(Comment): def _from_raw_comment( - self, raw_comment: Union[_GithubIssueComment, _GithubPullRequestComment] + self, + raw_comment: Union[_GithubIssueComment, _GithubPullRequestComment], ) -> None: self._raw_comment = raw_comment self._id = raw_comment.id diff --git a/ogr/services/github/flag.py b/ogr/services/github/flag.py index 3703d381..8cf9c2da 100644 --- a/ogr/services/github/flag.py +++ b/ogr/services/github/flag.py @@ -36,7 +36,9 @@ def get(project: "ogr_github.GithubProject", commit: str) -> List["CommitFlag"]: try: return [ GithubCommitFlag( - raw_commit_flag=raw_status, project=project, commit=commit + raw_commit_flag=raw_status, + project=project, + commit=commit, ) for raw_status in statuses ] @@ -59,7 +61,10 @@ def set( if trim: description = description[:140] status = github_commit.create_status( - state.name, target_url, description, context + state.name, + target_url, + description, + context, ) return GithubCommitFlag(project=project, raw_commit_flag=status, commit=commit) diff --git a/ogr/services/github/issue.py b/ogr/services/github/issue.py index 75a295a3..6ba98c83 100644 --- a/ogr/services/github/issue.py +++ b/ogr/services/github/issue.py @@ -23,11 +23,13 @@ class GithubIssue(BaseIssue): raw_issue: _GithubIssue def __init__( - self, raw_issue: _GithubIssue, project: "ogr_github.GithubProject" + self, + raw_issue: _GithubIssue, + project: "ogr_github.GithubProject", ) -> None: if raw_issue.pull_request: raise GithubAPIException( - f"Requested issue #{raw_issue.number} is a pull request" + f"Requested issue #{raw_issue.number} is a pull request", ) super().__init__(raw_issue=raw_issue, project=project) @@ -94,7 +96,10 @@ def create( raise IssueTrackerDisabled() github_issue = project.github_repo.create_issue( - title=title, body=body, labels=labels or [], assignees=assignees or [] + title=title, + body=body, + labels=labels or [], + assignees=assignees or [], ) return GithubIssue(github_issue, project) diff --git a/ogr/services/github/project.py b/ogr/services/github/project.py index 8cc00368..afb29b8a 100644 --- a/ogr/services/github/project.py +++ b/ogr/services/github/project.py @@ -59,7 +59,7 @@ def __init__( ) -> None: if unprocess_kwargs: logger.warning( - f"GithubProject will not process these kwargs: {unprocess_kwargs}" + f"GithubProject will not process these kwargs: {unprocess_kwargs}", ) super().__init__(repo, service, namespace) self._github_repo = github_repo @@ -71,7 +71,8 @@ def __init__( def github_instance(self): if not self._github_instance: self._github_instance = self.service.get_pygithub_instance( - self.namespace, self.repo + self.namespace, + self.repo, ) return self._github_instance @@ -80,7 +81,7 @@ def github_instance(self): def github_repo(self): if not self._github_repo: self._github_repo = self.github_instance.get_repo( - full_name_or_id=f"{self.namespace}/{self.repo}" + full_name_or_id=f"{self.namespace}/{self.repo}", ) return self._github_repo @@ -115,7 +116,10 @@ def _construct_fork_project(self) -> Optional["GithubProject"]: user_login = gh_user.login try: project = GithubProject( - self.repo, self.service, namespace=user_login, read_only=self.read_only + self.repo, + self.service, + namespace=user_login, + read_only=self.read_only, ) if not project.github_repo: # The github_repo attribute is lazy. @@ -172,7 +176,8 @@ def add_user(self, user: str, access_level: AccessLevel) -> None: } try: invitation = self.github_repo.add_to_collaborators( - user, permission=access_dict[access_level] + user, + permission=access_dict[access_level], ) except Exception as ex: raise GithubAPIException(f"User {user} not found") from ex @@ -195,7 +200,7 @@ def get_fork(self, create: bool = True) -> Optional["GithubProject"]: else: logger.info( f"Fork of {self.github_repo.full_name}" - " does not exist and we were asked not to create it." + " does not exist and we were asked not to create it.", ) return None return self._construct_fork_project() @@ -209,7 +214,7 @@ def __get_collaborators(self) -> Set[str]: collaborators = self._get_collaborators_with_permission() except github.GithubException: logger.debug( - "Current Github token must have push access to view repository permissions." + "Current Github token must have push access to view repository permissions.", ) return set() @@ -323,12 +328,18 @@ def create_pr( log_message="Create Comment to commit", ) def commit_comment( - self, commit: str, body: str, filename: str = None, row: int = None + self, + commit: str, + body: str, + filename: str = None, + row: int = None, ) -> CommitComment: github_commit: Commit = self.github_repo.get_commit(commit) if filename and row: comment = github_commit.create_comment( - body=body, position=row, path=filename + body=body, + position=row, + path=filename, ) else: comment = github_commit.create_comment(body=body) @@ -426,7 +437,8 @@ def get_file_content(self, path: str, ref=None) -> str: ref = ref or self.default_branch try: return self.github_repo.get_contents( - path=path, ref=ref + path=path, + ref=ref, ).decoded_content.decode() except (UnknownObjectException, GithubException) as ex: if ex.status == 404: @@ -434,7 +446,10 @@ def get_file_content(self, path: str, ref=None) -> str: raise GithubAPIException() from ex def get_files( - self, ref: str = None, filter_regex: str = None, recursive: bool = False + self, + ref: str = None, + filter_regex: str = None, + recursive: bool = False, ) -> List[str]: ref = ref or self.default_branch paths = [] @@ -445,7 +460,7 @@ def get_files( file_content = contents.pop(0) if file_content.type == "dir": contents.extend( - self.github_repo.get_contents(path=file_content.path, ref=ref) + self.github_repo.get_contents(path=file_content.path, ref=ref), ) else: paths.append(file_content.path) @@ -487,7 +502,9 @@ def update_labels(self, labels): if label.name not in current_label_names: color = self._normalize_label_color(color=label.color) self.github_repo.create_label( - name=label.name, color=color, description=label.description or "" + name=label.name, + color=color, + description=label.description or "", ) changes += 1 diff --git a/ogr/services/github/pull_request.py b/ogr/services/github/pull_request.py index 755ed9fb..dd769842 100644 --- a/ogr/services/github/pull_request.py +++ b/ogr/services/github/pull_request.py @@ -92,7 +92,7 @@ def patch(self) -> bytes: if not response.ok: cls = OgrNetworkError if response.status_code >= 500 else GithubAPIException raise cls( - f"Couldn't get patch from {self._raw_pr.patch_url} because {response.reason}." + f"Couldn't get patch from {self._raw_pr.patch_url} because {response.reason}.", ) return response.content @@ -121,7 +121,7 @@ def source_project(self) -> "ogr_github.GithubProject": if self._source_project is None: self._source_project = ( self._target_project.service.get_project_from_github_repository( - self._raw_pr.head.repo + self._raw_pr.head.repo, ) ) @@ -157,11 +157,15 @@ def create( source_branch = f"{fork_username}:{source_branch}" if fork_username != project.namespace and project.parent is not None: github_repo = GithubPullRequest.__get_fork( - fork_username, project.parent.github_repo + fork_username, + project.parent.github_repo, ) created_pr = github_repo.create_pull( - title=title, body=body, base=target_branch, head=source_branch + title=title, + body=body, + base=target_branch, + head=source_branch, ) logger.info(f"PR {created_pr.id} created: {target_branch}<-{source_branch}") return GithubPullRequest(created_pr, target_project) @@ -169,7 +173,7 @@ def create( @staticmethod def __get_fork(fork_username: str, repo: _GithubRepository) -> _GithubRepository: forks = list( - filter(lambda fork: fork.owner.login == fork_username, repo.get_forks()) + filter(lambda fork: fork.owner.login == fork_username, repo.get_forks()), ) if not forks: raise GithubAPIException("Requested fork doesn't exist") @@ -185,7 +189,8 @@ def get(project: "ogr_github.GithubProject", pr_id: int) -> "PullRequest": @staticmethod def get_list( - project: "ogr_github.GithubProject", status: PRStatus = PRStatus.open + 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' @@ -205,7 +210,9 @@ def get_list( return [] def update_info( - self, title: Optional[str] = None, description: Optional[str] = None + self, + title: Optional[str] = None, + description: Optional[str] = None, ) -> "PullRequest": try: self._raw_pr.edit(title=title, body=description) diff --git a/ogr/services/github/release.py b/ogr/services/github/release.py index c6e6753b..fb25f203 100644 --- a/ogr/services/github/release.py +++ b/ogr/services/github/release.py @@ -17,7 +17,8 @@ class GithubRelease(Release): @staticmethod def _release_id_from_name( - project: "ogr_github.GithubProject", name: str + project: "ogr_github.GithubProject", + name: str, ) -> Optional[int]: releases = project.github_repo.get_releases() for release in releases: @@ -27,7 +28,8 @@ def _release_id_from_name( @staticmethod def _release_id_from_tag( - project: "ogr_github.GithubProject", tag: str + project: "ogr_github.GithubProject", + tag: str, ) -> Optional[int]: releases = project.github_repo.get_releases() for release in releases: @@ -106,7 +108,9 @@ def create( ref: Optional[str] = None, ) -> "Release": created_release = project.github_repo.create_git_release( - tag=tag, name=name, message=message + tag=tag, + name=name, + message=message, ) return GithubRelease(created_release, project) diff --git a/ogr/services/github/service.py b/ogr/services/github/service.py index 46c2f657..9848bf3a 100644 --- a/ogr/services/github/service.py +++ b/ogr/services/github/service.py @@ -106,7 +106,7 @@ def set_auth_method(self, method: AuthMethod): self._other_auth_method = self._auth_methods[method] else: raise GithubAPIException( - f"Choosen authentication method ({method}) is not available" + f"Choosen authentication method ({method}) is not available", ) def reset_auth_method(self): @@ -144,7 +144,11 @@ def __hash__(self) -> int: return hash(str(self)) def get_project( - self, repo=None, namespace=None, is_fork=False, **kwargs + self, + repo=None, + namespace=None, + is_fork=False, + **kwargs, ) -> "GithubProject": if is_fork: namespace = self.user.get_username() @@ -157,7 +161,8 @@ def get_project( ) def get_project_from_github_repository( - self, github_repo: PyGithubRepository.Repository + self, + github_repo: PyGithubRepository.Repository, ) -> "GithubProject": return GithubProject( repo=github_repo.name, diff --git a/ogr/services/gitlab/comments.py b/ogr/services/gitlab/comments.py index 0c542992..a8a5d87b 100644 --- a/ogr/services/gitlab/comments.py +++ b/ogr/services/gitlab/comments.py @@ -31,7 +31,8 @@ def delete(self) -> None: class GitlabComment(Comment): def _from_raw_comment( - self, raw_comment: Union[ProjectIssueNote, ProjectMergeRequestNote] + self, + raw_comment: Union[ProjectIssueNote, ProjectMergeRequestNote], ) -> None: self._raw_comment = raw_comment self._id = raw_comment.get_id() diff --git a/ogr/services/gitlab/flag.py b/ogr/services/gitlab/flag.py index 19a7fed0..1dfdbd86 100644 --- a/ogr/services/gitlab/flag.py +++ b/ogr/services/gitlab/flag.py @@ -95,12 +95,13 @@ def set( @property def created(self) -> datetime.datetime: return datetime.datetime.strptime( - self._raw_commit_flag.created_at, "%Y-%m-%dT%H:%M:%S.%fZ" + self._raw_commit_flag.created_at, + "%Y-%m-%dT%H:%M:%S.%fZ", ) @property def edited(self) -> datetime.datetime: raise OperationNotSupported( "GitLab doesn't support edited on commit flags, for more info " - "see https://github.com/packit/ogr/issues/413#issuecomment-729623702" + "see https://github.com/packit/ogr/issues/413#issuecomment-729623702", ) diff --git a/ogr/services/gitlab/issue.py b/ogr/services/gitlab/issue.py index 4dcb2eb5..99819af2 100644 --- a/ogr/services/gitlab/issue.py +++ b/ogr/services/gitlab/issue.py @@ -169,7 +169,7 @@ def add_assignee(self, *assignees: str) -> None: assignee_ids = self._raw_issue.__dict__.get("assignee_ids") or [] for assignee in assignees: users = self.project.service.gitlab_instance.users.list( # type: ignore - username=assignee + username=assignee, ) if not users: raise GitlabAPIException(f"Unable to find '{assignee}' username") diff --git a/ogr/services/gitlab/project.py b/ogr/services/gitlab/project.py index 6e335fc0..1676665e 100644 --- a/ogr/services/gitlab/project.py +++ b/ogr/services/gitlab/project.py @@ -45,7 +45,7 @@ def __init__( ) -> None: if unprocess_kwargs: logger.warning( - f"GitlabProject will not process these kwargs: {unprocess_kwargs}" + f"GitlabProject will not process these kwargs: {unprocess_kwargs}", ) super().__init__(repo, service, namespace) self._gitlab_repo = gitlab_repo @@ -55,7 +55,7 @@ def __init__( def gitlab_repo(self) -> GitlabObjectsProject: if not self._gitlab_repo: self._gitlab_repo = self.service.gitlab_instance.projects.get( - f"{self.namespace}/{self.repo}" + f"{self.namespace}/{self.repo}", ) return self._gitlab_repo @@ -99,7 +99,9 @@ def _construct_fork_project(self) -> Optional["GitlabProject"]: user_login = self.service.user.get_username() try: project = GitlabProject( - repo=self.repo, service=self.service, namespace=user_login + repo=self.repo, + service=self.service, + namespace=user_login, ) if project.gitlab_repo: return project @@ -146,14 +148,14 @@ def get_fork(self, create: bool = True) -> Optional["GitlabProject"]: else: logger.info( f"Fork of {self.gitlab_repo.attributes['name']}" - " does not exist and we were asked not to create it." + " does not exist and we were asked not to create it.", ) return None return self._construct_fork_project() def get_owners(self) -> List[str]: return self._get_collaborators_with_given_access( - access_levels=[gitlab.const.OWNER_ACCESS] + access_levels=[gitlab.const.OWNER_ACCESS], ) def who_can_close_issue(self) -> Set[str]: @@ -164,8 +166,8 @@ def who_can_close_issue(self) -> Set[str]: gitlab.const.DEVELOPER_ACCESS, gitlab.const.MAINTAINER_ACCESS, gitlab.const.OWNER_ACCESS, - ] - ) + ], + ), ) def who_can_merge_pr(self) -> Set[str]: @@ -175,8 +177,8 @@ def who_can_merge_pr(self) -> Set[str]: gitlab.const.DEVELOPER_ACCESS, gitlab.const.MAINTAINER_ACCESS, gitlab.const.OWNER_ACCESS, - ] - ) + ], + ), ) def can_merge_pr(self, username) -> bool: @@ -186,7 +188,8 @@ def delete(self) -> None: self.gitlab_repo.delete() def _get_collaborators_with_given_access( - self, access_levels: List[int] + self, + access_levels: List[int], ) -> List[str]: """ Get all project collaborators with one of the given access levels. @@ -233,7 +236,7 @@ def add_user(self, user: str, access_level: AccessLevel) -> None: raise GitlabAPIException(f"User {user} not found") from e try: self.gitlab_repo.members.create( - {"user_id": user_id, "access_level": access_dict[access_level]} + {"user_id": user_id, "access_level": access_dict[access_level]}, ) except Exception as e: raise GitlabAPIException(f"User {user} already exists") from e @@ -268,7 +271,11 @@ def create_pr( pass def commit_comment( - self, commit: str, body: str, filename: str = None, row: int = None + self, + commit: str, + body: str, + filename: str = None, + row: int = None, ) -> "CommitComment": try: commit_object: ProjectCommit = self.gitlab_repo.commits.get(commit) @@ -278,7 +285,7 @@ def commit_comment( if filename and row: raw_comment = commit_object.comments.create( - {"note": body, "path": filename, "line": row, "line_type": "new"} + {"note": body, "path": filename, "line": row, "line_type": "new"}, ) else: raw_comment = commit_object.comments.create({"note": body}) @@ -287,7 +294,9 @@ def commit_comment( @staticmethod def _commit_comment_from_gitlab_object(raw_comment, commit) -> CommitComment: return CommitComment( - sha=commit, body=raw_comment.note, author=raw_comment.author["username"] + sha=commit, + body=raw_comment.note, + author=raw_comment.author["username"], ) def get_commit_comments(self, commit: str) -> List[CommitComment]: @@ -334,11 +343,13 @@ def fork_create(self, namespace: Optional[str] = None) -> "GitlabProject": except gitlab.GitlabCreateError as ex: logger.error(f"Repo {self.gitlab_repo} cannot be forked") raise GitlabAPIException( - f"Repo {self.gitlab_repo} cannot be forked" + f"Repo {self.gitlab_repo} cannot be forked", ) from ex logger.debug(f"Forked to {fork.namespace['full_path']}/{fork.path}") return GitlabProject( - namespace=fork.namespace["full_path"], service=self.service, repo=fork.path + namespace=fork.namespace["full_path"], + service=self.service, + repo=fork.path, ) def change_token(self, new_token: str): @@ -358,13 +369,18 @@ def get_file_content(self, path, ref=None) -> str: raise GitlabAPIException() from ex def get_files( - self, ref: str = None, filter_regex: str = None, recursive: bool = False + self, + ref: str = None, + filter_regex: str = None, + recursive: bool = False, ) -> List[str]: ref = ref or self.default_branch paths = [ file_dict["path"] for file_dict in self.gitlab_repo.repository_tree( - ref=ref, recursive=recursive, all=True + ref=ref, + recursive=recursive, + all=True, ) if file_dict["type"] != "tree" ] @@ -420,7 +436,11 @@ def get_release(self, identifier=None, name=None, tag_name=None) -> GitlabReleas @indirect(GitlabRelease.create) def create_release( - self, tag: str, name: str, message: str, commit_sha: Optional[str] = None + self, + tag: str, + name: str, + message: str, + commit_sha: Optional[str] = None, ) -> GitlabRelease: pass @@ -445,7 +465,7 @@ def get_forks(self) -> List["GitlabProject"]: # > KeyError: 0 # looks like some API weirdness raise OperationNotSupported( - "Please upgrade python-gitlab to a newer version." + "Please upgrade python-gitlab to a newer version.", ) from ex return [ GitlabProject( @@ -476,7 +496,7 @@ def update_labels(self, labels): "name": label.name, "color": color, "description": label.description or "", - } + }, ) changes += 1 @@ -509,7 +529,7 @@ def format_contributor(contributor: Dict[str, Any]) -> str: return f"{contributor['name']} <{contributor['email']}>" return set( - map(format_contributor, self.gitlab_repo.repository_contributors(all=True)) + map(format_contributor, self.gitlab_repo.repository_contributors(all=True)), ) def users_with_write_access(self) -> Set[str]: @@ -519,6 +539,6 @@ def users_with_write_access(self) -> Set[str]: gitlab.const.DEVELOPER_ACCESS, gitlab.const.MAINTAINER_ACCESS, gitlab.const.OWNER_ACCESS, - ] - ) + ], + ), ) diff --git a/ogr/services/gitlab/pull_request.py b/ogr/services/gitlab/pull_request.py index 20893b10..5a2ece79 100644 --- a/ogr/services/gitlab/pull_request.py +++ b/ogr/services/gitlab/pull_request.py @@ -98,7 +98,7 @@ def patch(self) -> bytes: if not response.ok: cls = OgrNetworkError if response.status_code >= 500 else GitlabAPIException raise cls( - f"Couldn't get patch from {self.url}.patch because {response.reason}." + f"Couldn't get patch from {self.url}.patch because {response.reason}.", ) return response.content @@ -136,7 +136,7 @@ def source_project(self) -> "ogr_gitlab.GitlabProject": if self._source_project is None: self._source_project = ( self._target_project.service.get_project_from_project_id( - self._raw_pr.attributes["source_project_id"] + self._raw_pr.attributes["source_project_id"], ) ) return self._source_project @@ -200,7 +200,8 @@ def create( @staticmethod def __get_fork( - fork_username: str, project: "ogr_gitlab.GitlabProject" + fork_username: str, + project: "ogr_gitlab.GitlabProject", ) -> "ogr_gitlab.GitlabProject": """ Returns forked project of a requested user. Internal method, in case the fork @@ -220,7 +221,7 @@ def __get_fork( filter( lambda fork: fork.gitlab_repo.namespace["full_path"] == fork_username, project.get_forks(), - ) + ), ) if not forks: raise GitlabAPIException("Requested fork doesn't exist") @@ -236,7 +237,8 @@ def get(project: "ogr_gitlab.GitlabProject", pr_id: int) -> "PullRequest": @staticmethod def get_list( - project: "ogr_gitlab.GitlabProject", status: PRStatus = PRStatus.open + project: "ogr_gitlab.GitlabProject", + status: PRStatus = PRStatus.open, ) -> List["PullRequest"]: # Gitlab API has status 'opened', not 'open' mrs = project.gitlab_repo.mergerequests.list( @@ -247,7 +249,9 @@ def get_list( return [GitlabPullRequest(mr, project) for mr in mrs] def update_info( - self, title: Optional[str] = None, description: Optional[str] = None + self, + title: Optional[str] = None, + description: Optional[str] = None, ) -> "PullRequest": if title: self._raw_pr.title = title diff --git a/ogr/services/gitlab/release.py b/ogr/services/gitlab/release.py index 8f2cb720..832a43a2 100644 --- a/ogr/services/gitlab/release.py +++ b/ogr/services/gitlab/release.py @@ -66,7 +66,7 @@ def get_latest(project: "ogr_gitlab.GitlabProject") -> Optional["Release"]: def get_list(project: "ogr_gitlab.GitlabProject") -> List["Release"]: if not hasattr(project.gitlab_repo, "releases"): raise OperationNotSupported( - "This version of python-gitlab does not support release, please upgrade." + "This version of python-gitlab does not support release, please upgrade.", ) releases = project.gitlab_repo.releases.list(all=True) return [GitlabRelease(release, project) for release in releases] @@ -80,7 +80,7 @@ def create( ref: Optional[str] = None, ) -> "Release": release = project.gitlab_repo.releases.create( - {"name": name, "tag_name": tag, "description": message, "ref": ref} + {"name": name, "tag_name": tag, "description": message, "ref": ref}, ) return GitlabRelease(release, project) diff --git a/ogr/services/gitlab/service.py b/ogr/services/gitlab/service.py index feab7bd3..efa99616 100644 --- a/ogr/services/gitlab/service.py +++ b/ogr/services/gitlab/service.py @@ -85,7 +85,11 @@ def __hash__(self) -> int: return hash(str(self)) def get_project( - self, repo=None, namespace=None, is_fork=False, **kwargs + self, + repo=None, + namespace=None, + is_fork=False, + **kwargs, ) -> "GitlabProject": if is_fork: namespace = self.user.get_username() @@ -125,7 +129,10 @@ def project_create( except gitlab.GitlabCreateError as ex: raise GitlabAPIException("Project already exists") from ex return GitlabProject( - repo=repo, namespace=namespace, service=self, gitlab_repo=new_project + repo=repo, + namespace=namespace, + service=self, + gitlab_repo=new_project, ) def list_projects( diff --git a/ogr/services/pagure/flag.py b/ogr/services/pagure/flag.py index 92e2e682..a456bd8f 100644 --- a/ogr/services/pagure/flag.py +++ b/ogr/services/pagure/flag.py @@ -66,20 +66,26 @@ def set( data["uid"] = uid response = project._call_project_api( - "c", commit, "flag", method="POST", data=data + "c", + commit, + "flag", + method="POST", + data=data, ) return PagureCommitFlag( - project=project, raw_commit_flag=response["flag"], uid=response["uid"] + project=project, + raw_commit_flag=response["flag"], + uid=response["uid"], ) @property def created(self) -> datetime.datetime: return datetime.datetime.fromtimestamp( - int(self._raw_commit_flag["date_created"]) + int(self._raw_commit_flag["date_created"]), ) @property def edited(self) -> datetime.datetime: return datetime.datetime.fromtimestamp( - int(self._raw_commit_flag["date_updated"]) + int(self._raw_commit_flag["date_updated"]), ) diff --git a/ogr/services/pagure/issue.py b/ogr/services/pagure/issue.py index 7fa3ff26..1bfc0af5 100644 --- a/ogr/services/pagure/issue.py +++ b/ogr/services/pagure/issue.py @@ -53,7 +53,9 @@ def status(self) -> IssueStatus: @property def url(self) -> str: return self.project._get_project_url( - "issue", str(self.id), add_api_endpoint_part=False + "issue", + str(self.id), + add_api_endpoint_part=False, ) @property @@ -103,12 +105,15 @@ def __update_info( } updated_issue = self.project._call_project_api( - "issue", str(self.id), method="POST", data=data + "issue", + str(self.id), + method="POST", + data=data, ) self._raw_issue = updated_issue["issue"] except Exception as ex: raise PagureAPIException( - "there was an error while updating the issue" + "there was an error while updating the issue", ) from ex @staticmethod @@ -191,7 +196,11 @@ def _get_all_comments(self) -> List[IssueComment]: def comment(self, body: str) -> IssueComment: payload = {"comment": body} self.project._call_project_api( - "issue", str(self.id), "comment", data=payload, method="POST" + "issue", + str(self.id), + "comment", + data=payload, + method="POST", ) self.__dirty = True return PagureIssueComment(parent=self, body=body, author=self.project._user) @@ -199,7 +208,11 @@ def comment(self, body: str) -> IssueComment: def close(self) -> "PagureIssue": payload = {"status": "Closed"} self.project._call_project_api( - "issue", str(self.id), "status", data=payload, method="POST" + "issue", + str(self.id), + "status", + data=payload, + method="POST", ) self.__dirty = True return self @@ -209,12 +222,20 @@ def add_assignee(self, *assignees: str) -> None: raise OperationNotSupported("Pagure does not support multiple assignees") payload = {"assignee": assignees[0]} self.project._call_project_api( - "issue", str(self.id), "assign", data=payload, method="POST" + "issue", + str(self.id), + "assign", + data=payload, + method="POST", ) def get_comment(self, comment_id: int) -> IssueComment: return PagureIssueComment( self.project._call_project_api( - "issue", str(self.id), "comment", str(comment_id), method="GET" - ) + "issue", + str(self.id), + "comment", + str(comment_id), + method="GET", + ), ) diff --git a/ogr/services/pagure/project.py b/ogr/services/pagure/project.py index c333ec09..41a376cc 100644 --- a/ogr/services/pagure/project.py +++ b/ogr/services/pagure/project.py @@ -113,7 +113,10 @@ def _call_project_api( ) return self.service.call_api( - url=request_url, method=method, params=params, data=data + url=request_url, + method=method, + params=params, + data=data, ) def _call_project_api_raw( @@ -150,7 +153,10 @@ def _call_project_api_raw( ) return self.service.call_api_raw( - url=request_url, method=method, params=params, data=data + url=request_url, + method=method, + params=params, + data=data, ) def _get_project_url(self, *args, add_fork_part=True, add_api_endpoint_part=True): @@ -257,7 +263,10 @@ def create_issue( @indirect(PagurePullRequest.get_list) def get_pr_list( - self, status: PRStatus = PRStatus.open, assignee=None, author=None + self, + status: PRStatus = PRStatus.open, + assignee=None, + author=None, ) -> List[PullRequest]: pass @@ -281,7 +290,7 @@ def create_pr( def fork_create(self, namespace: Optional[str] = None) -> "PagureProject": if namespace is not None: raise OperationNotSupported( - "Pagure does not support forking to namespaces." + "Pagure does not support forking to namespaces.", ) request_url = self.service.get_api_url("fork") @@ -318,7 +327,7 @@ def get_fork(self, create: bool = True) -> Optional["PagureProject"]: else: logger.info( f"Fork of {self.repo}" - " does not exist and we were asked not to create it." + " does not exist and we were asked not to create it.", ) return None return self._construct_fork_project() @@ -340,7 +349,7 @@ def is_private(self) -> bool: return False raise OperationNotSupported( f"is_private is not implemented for {self.service.instance_url}." - f"Please open issue in https://github.com/packit/ogr" + f"Please open issue in https://github.com/packit/ogr", ) def is_forked(self) -> bool: @@ -381,7 +390,10 @@ def remove_group(self, group: str) -> None: self.add_user_or_group(group, None, "group") def add_user_or_group( - self, user: str, access_level: Optional[AccessLevel], user_type: str + self, + user: str, + access_level: Optional[AccessLevel], + user_type: str, ) -> None: access_dict = { AccessLevel.pull: "ticket", @@ -414,14 +426,18 @@ def change_token(self, new_token: str) -> None: def get_file_content(self, path: str, ref=None) -> str: ref = ref or self.default_branch result = self._call_project_api_raw( - "raw", ref, "f", path, add_api_endpoint_part=False + "raw", + ref, + "f", + path, + add_api_endpoint_part=False, ) if not result or result.reason == "NOT FOUND": raise FileNotFoundError(f"File '{path}' on {ref} not found") if result.reason != "OK": raise PagureAPIException( - f"File '{path}' on {ref} not found due to {result.reason}" + f"File '{path}' on {ref} not found due to {result.reason}", ) return result.content.decode() @@ -433,7 +449,11 @@ def get_sha_from_tag(self, tag_name: str) -> str: return tags_dict[tag_name].commit_sha def commit_comment( - self, commit: str, body: str, filename: str = None, row: int = None + self, + commit: str, + body: str, + filename: str = None, + row: int = None, ) -> CommitComment: raise OperationNotSupported("Commit comments are not supported on Pagure.") @@ -481,14 +501,19 @@ def get_latest_release(self) -> Optional[PagureRelease]: @indirect(PagureRelease.create) def create_release( - self, tag: str, name: str, message: str, ref: Optional[str] = None + self, + tag: str, + name: str, + message: str, + ref: Optional[str] = None, ) -> Release: pass def get_forks(self) -> List["PagureProject"]: forks_url = self.service.get_api_url("projects") projects_response = self.service.call_api( - url=forks_url, params={"fork": True, "pattern": self.repo} + url=forks_url, + params={"fork": True, "pattern": self.repo}, ) return [ PagureProject( @@ -511,7 +536,10 @@ def full_repo_name(self) -> str: return f"{fork}{namespace}{self.repo}" def __get_files( - self, path: str, ref: str = None, recursive: bool = False + self, + path: str, + ref: str = None, + recursive: bool = False, ) -> Iterable[str]: subfolders = ["."] @@ -529,7 +557,10 @@ def __get_files( subfolders.append(file["path"]) def get_files( - self, ref: str = None, filter_regex: str = None, recursive: bool = False + self, + ref: str = None, + filter_regex: str = None, + recursive: bool = False, ) -> List[str]: ref = ref or self.default_branch paths = list(self.__get_files(".", ref, recursive)) @@ -540,7 +571,9 @@ def get_files( def get_sha_from_branch(self, branch: str) -> Optional[str]: branches = self._call_project_api( - "git", "branches", params={"with_commits": True} + "git", + "branches", + params={"with_commits": True}, )["branches"] return branches.get(branch) diff --git a/ogr/services/pagure/pull_request.py b/ogr/services/pagure/pull_request.py index 1d9acbad..d20681f0 100644 --- a/ogr/services/pagure/pull_request.py +++ b/ogr/services/pagure/pull_request.py @@ -54,7 +54,7 @@ def url(self) -> str: self._raw_pr["project"]["url_path"], "pull-request", str(self.id), - ] + ], ) @property @@ -93,7 +93,9 @@ def commits_url(self) -> str: @property def patch(self) -> bytes: request_response = self._target_project._call_project_api_raw( - "pull-request", f"{self.id}.patch", add_api_endpoint_part=False + "pull-request", + f"{self.id}.patch", + add_api_endpoint_part=False, ) if request_response.status_code != 200: raise PagureAPIException( @@ -120,7 +122,7 @@ def source_project(self) -> "ogr_pagure.PagureProject": source_project_info["username"] = source["user"]["name"] self._source_project = self._target_project.service.get_project( - **source_project_info + **source_project_info, ) return self._source_project @@ -135,7 +137,10 @@ def __str__(self) -> str: def __call_api(self, *args, **kwargs) -> dict: return self._target_project._call_project_api( - "pull-request", str(self.id), *args, **kwargs + "pull-request", + str(self.id), + *args, + **kwargs, ) @staticmethod @@ -174,7 +179,10 @@ def create( data["repo_from_namespace"] = fork_project.namespace response = caller._call_project_api( - "pull-request", "new", method="POST", data=data + "pull-request", + "new", + method="POST", + data=data, ) return PagurePullRequest(response, caller) @@ -209,7 +217,9 @@ def get_list( return [PagurePullRequest(pr_dict, project) for pr_dict in raw_prs] def update_info( - self, title: Optional[str] = None, description: Optional[str] = None + self, + title: Optional[str] = None, + description: Optional[str] = None, ) -> "PullRequest": try: data = {"title": title if title else self.title} @@ -324,5 +334,6 @@ def get_comment(self, comment_id: int) -> PRComment: return comment raise PagureAPIException( - f"No comment with id#{comment_id} in PR#{self.id} found.", response_code=404 + f"No comment with id#{comment_id} in PR#{self.id} found.", + response_code=404, ) diff --git a/ogr/services/pagure/service.py b/ogr/services/pagure/service.py index 2b62670f..a51edd91 100644 --- a/ogr/services/pagure/service.py +++ b/ogr/services/pagure/service.py @@ -96,7 +96,9 @@ def get_project(self, **kwargs) -> "PagureProject": return PagureProject(service=self, **kwargs) else: return PagureProject( - service=self, username=self.user.get_username(), **kwargs + service=self, + username=self.user.get_username(), + **kwargs, ) def get_project_from_url(self, url: str) -> "PagureProject": @@ -120,7 +122,11 @@ def user(self) -> "PagureUser": return PagureUser(service=self) def call_api( - self, url: str, method: str = None, params: dict = None, data=None + self, + url: str, + method: str = None, + params: dict = None, + data=None, ) -> dict: """ Call API endpoint. @@ -154,7 +160,8 @@ def call_api( if not response.json_content: logger.debug(response.content) raise PagureAPIException( - "Error while decoding JSON: {0}", response_code=response.status_code + "Error while decoding JSON: {0}", + response_code=response.status_code, ) if not response.ok: @@ -179,7 +186,11 @@ def call_api( return response.json_content def call_api_raw( - self, url: str, method: str = None, params: dict = None, data=None + self, + url: str, + method: str = None, + params: dict = None, + data=None, ): """ Call API endpoint and returns raw response. @@ -198,7 +209,10 @@ def call_api_raw( method = method or "GET" try: response = self.get_raw_request( - method=method, url=url, params=params, data=data + method=method, + url=url, + params=params, + data=data, ) except requests.exceptions.ConnectionError as er: @@ -208,13 +222,18 @@ def call_api_raw( if response.status_code >= 500: raise GitForgeInternalError( f"Pagure API returned {response.status_code} status for `{url}`" - f" with reason: `{response.reason}`" + f" with reason: `{response.reason}`", ) return response def get_raw_request( - self, url, method="GET", params=None, data=None, header=None + self, + url, + method="GET", + params=None, + data=None, + header=None, ) -> RequestResponse: """ Call API endpoint and wrap the response in `RequestResponse` type. @@ -307,7 +326,9 @@ def change_token(self, token: str): self.header = {"Authorization": "token " + self._token} def __handle_project_create_fail( - self, exception: PagureAPIException, namespace: str + self, + exception: PagureAPIException, + namespace: str, ) -> None: if ( exception.pagure_response @@ -322,7 +343,7 @@ def __handle_project_create_fail( raise OgrException(f"Namespace doesn't exist ({namespace}).") from ex raise OgrException( - "Cannot create project in given namespace (permissions)." + "Cannot create project in given namespace (permissions).", ) raise exception diff --git a/ogr/services/pagure/user.py b/ogr/services/pagure/user.py index 8351f5c7..beb049c9 100644 --- a/ogr/services/pagure/user.py +++ b/ogr/services/pagure/user.py @@ -54,5 +54,5 @@ def get_forks(self) -> List["PagureProject"]: def get_email(self) -> str: # Not supported by Pagure raise OperationNotSupported( - "Pagure does not support retrieving of user's email address" + "Pagure does not support retrieving of user's email address", ) diff --git a/ogr/utils.py b/ogr/utils.py index f3598b31..0e2959c6 100644 --- a/ogr/utils.py +++ b/ogr/utils.py @@ -49,13 +49,14 @@ def filter_comments( lambda comment: (not pattern or bool(pattern.search(comment.body))) and (not author or comment.author == author), comments, - ) + ), ) return comments def search_in_comments( - comments: List[Union[str, Comment]], filter_regex: str + comments: List[Union[str, Comment]], + filter_regex: str, ) -> Optional[Match[str]]: """ Find match in pull request description or comments. diff --git a/pyproject.toml b/pyproject.toml index c0e06d1e..911d797c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -70,7 +70,7 @@ raw-options.version_scheme = "no-guess-dev" select = [ "B", # flake8-bugbear "C4", # flake8-comprehensions - # "COM", # flake8-commas + "COM", # flake8-commas # "E", # pycodestyle Error # "F", # Pyflakes # "I", # isort diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index b4339962..a9275dc3 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -9,5 +9,6 @@ def skipif_not_all_env_vars_set(env_vars_list): requirements_met = all(getenv(item) for item in env_vars_list) return pytest.mark.skipif( - not requirements_met, reason=f"you have to have set env vars: {env_vars_list}" + not requirements_met, + reason=f"you have to have set env vars: {env_vars_list}", ) diff --git a/tests/integration/factory/test_factory.py b/tests/integration/factory/test_factory.py index d529376e..d5538150 100644 --- a/tests/integration/factory/test_factory.py +++ b/tests/integration/factory/test_factory.py @@ -29,7 +29,7 @@ def setUp(self): ): raise OSError( "You are in requre write mode, please set GITHUB_TOKEN PAGURE_TOKEN" - " GITLAB_TOKEN env variables" + " GITLAB_TOKEN env variables", ) @property @@ -48,7 +48,8 @@ def pagure_service(self): def gitlab_service(self): if not self._gitlab_service: self._gitlab_service = GitlabService( - token=self.gitlab_token, instance_url="https://gitlab.com" + token=self.gitlab_token, + instance_url="https://gitlab.com", ) return self._gitlab_service diff --git a/tests/integration/github/base.py b/tests/integration/github/base.py index 323f4947..15d20ac4 100644 --- a/tests/integration/github/base.py +++ b/tests/integration/github/base.py @@ -16,7 +16,7 @@ def setUp(self): self.token = os.environ.get("GITHUB_TOKEN") if not Path(get_datafile_filename(obj=self)).exists() and not self.token: raise OSError( - "You are in Requre write mode, please set proper GITHUB_TOKEN env variables" + "You are in Requre write mode, please set proper GITHUB_TOKEN env variables", ) self._service = None self._ogr_project = None @@ -40,7 +40,9 @@ def ogr_project(self): def ogr_fork(self): if not self._ogr_fork: self._ogr_fork = self.service.get_project( - namespace="packit", repo="ogr", is_fork=True + namespace="packit", + repo="ogr", + is_fork=True, ) return self._ogr_fork @@ -48,7 +50,8 @@ def ogr_fork(self): def hello_world_project(self): if not self._hello_world_project: self._hello_world_project = self.service.get_project( - namespace="packit", repo="hello-world" + namespace="packit", + repo="hello-world", ) return self._hello_world_project @@ -56,6 +59,7 @@ def hello_world_project(self): def not_forked_project(self): if not self._not_forked_project: self._not_forked_project = self.service.get_project( - namespace="fedora-modularity", repo="fed-to-brew" + namespace="fedora-modularity", + repo="fed-to-brew", ) return self._not_forked_project diff --git a/tests/integration/github/base_app.py b/tests/integration/github/base_app.py index 8296e52b..20d5f48d 100644 --- a/tests/integration/github/base_app.py +++ b/tests/integration/github/base_app.py @@ -22,14 +22,14 @@ class GithubAppTests(unittest.TestCase): "67KslR0PoxOwpzaOz7PkHBn7OH6zuN+PAiB82Lt1IocRhr3aABkCaQ5Kg8RsHxqX\n" "zVi5WO+Ku0d1oQIgQA4fHmeDWg3AovM98Vnps4fwjqgCzsO829nrgs7zYK8CIFog\n" "uIAEI5e2Sm4P285Pq3B7k1D/1t/cUtR4imzpDheQ\n" - "-----END RSA PRIVATE KEY-----" + "-----END RSA PRIVATE KEY-----", ) def setUp(self): self._service = None self._github_app_id = os.environ.get("GITHUB_APP_ID") self._github_app_private_key_path = os.environ.get( - "GITHUB_APP_PRIVATE_KEY_PATH" + "GITHUB_APP_PRIVATE_KEY_PATH", ) self._temporary_private_key_path = None @@ -40,7 +40,7 @@ def setUp(self): ): raise OSError( "You are in Requre write mode, please set " - "GITHUB_APP_ID GITHUB_APP_PRIVATE_KEY_PATH env variables" + "GITHUB_APP_ID GITHUB_APP_PRIVATE_KEY_PATH env variables", ) def tearDown(self) -> None: @@ -60,7 +60,8 @@ def service(self): def hello_world_project(self): if not self._hello_world_project: self._hello_world_project = self.service.get_project( - namespace="packit", repo="hello-world" + namespace="packit", + repo="hello-world", ) return self._hello_world_project diff --git a/tests/integration/github/test_app.py b/tests/integration/github/test_app.py index 774e87bd..4d67ccb1 100644 --- a/tests/integration/github/test_app.py +++ b/tests/integration/github/test_app.py @@ -18,7 +18,8 @@ class App(GithubAppTests): # Tests creation of the service using GitHub App credentials def test_private_key(self): service = GithubService( - github_app_id="123", github_app_private_key=self.TESTING_PRIVATE_KEY + github_app_id="123", + github_app_private_key=self.TESTING_PRIVATE_KEY, ) assert service.authentication.private_key == self.TESTING_PRIVATE_KEY @@ -26,7 +27,8 @@ def test_private_key_path(self): with tempfile.NamedTemporaryFile() as pr_key: Path(pr_key.name).write_text(self.TESTING_PRIVATE_KEY) service = GithubService( - github_app_id="123", github_app_private_key_path=pr_key.name + github_app_id="123", + github_app_private_key_path=pr_key.name, ) assert service.authentication.private_key == self.TESTING_PRIVATE_KEY @@ -52,7 +54,8 @@ def test_get_project_having_key_as_path(self): # Tests with invalid credentials def test_github_proj_no_app_creds(self): service = GithubService( - github_app_id="123", github_app_private_key=self.TESTING_PRIVATE_KEY + github_app_id="123", + github_app_private_key=self.TESTING_PRIVATE_KEY, ) project = GithubProject(repo="packit", service=service, namespace="packit") with pytest.raises(OgrException) as exc: diff --git a/tests/integration/github/test_check_run.py b/tests/integration/github/test_check_run.py index 18b40821..c2c29d33 100644 --- a/tests/integration/github/test_check_run.py +++ b/tests/integration/github/test_check_run.py @@ -24,14 +24,14 @@ def project(self) -> GithubProject: def test_non_existing_check_runs_returns_none(self): check_run = self.project.get_check_run( - commit_sha="f502aae6920d82948f2dba0b70c9260fb1e34822" + commit_sha="f502aae6920d82948f2dba0b70c9260fb1e34822", ) assert check_run is None def test_get_list(self): check_runs = self.project.get_check_runs( - "7cf6d0cbeca285ecbeb19a0067cb243783b3c768" + "7cf6d0cbeca285ecbeb19a0067cb243783b3c768", ) assert check_runs @@ -39,7 +39,7 @@ def test_get_list(self): def test_get_list_no_runs(self): check_runs = self.project.get_check_runs( - "f502aae6920d82948f2dba0b70c9260fb1e34822" + "f502aae6920d82948f2dba0b70c9260fb1e34822", ) assert check_runs == [] @@ -109,7 +109,12 @@ def test_create_with_completed_at_without_conclusion(self): name="should fail", commit_sha="7cf6d0cbeca285ecbeb19a0067cb243783b3c768", completed_at=datetime( - year=2021, month=5, day=27, hour=11, minute=11, second=11 + year=2021, + month=5, + day=27, + hour=11, + minute=11, + second=11, ), ) @@ -120,20 +125,25 @@ def test_create_completed_without_conclusion(self): commit_sha="7cf6d0cbeca285ecbeb19a0067cb243783b3c768", status=GithubCheckRunStatus.completed, completed_at=datetime( - year=2021, month=5, day=27, hour=11, minute=11, second=11 + year=2021, + month=5, + day=27, + hour=11, + minute=11, + second=11, ), ) # these tests need to have at least one check run on given commit def test_get_latest_check_run(self): check_run = self.project.get_check_run( - commit_sha="7cf6d0cbeca285ecbeb19a0067cb243783b3c768" + commit_sha="7cf6d0cbeca285ecbeb19a0067cb243783b3c768", ) assert check_run def test_change_name(self): check_run = self.project.get_check_run( - commit_sha="7cf6d0cbeca285ecbeb19a0067cb243783b3c768" + commit_sha="7cf6d0cbeca285ecbeb19a0067cb243783b3c768", ) assert check_run, "No check run exists" @@ -142,7 +152,7 @@ def test_change_name(self): def test_change_url(self): check_run = self.project.get_check_run( - commit_sha="7cf6d0cbeca285ecbeb19a0067cb243783b3c768" + commit_sha="7cf6d0cbeca285ecbeb19a0067cb243783b3c768", ) assert check_run, "No check run exists" diff --git a/tests/integration/github/test_comments.py b/tests/integration/github/test_comments.py index e3abfa98..d36e0cb5 100644 --- a/tests/integration/github/test_comments.py +++ b/tests/integration/github/test_comments.py @@ -31,7 +31,7 @@ def test_pr_comments_filter(self): assert pr_comments[0].body.startswith("@TomasTomecek") pr_comments = self.ogr_project.get_pr(9).get_comments( - filter_regex="LGTM, nicely ([a-z]*)" + filter_regex="LGTM, nicely ([a-z]*)", ) assert pr_comments assert len(pr_comments) == 1 @@ -43,7 +43,7 @@ def test_pr_comments_search(self): assert comment_match[0] == "LGTM" comment_match = self.ogr_project.get_pr(9).search( - filter_regex="LGTM, nicely ([a-z]*)" + filter_regex="LGTM, nicely ([a-z]*)", ) assert comment_match assert comment_match[0] == "LGTM, nicely done" @@ -60,21 +60,23 @@ def test_issue_comments_reversed(self): def test_issue_comments_regex(self): comments = self.ogr_project.get_issue(194).get_comments( - filter_regex=r".*Fedora package.*" + filter_regex=r".*Fedora package.*", ) assert len(comments) == 3 assert "master" in comments[0].body def test_issue_comments_regex_reversed(self): comments = self.ogr_project.get_issue(194).get_comments( - reverse=True, filter_regex=".*Fedora package.*" + reverse=True, + filter_regex=".*Fedora package.*", ) assert len(comments) == 3 assert "f29" in comments[0].body def test_pr_comments_author_regex(self): comments = self.ogr_project.get_pr(217).get_comments( - filter_regex="^I", author="mfocko" + filter_regex="^I", + author="mfocko", ) assert len(comments) == 1 assert "API" in comments[0].body @@ -86,7 +88,8 @@ def test_pr_comments_author(self): def test_issue_comments_author_regex(self): comments = self.ogr_project.get_issue(220).get_comments( - filter_regex=".*API.*", author="lachmanfrantisek" + filter_regex=".*API.*", + author="lachmanfrantisek", ) assert len(comments) == 1 assert comments[0].body.startswith("After") @@ -99,7 +102,7 @@ def test_issue_comments_author(self): def test_issue_comments_updates(self): comments = self.hello_world_project.get_issue(61).get_comments( - filter_regex="comment-update" + filter_regex="comment-update", ) assert len(comments) == 1 before_comment = comments[0].body @@ -114,7 +117,7 @@ def test_issue_comments_updates(self): def test_pr_comments_updates(self): comments = self.hello_world_project.get_pr(72).get_comments( - filter_regex="comment updates" + filter_regex="comment updates", ) assert len(comments) == 1 before_comment = comments[0].body @@ -139,7 +142,8 @@ def test_pr_react_to_comment_and_delete(self): def test_issue_react_to_comment_and_delete(self): issue = self.service.get_project( - repo="playground", namespace="nikromen" + repo="playground", + namespace="nikromen", ).get_issue(5) issue_comment = issue.comment(datetime.now().strftime("%m/%d/%Y")) @@ -159,7 +163,8 @@ def test_get_reactions(self): assert len(pr_comment.get_reactions()) == 3 issue = self.service.get_project( - repo="playground", namespace="nikromen" + repo="playground", + namespace="nikromen", ).get_issue(5) issue_comment = issue.comment(datetime.now().strftime("%m/%d/%Y")) diff --git a/tests/integration/github/test_forks.py b/tests/integration/github/test_forks.py index ef5c73f2..c8dee776 100644 --- a/tests/integration/github/test_forks.py +++ b/tests/integration/github/test_forks.py @@ -16,7 +16,8 @@ def test_fork(self): def test_nonexisting_fork(self): self.ogr_nonexisting_fork = self.service.get_project( - repo="omfeprkfmwpefmwpefkmwpeofjwepof", is_fork=True + repo="omfeprkfmwpefmwpefkmwpeofjwepof", + is_fork=True, ) with self.assertRaises(GithubAPIException) as ex: self.ogr_nonexisting_fork.get_description() @@ -71,7 +72,8 @@ def test_create_fork_with_namespace(self): """ namespace = f"ogr-tests-{self.service.user.get_username()}" expected_fork = self.service.get_project( - namespace=namespace, repo=self.hello_world_project + namespace=namespace, + repo=self.hello_world_project, ) assert not expected_fork.exists(), "Fork should not exist before regenerating" diff --git a/tests/integration/github/test_generic_commands.py b/tests/integration/github/test_generic_commands.py index 2817126a..e1cf4d0f 100644 --- a/tests/integration/github/test_generic_commands.py +++ b/tests/integration/github/test_generic_commands.py @@ -19,7 +19,8 @@ def test_add_user(self): `lachmanfrantisek` is not added in the project before running tests """ project = self.service.get_project( - repo="playground", namespace=self.service.user.get_username() + repo="playground", + namespace=self.service.user.get_username(), ) assert not project.can_merge_pr("lachmanfrantisek") @@ -96,7 +97,7 @@ def test_parent_project(self): def test_commit_flags(self): flags = self.ogr_project.get_commit_statuses( - commit="29ca3caefc781b4b41245df3e01086ffa4b4639e" + commit="29ca3caefc781b4b41245df3e01086ffa4b4639e", ) assert isinstance(flags, list) assert len(flags) == 0 @@ -191,10 +192,20 @@ def test_get_commit_statuses(self): assert last_flag.context == "test" assert last_flag.uid assert last_flag.created.replace(tzinfo=None) == datetime( - year=2019, month=9, day=19, hour=12, minute=21, second=6 + year=2019, + month=9, + day=19, + hour=12, + minute=21, + second=6, ) assert last_flag.edited.replace(tzinfo=None) == datetime( - year=2019, month=9, day=19, hour=12, minute=21, second=6 + year=2019, + month=9, + day=19, + hour=12, + minute=21, + second=6, ) def test_set_commit_status_long_description(self): @@ -236,7 +247,7 @@ def test_commit_comment(self): def test_get_commit_comments(self): comments = self.hello_world_project.get_commit_comments( - "95069d7bedb6ae02def3fccce22169b412d08eac" + "95069d7bedb6ae02def3fccce22169b412d08eac", ) assert len(comments) assert comments[0].sha == "95069d7bedb6ae02def3fccce22169b412d08eac" @@ -254,7 +265,8 @@ def test_project_exists(self): def test_project_not_exists(self): assert not self.service.get_project( - repo="some-non-existing-repo", namespace="some-none-existing-namespace" + repo="some-non-existing-repo", + namespace="some-none-existing-namespace", ).exists() def test_is_private(self): @@ -262,7 +274,8 @@ def test_is_private(self): # accessed by the user who's GITHUB_TOKEN is used for # test regeneration. private_project = self.service.get_project( - namespace=self.service.user.get_username(), repo="playground" + namespace=self.service.user.get_username(), + repo="playground", ) assert private_project.is_private() @@ -271,7 +284,8 @@ def test_is_not_private(self): def test_delete(self): project = self.service.get_project( - repo="delete-project", namespace="shreyaspapi" + repo="delete-project", + namespace="shreyaspapi", ) project.delete() diff --git a/tests/integration/github/test_issues.py b/tests/integration/github/test_issues.py index 9eaf3417..244bf7fc 100644 --- a/tests/integration/github/test_issues.py +++ b/tests/integration/github/test_issues.py @@ -37,7 +37,9 @@ def test_issue_list(self): def test_create_issue(self): labels = ["label1", "label2"] issue = self.hello_world_project.create_issue( - title=self.title, body=self.description, labels=labels + title=self.title, + body=self.description, + labels=labels, ) assert issue.title == self.title assert issue.description == self.description @@ -47,14 +49,19 @@ def test_create_issue(self): def test_create_private_issue(self): with self.assertRaises(OperationNotSupported): self.hello_world_project.create_issue( - title=self.title, body=self.description, private=True + title=self.title, + body=self.description, + private=True, ) def test_create_issue_with_assignee(self): labels = ["label1", "label2"] assignee = ["lachmanfrantisek"] issue = self.hello_world_project.create_issue( - title=self.title, body=self.description, labels=labels, assignees=assignee + title=self.title, + body=self.description, + labels=labels, + assignees=assignee, ) assert issue.title == self.title assert issue.description == self.description @@ -70,27 +77,31 @@ def test_issue_without_label(self): def test_issue_list_author(self): issue_list = self.ogr_project.get_issue_list( - status=IssueStatus.all, author="mfocko" + status=IssueStatus.all, + author="mfocko", ) assert issue_list assert len(issue_list) >= 12 def test_issue_list_nonexisting_author(self): issue_list = self.ogr_project.get_issue_list( - status=IssueStatus.all, author="xyzidontexist" + status=IssueStatus.all, + author="xyzidontexist", ) assert len(issue_list) == 0 def test_issue_list_assignee(self): issue_list = self.ogr_project.get_issue_list( - status=IssueStatus.all, assignee="mfocko" + status=IssueStatus.all, + assignee="mfocko", ) assert issue_list assert len(issue_list) >= 10 def test_issue_list_labels(self): issue_list = self.ogr_project.get_issue_list( - status=IssueStatus.all, labels=["Pagure"] + status=IssueStatus.all, + labels=["Pagure"], ) assert issue_list assert len(issue_list) >= 42 @@ -195,5 +206,6 @@ def test_get_comment(self): def test_create_with_disabled_issues(self): with self.assertRaises(IssueTrackerDisabled): self.hello_world_project.get_fork().create_issue( - "Testing issue", "shouldn't be created" + "Testing issue", + "shouldn't be created", ) diff --git a/tests/integration/github/test_pull_requests.py b/tests/integration/github/test_pull_requests.py index 7a20f28c..17022ab7 100644 --- a/tests/integration/github/test_pull_requests.py +++ b/tests/integration/github/test_pull_requests.py @@ -156,7 +156,8 @@ def test_pr_create_fork_other_fork(self): """ fork_project = self.service.get_project(namespace="mfocko", repo="hello-world") other_fork_project = self.service.get_project( - namespace="lachmanfrantisek", repo="hello-world" + namespace="lachmanfrantisek", + repo="hello-world", ) pr_opened_before = len(other_fork_project.get_pr_list(status=PRStatus.open)) opened_pr = fork_project.create_pr( @@ -319,7 +320,8 @@ def test_source_project_fork_fork(self): def test_source_project_other_fork_fork(self): # Tests source project for PR from one fork to another fork project = self.service.get_project( - repo="hello-world", namespace="lachmanfrantisek" + repo="hello-world", + namespace="lachmanfrantisek", ) pr = project.get_pr(1) source_project = pr.source_project @@ -347,7 +349,8 @@ def test_source_project_renamed_upstream(self): 3. Rename the repo in packit namespace. """ pr = self.service.get_project( - repo="testing_repo_changed_name", namespace="packit" + repo="testing_repo_changed_name", + namespace="packit", ).get_pr(1) source_project = pr.source_project assert source_project.namespace == self.service.user.get_username() diff --git a/tests/integration/github/test_readonly.py b/tests/integration/github/test_readonly.py index 6c732e4f..7e2bad15 100644 --- a/tests/integration/github/test_readonly.py +++ b/tests/integration/github/test_readonly.py @@ -16,7 +16,7 @@ def setUp(self): self.token = os.environ.get("GITHUB_TOKEN") if not Path(get_datafile_filename(obj=self)).exists() and not self.token: raise OSError( - "You are in Requre write mode, please set proper GITHUB_TOKEN env variables" + "You are in Requre write mode, please set proper GITHUB_TOKEN env variables", ) self._service = None self._ogr_project = None @@ -43,7 +43,10 @@ def test_pr_comments(self): def test_create_pr(self): pr = self.ogr_project.create_pr( - "title", "text", "master", "lbarcziova:testing_branch" + "title", + "text", + "master", + "lbarcziova:testing_branch", ) assert pr.title == "title" diff --git a/tests/integration/github/test_releases.py b/tests/integration/github/test_releases.py index af9c86fe..4fca491e 100644 --- a/tests/integration/github/test_releases.py +++ b/tests/integration/github/test_releases.py @@ -31,10 +31,12 @@ def test_create_release(self): [ latest_release.rsplit(".", 1)[0], str(int(latest_release.rsplit(".", 1)[1]) + 1), - ] + ], ) release = self.hello_world_project.create_release( - tag=increased_release, name="test", message="testing release" + tag=increased_release, + name="test", + message="testing release", ) count_after = len(self.hello_world_project.get_releases()) assert release.tag_name == increased_release @@ -48,7 +50,8 @@ def test_edit_release(self): origin_message = release.body release.edit_release( - name=f"{origin_name}-changed", message=f"{origin_message}-changed" + name=f"{origin_name}-changed", + message=f"{origin_message}-changed", ) assert release.title == f"{origin_name}-changed" assert release.body == f"{origin_message}-changed" diff --git a/tests/integration/github/test_service.py b/tests/integration/github/test_service.py index 24b4ddd8..5b032887 100644 --- a/tests/integration/github/test_service.py +++ b/tests/integration/github/test_service.py @@ -19,7 +19,8 @@ def test_project_create(self): """ name_of_the_repo = "repo_created_for_test" project = self.service.get_project( - repo=name_of_the_repo, namespace=self.service.user.get_username() + repo=name_of_the_repo, + namespace=self.service.user.get_username(), ) with self.assertRaises(GithubException): _ = project.github_repo @@ -29,7 +30,8 @@ def test_project_create(self): assert new_project.github_repo project = self.service.get_project( - repo=name_of_the_repo, namespace=self.service.user.get_username() + repo=name_of_the_repo, + namespace=self.service.user.get_username(), ) assert project.github_repo @@ -42,7 +44,8 @@ def test_project_create_with_description(self): description = "The description of the newly created project." project = self.service.get_project( - repo=name_of_the_repo, namespace=self.service.user.get_username() + repo=name_of_the_repo, + namespace=self.service.user.get_username(), ) with self.assertRaises(GithubException): _ = project.github_repo @@ -56,7 +59,8 @@ def test_project_create_with_description(self): assert new_project.get_description() == description project = self.service.get_project( - repo=name_of_the_repo, namespace=self.service.user.get_username() + repo=name_of_the_repo, + namespace=self.service.user.get_username(), ) assert project.github_repo assert project.get_description() == description @@ -69,20 +73,23 @@ def test_project_create_in_the_group(self): name_of_the_repo = "repo_created_for_test_in_group" namespace_of_the_repo = "packit" project = self.service.get_project( - repo=name_of_the_repo, namespace=namespace_of_the_repo + repo=name_of_the_repo, + namespace=namespace_of_the_repo, ) with self.assertRaises(UnknownObjectException): _ = project.github_repo new_project = self.service.project_create( - repo=name_of_the_repo, namespace=namespace_of_the_repo + repo=name_of_the_repo, + namespace=namespace_of_the_repo, ) assert new_project.repo == name_of_the_repo assert new_project.namespace == namespace_of_the_repo assert new_project.github_repo project = self.service.get_project( - repo=name_of_the_repo, namespace=namespace_of_the_repo + repo=name_of_the_repo, + namespace=namespace_of_the_repo, ) assert project.github_repo @@ -93,7 +100,8 @@ def test_project_create_duplicate(self): """ name_of_the_repo = "repo_created_for_test_fail" project = self.service.get_project( - repo=name_of_the_repo, namespace=self.service.user.get_username() + repo=name_of_the_repo, + namespace=self.service.user.get_username(), ) with self.assertRaises(GithubException): _ = project.github_repo diff --git a/tests/integration/gitlab/base.py b/tests/integration/gitlab/base.py index 63a09c73..a9f1b52d 100644 --- a/tests/integration/gitlab/base.py +++ b/tests/integration/gitlab/base.py @@ -17,7 +17,7 @@ def setUp(self): if not Path(get_datafile_filename(obj=self)).exists() and not self.token: raise OSError( - "You are in Requre write mode, please set GITLAB_TOKEN env variables" + "You are in Requre write mode, please set GITLAB_TOKEN env variables", ) elif not self.token: self.token = "some_token" @@ -28,7 +28,9 @@ def setUp(self): def service(self): if not self._service: self._service = GitlabService( - token=self.token, instance_url="https://gitlab.com", ssl_verify=True + token=self.token, + instance_url="https://gitlab.com", + ssl_verify=True, ) return self._service @@ -36,6 +38,7 @@ def service(self): def project(self): if not self._project: self._project = self.service.get_project( - repo="ogr-tests", namespace="packit-service" + repo="ogr-tests", + namespace="packit-service", ) return self._project diff --git a/tests/integration/gitlab/test_comments.py b/tests/integration/gitlab/test_comments.py index c77fd2b1..527cdbc5 100644 --- a/tests/integration/gitlab/test_comments.py +++ b/tests/integration/gitlab/test_comments.py @@ -19,7 +19,8 @@ def test_pr_react_to_comment_and_delete(self): def test_issue_react_to_comment_and_delete(self): issue = self.service.get_project( - repo="playground", namespace="nikromen" + repo="playground", + namespace="nikromen", ).get_issue(2) issue_comment = issue.comment(datetime.now().strftime("%m/%d/%Y")) @@ -39,7 +40,8 @@ def test_get_reactions(self): assert len(pr_comment.get_reactions()) == 3 issue = self.service.get_project( - repo="playground", namespace="nikromen" + repo="playground", + namespace="nikromen", ).get_issue(2) issue_comment = issue.comment(datetime.now().strftime("%m/%d/%Y")) diff --git a/tests/integration/gitlab/test_forks.py b/tests/integration/gitlab/test_forks.py index 9f9254ab..890bbaed 100644 --- a/tests/integration/gitlab/test_forks.py +++ b/tests/integration/gitlab/test_forks.py @@ -45,7 +45,8 @@ def test_create_fork_with_namespace(self): """ namespace = f"ogr-tests-{self.service.user.get_username()}" expected_fork = self.service.get_project( - namespace=namespace, repo=self.project.repo + namespace=namespace, + repo=self.project.repo, ) assert not expected_fork.exists(), "Fork should not exist before regenerating" diff --git a/tests/integration/gitlab/test_generic_commands.py b/tests/integration/gitlab/test_generic_commands.py index 6ff90068..f24aadbd 100644 --- a/tests/integration/gitlab/test_generic_commands.py +++ b/tests/integration/gitlab/test_generic_commands.py @@ -15,7 +15,8 @@ class GenericCommands(GitlabTests): def test_get_file_content(self): file = self.project.get_file_content( - path="README.md", ref="b8e18207cfdad954f1b3a96db34d0706b272e6cf" + path="README.md", + ref="b8e18207cfdad954f1b3a96db34d0706b272e6cf", ) assert ( file == "# ogr-tests\n\nTesting repository for python-ogr package. | " @@ -24,7 +25,8 @@ def test_get_file_content(self): def test_request_access(self): project = self.service.get_project( - repo="hello-world", namespace="shreyaspapitest" + repo="hello-world", + namespace="shreyaspapitest", ) project.request_access() @@ -140,7 +142,7 @@ def test_parent_project(self): def test_get_commit_statuses(self): flags = self.project.get_commit_statuses( - commit="11b37d913374b14f8519d16c2a2cca3ebc14ac64" + commit="11b37d913374b14f8519d16c2a2cca3ebc14ac64", ) assert isinstance(flags, list) assert len(flags) >= 2 @@ -159,7 +161,7 @@ def test_get_commit_statuses(self): def test_set_commit_status(self): old_statuses = self.project.get_commit_statuses( - commit="11b37d913374b14f8519d16c2a2cca3ebc14ac64" + commit="11b37d913374b14f8519d16c2a2cca3ebc14ac64", ) status = self.project.set_commit_status( commit="11b37d913374b14f8519d16c2a2cca3ebc14ac64", @@ -170,7 +172,7 @@ def test_set_commit_status(self): ) assert status new_statuses = self.project.get_commit_statuses( - commit="11b37d913374b14f8519d16c2a2cca3ebc14ac64" + commit="11b37d913374b14f8519d16c2a2cca3ebc14ac64", ) assert len(old_statuses) == len(new_statuses) @@ -186,7 +188,7 @@ def test_commit_comment(self): def test_get_commit_comments(self): comments = self.project.get_commit_comments( - "11b37d913374b14f8519d16c2a2cca3ebc14ac64" + "11b37d913374b14f8519d16c2a2cca3ebc14ac64", ) assert len(comments) assert comments[0].sha == "11b37d913374b14f8519d16c2a2cca3ebc14ac64" @@ -204,7 +206,8 @@ def test_project_exists(self): def test_project_not_exists(self): assert not self.service.get_project( - repo="some-non-existing-repo", namespace="some-none-existing-namespace" + repo="some-non-existing-repo", + namespace="some-none-existing-namespace", ).exists() def test_get_owners(self): @@ -238,14 +241,16 @@ def test_is_not_private(self): def test_delete(self): project = self.service.get_project( - repo="delete-project", namespace="shreyaspapi" + repo="delete-project", + namespace="shreyaspapi", ) project.delete() def test_has_issues(self): assert self.project.has_issues assert not self.service.get_project( - namespace="redhat/centos-stream/rpms", repo="firefox" + namespace="redhat/centos-stream/rpms", + repo="firefox", ).has_issues def test_get_contributors(self): diff --git a/tests/integration/gitlab/test_issues.py b/tests/integration/gitlab/test_issues.py index 4775d431..454f8cea 100644 --- a/tests/integration/gitlab/test_issues.py +++ b/tests/integration/gitlab/test_issues.py @@ -24,20 +24,23 @@ def test_get_issue_list(self): def test_get_issue_list_author(self): issue_list = self.project.get_issue_list( - status=IssueStatus.all, author="mfocko" + status=IssueStatus.all, + author="mfocko", ) assert issue_list assert len(issue_list) >= 5 def test_get_issue_list_nonexisting_author(self): issue_list = self.project.get_issue_list( - status=IssueStatus.all, author="xyzidontexist" + status=IssueStatus.all, + author="xyzidontexist", ) assert len(issue_list) == 0 def test_get_issue_list_assignee(self): issue_list = self.project.get_issue_list( - status=IssueStatus.all, assignee="mfocko" + status=IssueStatus.all, + assignee="mfocko", ) assert issue_list assert len(issue_list) >= 3 @@ -56,7 +59,9 @@ def test_create_issue(self): issue_title = f"New Issue {self.random_str}" issue_desc = f"Description for issue {self.random_str}" issue = self.project.create_issue( - title=issue_title, body=issue_desc, labels=labels + title=issue_title, + body=issue_desc, + labels=labels, ) assert issue.title == issue_title @@ -74,7 +79,9 @@ def test_create_issue_with_assignee(self): assign = ["mfocko"] project = self.service.get_project(repo="ogr-tests", namespace="packit-service") issue = project.create_issue( - title=issue_title, body=issue_desc, assignees=assign + title=issue_title, + body=issue_desc, + assignees=assign, ) assert issue.title == issue_title @@ -88,7 +95,9 @@ def test_create_private_issue(self): issue_title = f"New Confidential Issue {self.random_str}" issue_desc = f"Description for issue {self.random_str}" issue = self.project.create_issue( - title=issue_title, body=issue_desc, private=True + title=issue_title, + body=issue_desc, + private=True, ) assert issue.title == issue_title assert issue.description == issue_desc @@ -126,7 +135,8 @@ def test_get_issue_comments_regex(self): def test_get_issue_comments_regex_reversed(self): comments = self.project.get_issue(2).get_comments( - filter_regex="regex", reverse=True + filter_regex="regex", + reverse=True, ) assert len(comments) == 2 assert comments[0].body.startswith("regex") @@ -164,14 +174,16 @@ def test_issue_assignees(self): def test_issue_list_labels(self): issue_list = self.project.get_issue_list( - status=IssueStatus.all, labels=["testing-label-for-test-issue-list-labels"] + status=IssueStatus.all, + labels=["testing-label-for-test-issue-list-labels"], ) assert issue_list assert len(issue_list) == 33 def test_get_issue_comments_author_regex(self): comments = self.project.get_issue(2).get_comments( - filter_regex="2$", author="lbarcziova" + filter_regex="2$", + author="lbarcziova", ) assert len(comments) == 1 assert comments[0].body.startswith("Comment") @@ -227,7 +239,8 @@ def test_get_comment(self): def test_create_with_disabled_issues(self): project = self.service.get_project( - namespace="packit-service", repo="private-testing-repo" + namespace="packit-service", + repo="private-testing-repo", ) with self.assertRaises(IssueTrackerDisabled): project.create_issue("Testing issue", "shouldn't be created") diff --git a/tests/integration/gitlab/test_pull_requests.py b/tests/integration/gitlab/test_pull_requests.py index 257c5074..4b08083a 100644 --- a/tests/integration/gitlab/test_pull_requests.py +++ b/tests/integration/gitlab/test_pull_requests.py @@ -60,7 +60,11 @@ def test_update_pr_info(self): assert pr_info.description == original_description def create_pull_request( - self, title="New PR of pr-3", body="Description", dest="master", source="pr-3" + self, + title="New PR of pr-3", + body="Description", + dest="master", + source="pr-3", ): return self.project.create_pr(title, body, dest, source) @@ -105,7 +109,8 @@ def test_pr_labels(self): def test_get_pr_comments_author_regex(self): comments = self.project.get_pr(1).get_comments( - filter_regex="test$", author="mfocko" + filter_regex="test$", + author="mfocko", ) assert len(comments) == 1 assert comments[0].body.startswith("author") @@ -196,7 +201,7 @@ def test_test_merge_commit_sha(self): assert open_mergeable.merge_commit_sha # cannot provide specific value except AttributeError: self.skipTest( - "installed version of python-gitlab does not support merge_ref" + "installed version of python-gitlab does not support merge_ref", ) # open PR with conflicts @@ -237,7 +242,8 @@ def test_source_project_fork_fork(self): Use PR id of a merge request from your fork to the fork itself. """ project = self.service.get_project( - repo="ogr-tests", namespace=self.service.user.get_username() + repo="ogr-tests", + namespace=self.service.user.get_username(), ) pr = project.get_pr(1) source_project = pr.source_project @@ -250,7 +256,8 @@ def test_source_project_other_fork_fork(self): the other fork if necessary. """ project = self.service.get_project( - repo="ogr-tests", namespace="lachmanfrantisek" + repo="ogr-tests", + namespace="lachmanfrantisek", ) pr = project.get_pr(5) source_project = pr.source_project @@ -270,7 +277,8 @@ def test_source_project_renamed_upstream(self): 3. Rename upstream """ pr = self.service.get_project( - repo="old-ogr-tests", namespace="packit-service" + repo="old-ogr-tests", + namespace="packit-service", ).get_pr(54) source_project = pr.source_project assert source_project.namespace == self.service.user.get_username() diff --git a/tests/integration/gitlab/test_service.py b/tests/integration/gitlab/test_service.py index 1062bcae..987cdff6 100644 --- a/tests/integration/gitlab/test_service.py +++ b/tests/integration/gitlab/test_service.py @@ -20,7 +20,8 @@ def test_project_create(self): """ name_of_the_repo = "new-ogr-testing-repo" project = self.service.get_project( - repo=name_of_the_repo, namespace=self.service.user.get_username() + repo=name_of_the_repo, + namespace=self.service.user.get_username(), ) with pytest.raises(GitlabGetError): assert project.gitlab_repo @@ -30,7 +31,8 @@ def test_project_create(self): assert new_project.gitlab_repo project = self.service.get_project( - repo=name_of_the_repo, namespace=self.service.user.get_username() + repo=name_of_the_repo, + namespace=self.service.user.get_username(), ) assert project.gitlab_repo @@ -58,7 +60,8 @@ def test_project_create_with_description(self): assert new_project.get_description() == description project = self.service.get_project( - repo=name_of_the_repo, namespace=self.service.user.get_username() + repo=name_of_the_repo, + namespace=self.service.user.get_username(), ) assert project.gitlab_repo assert project.get_description() == description @@ -71,20 +74,23 @@ def test_project_create_in_the_group(self): name_of_the_repo = "new-ogr-testing-repo-in-the-group" namespace_of_the_repo = "packit-service" project = self.service.get_project( - repo=name_of_the_repo, namespace=namespace_of_the_repo + repo=name_of_the_repo, + namespace=namespace_of_the_repo, ) with pytest.raises(GitlabGetError): assert project.gitlab_repo new_project = self.service.project_create( - repo=name_of_the_repo, namespace=namespace_of_the_repo + repo=name_of_the_repo, + namespace=namespace_of_the_repo, ) assert new_project.repo == name_of_the_repo assert new_project.namespace == namespace_of_the_repo assert new_project.gitlab_repo project = self.service.get_project( - repo=name_of_the_repo, namespace=namespace_of_the_repo + repo=name_of_the_repo, + namespace=namespace_of_the_repo, ) assert project.gitlab_repo @@ -94,7 +100,8 @@ def test_project_create_duplicate(self): """ name_of_the_repo = "new-ogr-testing-repo-fail" project = self.service.get_project( - repo=name_of_the_repo, namespace=self.service.user.get_username() + repo=name_of_the_repo, + namespace=self.service.user.get_username(), ) with pytest.raises(GitlabGetError): assert project.gitlab_repo @@ -119,7 +126,8 @@ def test_list_projects_with_namespace_input_and_language_input(self): language = "C++" number_of_projects = 2 projects = self.service.list_projects( - namespace=name_of_the_repo, language=language + namespace=name_of_the_repo, + language=language, ) assert len(projects) == number_of_projects diff --git a/tests/integration/pagure/base.py b/tests/integration/pagure/base.py index fa78614f..7ea1dadd 100644 --- a/tests/integration/pagure/base.py +++ b/tests/integration/pagure/base.py @@ -16,7 +16,7 @@ def setUp(self): if not get_datafile_filename(obj=self) and (not self.token): raise OSError( - "You are in Requre write mode, please set PAGURE_TOKEN env variables" + "You are in Requre write mode, please set PAGURE_TOKEN env variables", ) self._service = None self._user = None @@ -27,7 +27,8 @@ def setUp(self): def service(self): if not self._service: self._service = PagureService( - token=self.token, instance_url="https://pagure.io" + token=self.token, + instance_url="https://pagure.io", ) return self._service @@ -41,7 +42,8 @@ def user(self): def ogr_project(self): if not self._ogr_project: self._ogr_project = self.service.get_project( - namespace=None, repo="ogr-tests" + namespace=None, + repo="ogr-tests", ) return self._ogr_project @@ -49,6 +51,9 @@ def ogr_project(self): def ogr_fork(self): if not self._ogr_fork: self._ogr_fork = self.service.get_project( - namespace=None, repo="ogr-tests", username=self.user, is_fork=True + namespace=None, + repo="ogr-tests", + username=self.user, + is_fork=True, ) return self._ogr_fork diff --git a/tests/integration/pagure/test_comments.py b/tests/integration/pagure/test_comments.py index 24d68e77..21eaf4dd 100644 --- a/tests/integration/pagure/test_comments.py +++ b/tests/integration/pagure/test_comments.py @@ -28,7 +28,7 @@ def test_pr_comments_filter(self): assert pr_comments[0].body == "ignored comment" pr_comments = self.ogr_project.get_pr(4).get_comments( - filter_regex="PR comment [0-9]*" + filter_regex="PR comment [0-9]*", ) assert pr_comments assert len(pr_comments) == 2 @@ -41,7 +41,7 @@ def test_pr_comments_search(self): assert comment_match[0] == "New" comment_match = self.ogr_project.get_pr(4).search( - filter_regex="Pull-Request has been merged by [a-z]*" + filter_regex="Pull-Request has been merged by [a-z]*", ) print(comment_match) assert comment_match diff --git a/tests/integration/pagure/test_generic_commands.py b/tests/integration/pagure/test_generic_commands.py index 762a0c6b..339d5d9e 100644 --- a/tests/integration/pagure/test_generic_commands.py +++ b/tests/integration/pagure/test_generic_commands.py @@ -83,7 +83,9 @@ def test_get_files(self): assert "a/b/c" not in files files = self.ogr_project.get_files( - ref="for-testing-get-files", filter_regex=".*.c", recursive=True + ref="for-testing-get-files", + filter_regex=".*.c", + recursive=True, ) assert files assert len(files) >= 3 @@ -104,7 +106,7 @@ def test_parent_project(self): def test_commit_statuses(self): flags = self.ogr_project.get_commit_statuses( - commit="d87466de81c72231906a6597758f37f28830bb71" + commit="d87466de81c72231906a6597758f37f28830bb71", ) assert isinstance(flags, list) assert len(flags) == 0 diff --git a/tests/integration/pagure/test_issues.py b/tests/integration/pagure/test_issues.py index f4330d5e..13512241 100644 --- a/tests/integration/pagure/test_issues.py +++ b/tests/integration/pagure/test_issues.py @@ -18,7 +18,8 @@ def setUp(self): def long_issues_project(self): if not self._long_issues_project: self._long_issues_project = self.service.get_project( - repo="pagure", namespace=None + repo="pagure", + namespace=None, ) return self._long_issues_project @@ -38,27 +39,31 @@ def test_issue_list_paginated(self): def test_issue_list_author(self): issue_list = self.ogr_project.get_issue_list( - status=IssueStatus.all, author="mfocko" + status=IssueStatus.all, + author="mfocko", ) assert issue_list assert len(issue_list) >= 3 def test_issue_list_nonexisting_author(self): issue_list = self.ogr_project.get_issue_list( - status=IssueStatus.all, author="xyzidontexist" + status=IssueStatus.all, + author="xyzidontexist", ) assert len(issue_list) == 0 def test_issue_list_assignee(self): issue_list = self.ogr_project.get_issue_list( - status=IssueStatus.all, assignee="mfocko" + status=IssueStatus.all, + assignee="mfocko", ) assert issue_list assert len(issue_list) == 1 def test_issue_list_labels(self): issue_list = self.ogr_project.get_issue_list( - status=IssueStatus.all, labels=["test_label"] + status=IssueStatus.all, + labels=["test_label"], ) assert issue_list assert len(issue_list) == 1 @@ -69,7 +74,10 @@ def test_create_issue(self): labels = ["label1", "label2"] project = self.service.get_project(repo="hello-112111", namespace="testing") issue = project.create_issue( - title=title, body=description, private=True, labels=labels + title=title, + body=description, + private=True, + labels=labels, ) assert issue.title == title assert issue.description == description @@ -82,7 +90,9 @@ def test_create_issue_with_assignees(self): project = self.service.get_project(repo="hello-112111", namespace="testing") assignee = ["mfocko"] issue = project.create_issue( - title=random_str, body=random_str, assignees=assignee + title=random_str, + body=random_str, + assignees=assignee, ) assert issue.title == random_str assert issue.description == random_str @@ -95,7 +105,9 @@ def test_issue_assignees(self): """ project = self.service.get_project( - repo="hello-112111", namespace="testing", is_fork=True + repo="hello-112111", + namespace="testing", + is_fork=True, ) issue = project.get_issue(4) @@ -114,7 +126,9 @@ def test_issue_without_label(self): def test_get_comment(self): project = self.service.get_project( - repo="my-playground", namespace=None, username="nikromen" + repo="my-playground", + namespace=None, + username="nikromen", ) comment = project.get_issue(1).get_comment(753462) assert comment.body == "example issue comment" @@ -122,5 +136,6 @@ def test_get_comment(self): def test_create_with_disabled_issues(self): with self.assertRaises(IssueTrackerDisabled): self.ogr_project.get_fork().create_issue( - "Testing issue", "shouldn't be created" + "Testing issue", + "shouldn't be created", ) diff --git a/tests/integration/pagure/test_project_token.py b/tests/integration/pagure/test_project_token.py index cbf063a2..8dabf126 100644 --- a/tests/integration/pagure/test_project_token.py +++ b/tests/integration/pagure/test_project_token.py @@ -32,7 +32,8 @@ def setUp(self): def service(self): if not self._service: self._service = PagureService( - token=self.token, instance_url="https://pagure.io" + token=self.token, + instance_url="https://pagure.io", ) return self._service @@ -63,14 +64,15 @@ def test_issue_comments_reversed(self): def test_issue_comments_regex(self): issue_comments = self.ogr_project.get_issue(3).get_comments( - filter_regex="regex" + filter_regex="regex", ) assert len(issue_comments) == 2 assert issue_comments[0].body.startswith("let's") def test_issue_comments_regex_reversed(self): issue_comments = self.ogr_project.get_issue(3).get_comments( - filter_regex="regex", reverse=True + filter_regex="regex", + reverse=True, ) assert len(issue_comments) == 2 assert issue_comments[0].body.startswith("regex") @@ -101,14 +103,16 @@ def test_update_pr_info(self): orig_description = pr_info.description self.ogr_project.get_pr(4).update_info( - title="changed", description="changed description" + title="changed", + description="changed description", ) pr_info = self.ogr_project.get_pr(pr_id=4) assert pr_info.title == "changed" assert pr_info.description == "changed description" self.ogr_project.get_pr(4).update_info( - title=orig_title, description=orig_description + title=orig_title, + description=orig_description, ) pr_info = self.ogr_project.get_pr(pr_id=4) assert pr_info.title == orig_title @@ -135,7 +139,8 @@ def test_pr_setters(self): def test_pr_comments_author_regex(self): comments = self.ogr_project.get_pr(4).get_comments( - filter_regex="^regex", author="mfocko" + filter_regex="^regex", + author="mfocko", ) assert len(comments) == 1 assert comments[0].body.endswith("test") @@ -146,7 +151,8 @@ def test_pr_comments_author(self): def test_issue_comments_author_regex(self): comments = self.ogr_project.get_issue(3).get_comments( - filter_regex="^test[s]?$", author="mfocko" + filter_regex="^test[s]?$", + author="mfocko", ) assert len(comments) == 2 assert comments[0].body == "test" @@ -180,7 +186,12 @@ def test_pr_status(self): second=0, ) assert statuses[-1].edited >= datetime( - year=2020, month=8, day=31, hour=1, minute=0, second=0 + year=2020, + month=8, + day=31, + hour=1, + minute=0, + second=0, ) def test_is_private(self): diff --git a/tests/integration/pagure/test_service.py b/tests/integration/pagure/test_service.py index 23d8458c..4f8e7594 100644 --- a/tests/integration/pagure/test_service.py +++ b/tests/integration/pagure/test_service.py @@ -77,7 +77,8 @@ def test_project_create_unauthorized_namespace(self): namespace = "fedora-magazine" with pytest.raises( - OgrException, match=r".*Cannot create project in given namespace.*" + OgrException, + match=r".*Cannot create project in given namespace.*", ): self.service.project_create(repo=name, namespace=namespace) project = self.service.get_project(repo=name, namespace=namespace) diff --git a/tests/unit/test_factory.py b/tests/unit/test_factory.py index be249c49..a9977dcb 100644 --- a/tests/unit/test_factory.py +++ b/tests/unit/test_factory.py @@ -103,7 +103,9 @@ def test_get_service_class_not_found(url, mapping): None, True, GithubProject( - namespace="packit-service", repo="ogr", service=GithubService() + namespace="packit-service", + repo="ogr", + service=GithubService(), ), ), ( @@ -112,7 +114,9 @@ def test_get_service_class_not_found(url, mapping): None, True, GithubProject( - namespace="packit-service", repo="ogr", service=GithubService() + namespace="packit-service", + repo="ogr", + service=GithubService(), ), ), ( @@ -121,7 +125,9 @@ def test_get_service_class_not_found(url, mapping): None, True, GithubProject( - namespace="packit-service", repo="ogr", service=GithubService() + namespace="packit-service", + repo="ogr", + service=GithubService(), ), ), ( @@ -130,7 +136,9 @@ def test_get_service_class_not_found(url, mapping): None, True, GithubProject( - namespace="packit-service", repo="ogr", service=GithubService() + namespace="packit-service", + repo="ogr", + service=GithubService(), ), ), ( @@ -139,7 +147,9 @@ def test_get_service_class_not_found(url, mapping): None, True, GithubProject( - namespace="packit-service", repo="ogr", service=GithubService() + namespace="packit-service", + repo="ogr", + service=GithubService(), ), ), ( @@ -183,7 +193,7 @@ def test_get_service_class_not_found(url, mapping): instance_url="https://host.name", hostname="host.name", get_project_from_url=lambda url: "project", - ) + ), ], True, "project", @@ -303,7 +313,7 @@ def test_get_project(url, mapping, instances, force_custom_instance, result): instance_url="https://unknown.com", hostname="unknown.com", get_project_from_url=lambda url: "project", - ) + ), ], "Instance of type", ), @@ -329,7 +339,9 @@ def test_get_project(url, mapping, instances, force_custom_instance, result): def test_get_project_not_found(url, mapping, instances, exc_str): with pytest.raises(OgrException) as ex: _ = get_project( - url=url, service_mapping_update=mapping, custom_instances=instances + url=url, + service_mapping_update=mapping, + custom_instances=instances, ) assert exc_str in str(ex.value) @@ -346,7 +358,7 @@ def test_get_project_not_found(url, mapping, instances, exc_str): "pagure": { "token": "abcd", "instance_url": "https://src.fedoraproject.org", - } + }, }, {PagureService(token="abcd", instance_url="https://src.fedoraproject.org")}, ), @@ -363,12 +375,13 @@ def test_get_project_not_found(url, mapping, instances, exc_str): "github.com": { "github_app_id": "abcd", "github_app_private_key_path": "/abc/def/ghi", - } + }, }, { GithubService( - github_app_id="abcd", github_app_private_key_path="/abc/def/ghi" - ) + github_app_id="abcd", + github_app_private_key_path="/abc/def/ghi", + ), }, ), ( @@ -412,7 +425,7 @@ def test_get_instances_from_dict(instances_in_dict, result_instances: Set): "token": "abcd", "github_app_id": "123", "tokman_instance_url": "http://localhost", - } + }, }, {GithubService(tokman_instance_url="http://localhost")}, ), @@ -421,7 +434,7 @@ def test_get_instances_from_dict(instances_in_dict, result_instances: Set): "github.com": { "github_app_id": "123", "tokman_instance_url": "http://localhost", - } + }, }, {GithubService(tokman_instance_url="http://localhost")}, ), @@ -431,12 +444,13 @@ def test_get_instances_from_dict(instances_in_dict, result_instances: Set): "type": "gitlab", "instance_url": "https://gitlab.com", "token": "my_very_secret_token", - } + }, }, { GitlabService( - instance_url="https://gitlab.com", token="my_very_secret_token" - ) + instance_url="https://gitlab.com", + token="my_very_secret_token", + ), }, ), ], @@ -452,7 +466,7 @@ def test_get_instances_from_dict_multiple_auth(instances_in_dict, result_instanc { "github.com": { "token": "abcd", - } + }, }, 0, ), @@ -461,7 +475,7 @@ def test_get_instances_from_dict_multiple_auth(instances_in_dict, result_instanc "github.com": { "token": "abcd", "max_retries": "3", - } + }, }, 3, ), @@ -470,7 +484,7 @@ def test_get_instances_from_dict_multiple_auth(instances_in_dict, result_instanc "github.com": { "token": "abcd", "max_retries": 3, - } + }, }, 3, ), @@ -479,7 +493,7 @@ def test_get_instances_from_dict_multiple_auth(instances_in_dict, result_instanc "github.com": { "tokman_instance_url": "http://localhost", "max_retries": 3, - } + }, }, 3, ), @@ -488,7 +502,7 @@ def test_get_instances_from_dict_multiple_auth(instances_in_dict, result_instanc "github.com": { "github_app_id": "123", "max_retries": 3, - } + }, }, 3, ), diff --git a/tests/unit/test_github.py b/tests/unit/test_github.py index d9718f91..507f84d8 100644 --- a/tests/unit/test_github.py +++ b/tests/unit/test_github.py @@ -23,7 +23,9 @@ @pytest.fixture def github_project(mock_github_repo): github_project = GithubProject( - repo="test_repo", service="test_service", namespace="fork_username" + repo="test_repo", + service="test_service", + namespace="fork_username", ) parent_github_project = GithubProject( repo="test_parent_repo", @@ -73,7 +75,10 @@ def test_pr_create_is_not_fork(self, github_project, fork_username): head = ":".join(filter(None, [fork_username, "master"])) github_project.github_repo.should_call("create_pull").with_args( - title="test_title", body="test_content", base="master", head=head + title="test_title", + body="test_content", + base="master", + head=head, ) github_project.parent.github_repo.should_call("create_pull").never() github_project.github_repo.should_call("create_pull").once() @@ -143,7 +148,10 @@ def test_hostname(self): ), ) def test_create_github_check_run_output( - title: str, summary: str, text: Optional[str], expected: GithubCheckRunOutput + title: str, + summary: str, + text: Optional[str], + expected: GithubCheckRunOutput, ) -> None: assert create_github_check_run_output(title, summary, text) == expected @@ -181,7 +189,8 @@ def test_set_reset_customized_auth_method(github_service_with_multiple_auth_meth @pytest.fixture def github_service_with_one_auth_method(): service = GithubService( - tokman_instance_url="http://tokman:8080", github_authentication=None + tokman_instance_url="http://tokman:8080", + github_authentication=None, ) return service From 59bf79885bd62544d66783fd80d70bb15b3de288 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 18:52:23 +0200 Subject: [PATCH 05/16] ci(ruff): enable rules without changes Signed-off-by: Matej Focko --- pyproject.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 911d797c..5afda406 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -71,8 +71,8 @@ select = [ "B", # flake8-bugbear "C4", # flake8-comprehensions "COM", # flake8-commas - # "E", # pycodestyle Error - # "F", # Pyflakes + "E", # pycodestyle Error + "F", # Pyflakes # "I", # isort # "PERF",# Perflint # "PIE", # flake8-pie @@ -81,7 +81,7 @@ select = [ # "RUF", # Ruff-specific rules # "SIM", # flake8-simplify # "UP", # pyupgrade - # "W", # pycodestyle Warning + "W", # pycodestyle Warning ] ignore = [ From 708f8943c0becc8908c02282399d96bca51dc30d Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 18:52:53 +0200 Subject: [PATCH 06/16] ci(ruff): enable isort Signed-off-by: Matej Focko --- ogr/__init__.py | 4 +-- ogr/abstract.py | 18 +++++------ ogr/exceptions.py | 2 +- ogr/factory.py | 4 +-- ogr/parsing.py | 4 +-- ogr/read_only.py | 12 +++---- ogr/services/base.py | 12 +++---- ogr/services/github/__init__.py | 10 +++--- .../github/auth_providers/__init__.py | 2 +- .../github/auth_providers/github_app.py | 2 +- ogr/services/github/auth_providers/token.py | 2 +- ogr/services/github/auth_providers/tokman.py | 4 +-- ogr/services/github/issue.py | 2 +- ogr/services/github/project.py | 32 +++++++++---------- ogr/services/github/pull_request.py | 9 +++--- ogr/services/github/release.py | 3 +- ogr/services/github/service.py | 18 +++++++---- ogr/services/github/user.py | 2 +- ogr/services/gitlab/__init__.py | 8 ++--- ogr/services/gitlab/comments.py | 2 +- ogr/services/gitlab/flag.py | 2 +- ogr/services/gitlab/issue.py | 4 +-- ogr/services/gitlab/project.py | 19 +++++------ ogr/services/gitlab/pull_request.py | 7 ++-- ogr/services/gitlab/release.py | 10 +++--- ogr/services/gitlab/service.py | 2 +- ogr/services/gitlab/user.py | 2 +- ogr/services/pagure/__init__.py | 8 ++--- ogr/services/pagure/flag.py | 3 +- ogr/services/pagure/issue.py | 4 +-- ogr/services/pagure/project.py | 16 +++++----- ogr/services/pagure/pull_request.py | 5 ++- ogr/services/pagure/release.py | 2 +- ogr/services/pagure/service.py | 6 ++-- ogr/services/pagure/user.py | 2 +- ogr/utils.py | 2 +- pyproject.toml | 2 +- tests/integration/factory/test_factory.py | 8 +++-- tests/integration/github/base.py | 2 +- tests/integration/github/base_app.py | 7 ++-- tests/integration/github/test_app.py | 6 ++-- tests/integration/github/test_check_run.py | 12 +++---- tests/integration/github/test_forks.py | 2 +- .../github/test_generic_commands.py | 2 +- tests/integration/github/test_issues.py | 2 +- .../integration/github/test_pull_requests.py | 4 +-- tests/integration/github/test_readonly.py | 6 ++-- tests/integration/github/test_retries.py | 8 ++--- tests/integration/github/test_service.py | 2 +- tests/integration/gitlab/base.py | 2 +- tests/integration/gitlab/test_forks.py | 2 +- .../gitlab/test_generic_commands.py | 2 +- tests/integration/gitlab/test_issues.py | 4 +-- .../integration/gitlab/test_pull_requests.py | 4 +-- tests/integration/gitlab/test_releases.py | 2 +- tests/integration/gitlab/test_service.py | 3 +- tests/integration/pagure/test_forks.py | 2 +- .../pagure/test_generic_commands.py | 5 ++- tests/integration/pagure/test_issues.py | 4 +-- .../integration/pagure/test_project_token.py | 6 ++-- .../integration/pagure/test_pull_requests.py | 2 +- tests/integration/pagure/test_service.py | 2 +- tests/unit/test_factory.py | 8 ++--- tests/unit/test_github.py | 14 ++++---- tests/unit/test_parsing.py | 2 +- 65 files changed, 188 insertions(+), 185 deletions(-) diff --git a/ogr/__init__.py b/ogr/__init__.py index 995678c4..ff0beba6 100644 --- a/ogr/__init__.py +++ b/ogr/__init__.py @@ -7,16 +7,16 @@ from importlib.metadata import PackageNotFoundError, distribution +from ogr.abstract import AuthMethod from ogr.factory import ( + get_instances_from_dict, get_project, get_service_class, get_service_class_or_none, - get_instances_from_dict, ) from ogr.services.github import GithubService from ogr.services.gitlab import GitlabService from ogr.services.pagure import PagureService -from ogr.abstract import AuthMethod try: __version__ = distribution(__name__).version diff --git a/ogr/abstract.py b/ogr/abstract.py index aeeddde7..fa8b618c 100644 --- a/ogr/abstract.py +++ b/ogr/abstract.py @@ -5,32 +5,32 @@ import functools from enum import Enum, IntEnum from typing import ( - Optional, - Match, - List, + Any, + Callable, Dict, + List, + Match, + Optional, + Sequence, Set, TypeVar, - Any, - Sequence, Union, - Callable, ) import github import gitlab import requests +from ogr.deprecation import deprecate_and_set_removal from ogr.exceptions import ( APIException, GitForgeInternalError, - OgrException, - GitlabAPIException, GithubAPIException, + GitlabAPIException, + OgrException, OgrNetworkError, ) from ogr.parsing import parse_git_repo -from ogr.deprecation import deprecate_and_set_removal try: from functools import cached_property as _cached_property diff --git a/ogr/exceptions.py b/ogr/exceptions.py index 8d1a6021..5b090a8e 100644 --- a/ogr/exceptions.py +++ b/ogr/exceptions.py @@ -1,7 +1,7 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from typing import Optional, Dict, Any +from typing import Any, Dict, Optional import github import gitlab diff --git a/ogr/factory.py b/ogr/factory.py index 5296b349..6d379308 100644 --- a/ogr/factory.py +++ b/ogr/factory.py @@ -2,9 +2,9 @@ # SPDX-License-Identifier: MIT import functools -from typing import Dict, Type, Optional, Set, Iterable +from typing import Dict, Iterable, Optional, Set, Type -from ogr.abstract import GitService, GitProject +from ogr.abstract import GitProject, GitService from ogr.exceptions import OgrException from ogr.parsing import parse_git_repo diff --git a/ogr/parsing.py b/ogr/parsing.py index 9e00c277..5e3cc507 100644 --- a/ogr/parsing.py +++ b/ogr/parsing.py @@ -1,8 +1,8 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from typing import Optional, Tuple, List -from urllib.parse import urlparse, ParseResult +from typing import List, Optional, Tuple +from urllib.parse import ParseResult, urlparse class RepoUrl: diff --git a/ogr/read_only.py b/ogr/read_only.py index c47880b4..c090a81b 100644 --- a/ogr/read_only.py +++ b/ogr/read_only.py @@ -4,17 +4,17 @@ import datetime import functools import logging -from typing import Callable, Any, Optional +from typing import Any, Callable, Optional from ogr.abstract import ( - PullRequest, - IssueComment, - PRComment, - PRStatus, - GitProject, CommitComment, CommitFlag, CommitStatus, + GitProject, + IssueComment, + PRComment, + PRStatus, + PullRequest, ) from ogr.constant import DEFAULT_RO_PREFIX_STRING diff --git a/ogr/services/base.py b/ogr/services/base.py index 22a565c6..365eb186 100644 --- a/ogr/services/base.py +++ b/ogr/services/base.py @@ -1,23 +1,23 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from typing import List, Optional, Any +from typing import Any, List, Optional from urllib.request import urlopen from ogr.abstract import ( - GitService, + CommitFlag, + CommitStatus, GitProject, + GitService, GitUser, - IssueComment, Issue, + IssueComment, PullRequest, - CommitFlag, - CommitStatus, Release, ) from ogr.exceptions import OgrException from ogr.parsing import parse_git_repo -from ogr.utils import search_in_comments, filter_comments +from ogr.utils import filter_comments, search_in_comments try: from functools import cached_property diff --git a/ogr/services/github/__init__.py b/ogr/services/github/__init__.py index 85462ae5..a5fab4bf 100644 --- a/ogr/services/github/__init__.py +++ b/ogr/services/github/__init__.py @@ -1,14 +1,14 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from ogr.services.github.release import GithubRelease -from ogr.services.github.user import GithubUser -from ogr.services.github.project import GithubProject -from ogr.services.github.service import GithubService +from ogr.services.github.check_run import GithubCheckRun from ogr.services.github.comments import GithubIssueComment, GithubPRComment from ogr.services.github.issue import GithubIssue +from ogr.services.github.project import GithubProject from ogr.services.github.pull_request import GithubPullRequest -from ogr.services.github.check_run import GithubCheckRun +from ogr.services.github.release import GithubRelease +from ogr.services.github.service import GithubService +from ogr.services.github.user import GithubUser __all__ = [ GithubCheckRun.__name__, diff --git a/ogr/services/github/auth_providers/__init__.py b/ogr/services/github/auth_providers/__init__.py index 32534e03..1ecd97c0 100644 --- a/ogr/services/github/auth_providers/__init__.py +++ b/ogr/services/github/auth_providers/__init__.py @@ -2,8 +2,8 @@ # SPDX-License-Identifier: MIT from ogr.services.github.auth_providers.abstract import GithubAuthentication -from ogr.services.github.auth_providers.token import TokenAuthentication from ogr.services.github.auth_providers.github_app import GithubApp +from ogr.services.github.auth_providers.token import TokenAuthentication from ogr.services.github.auth_providers.tokman import Tokman __all__ = [ diff --git a/ogr/services/github/auth_providers/github_app.py b/ogr/services/github/auth_providers/github_app.py index 4cd60c09..9fa3f992 100644 --- a/ogr/services/github/auth_providers/github_app.py +++ b/ogr/services/github/auth_providers/github_app.py @@ -6,8 +6,8 @@ import github -from ogr.services.github.auth_providers.abstract import GithubAuthentication from ogr.exceptions import OgrException +from ogr.services.github.auth_providers.abstract import GithubAuthentication class GithubApp(GithubAuthentication): diff --git a/ogr/services/github/auth_providers/token.py b/ogr/services/github/auth_providers/token.py index 39991f21..e6172d9e 100644 --- a/ogr/services/github/auth_providers/token.py +++ b/ogr/services/github/auth_providers/token.py @@ -2,9 +2,9 @@ # SPDX-License-Identifier: MIT from typing import Optional, Union -from urllib3.util import Retry import github +from urllib3.util import Retry from ogr.services.github.auth_providers.abstract import GithubAuthentication diff --git a/ogr/services/github/auth_providers/tokman.py b/ogr/services/github/auth_providers/tokman.py index 0978ba39..c261a1e9 100644 --- a/ogr/services/github/auth_providers/tokman.py +++ b/ogr/services/github/auth_providers/tokman.py @@ -1,13 +1,13 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -import requests from typing import Optional import github +import requests -from ogr.services.github.auth_providers.abstract import GithubAuthentication from ogr.exceptions import GithubAppNotInstalledError, OgrException, OgrNetworkError +from ogr.services.github.auth_providers.abstract import GithubAuthentication class Tokman(GithubAuthentication): diff --git a/ogr/services/github/issue.py b/ogr/services/github/issue.py index 6ba98c83..3fbf5530 100644 --- a/ogr/services/github/issue.py +++ b/ogr/services/github/issue.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import List, Optional, Dict, Union +from typing import Dict, List, Optional, Union import github from github import UnknownObjectException diff --git a/ogr/services/github/project.py b/ogr/services/github/project.py index afb29b8a..f2de24b4 100644 --- a/ogr/services/github/project.py +++ b/ogr/services/github/project.py @@ -3,37 +3,37 @@ import datetime import logging -from ogr.services.github.check_run import ( - GithubCheckRun, - GithubCheckRunOutput, - GithubCheckRunResult, - GithubCheckRunStatus, -) -from typing import Optional, Dict, List, Set, Union +from typing import Dict, List, Optional, Set, Union import github from github import UnknownObjectException -from github.GithubException import GithubException -from github.Repository import Repository from github.Commit import Commit from github.CommitComment import CommitComment as GithubCommitComment +from github.GithubException import GithubException +from github.Repository import Repository from ogr.abstract import ( + AccessLevel, + CommitComment, + CommitFlag, + CommitStatus, + GitTag, Issue, IssueStatus, - PullRequest, PRStatus, + PullRequest, Release, - CommitComment, - GitTag, - CommitFlag, - CommitStatus, - AccessLevel, ) from ogr.exceptions import GithubAPIException, OperationNotSupported -from ogr.read_only import if_readonly, GitProjectReadOnly +from ogr.read_only import GitProjectReadOnly, if_readonly from ogr.services import github as ogr_github from ogr.services.base import BaseGitProject +from ogr.services.github.check_run import ( + GithubCheckRun, + GithubCheckRunOutput, + GithubCheckRunResult, + GithubCheckRunStatus, +) from ogr.services.github.flag import GithubCommitFlag from ogr.services.github.issue import GithubIssue from ogr.services.github.pull_request import GithubPullRequest diff --git a/ogr/services/github/pull_request.py b/ogr/services/github/pull_request.py index dd769842..e7160c93 100644 --- a/ogr/services/github/pull_request.py +++ b/ogr/services/github/pull_request.py @@ -3,19 +3,18 @@ import datetime import logging +from typing import List, Optional, Union import github import requests -from typing import Optional, List, Union - from github import UnknownObjectException +from github.IssueComment import IssueComment as _GithubIssueComment from github.Label import Label as GithubLabel from github.PullRequest import PullRequest as _GithubPullRequest -from github.Repository import Repository as _GithubRepository -from github.IssueComment import IssueComment as _GithubIssueComment from github.PullRequestComment import PullRequestComment as _GithubPullRequestComment +from github.Repository import Repository as _GithubRepository -from ogr.abstract import PRComment, PRStatus, PullRequest, MergeCommitStatus +from ogr.abstract import MergeCommitStatus, PRComment, PRStatus, PullRequest from ogr.exceptions import GithubAPIException, OgrNetworkError from ogr.services import github as ogr_github from ogr.services.base import BasePullRequest diff --git a/ogr/services/github/release.py b/ogr/services/github/release.py index fb25f203..7d263599 100644 --- a/ogr/services/github/release.py +++ b/ogr/services/github/release.py @@ -3,10 +3,11 @@ import datetime from typing import List, Optional + from github import GithubException from github.GitRelease import GitRelease as PyGithubRelease -from ogr.abstract import Release, GitTag +from ogr.abstract import GitTag, Release from ogr.exceptions import GithubAPIException from ogr.services import github as ogr_github diff --git a/ogr/services/github/service.py b/ogr/services/github/service.py index 9848bf3a..bfb09765 100644 --- a/ogr/services/github/service.py +++ b/ogr/services/github/service.py @@ -2,29 +2,33 @@ # SPDX-License-Identifier: MIT import logging -from typing import Optional, Type, Union, List, Dict - import re -from urllib3.util import Retry +from typing import Dict, List, Optional, Type, Union + import github import github.GithubObject from github import ( - UnknownObjectException, Github as PyGithubInstance, +) +from github import ( Repository as PyGithubRepository, ) +from github import ( + UnknownObjectException, +) +from urllib3.util import Retry -from ogr.abstract import GitUser, AuthMethod +from ogr.abstract import AuthMethod, GitUser from ogr.exceptions import GithubAPIException from ogr.factory import use_for_service from ogr.services.base import BaseGitService, GitProject -from ogr.services.github.project import GithubProject from ogr.services.github.auth_providers import ( + GithubApp, GithubAuthentication, TokenAuthentication, - GithubApp, Tokman, ) +from ogr.services.github.project import GithubProject from ogr.services.github.user import GithubUser logger = logging.getLogger(__name__) diff --git a/ogr/services/github/user.py b/ogr/services/github/user.py index d247cd0d..20ed1543 100644 --- a/ogr/services/github/user.py +++ b/ogr/services/github/user.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT from collections import namedtuple -from typing import Optional, List +from typing import List, Optional from ogr.services import github as ogr_github from ogr.services.base import BaseGitUser diff --git a/ogr/services/gitlab/__init__.py b/ogr/services/gitlab/__init__.py index 9ae245ca..870a9e76 100644 --- a/ogr/services/gitlab/__init__.py +++ b/ogr/services/gitlab/__init__.py @@ -1,13 +1,13 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from ogr.services.gitlab.release import GitlabRelease -from ogr.services.gitlab.user import GitlabUser -from ogr.services.gitlab.project import GitlabProject -from ogr.services.gitlab.service import GitlabService from ogr.services.gitlab.comments import GitlabIssueComment, GitlabPRComment from ogr.services.gitlab.issue import GitlabIssue +from ogr.services.gitlab.project import GitlabProject from ogr.services.gitlab.pull_request import GitlabPullRequest +from ogr.services.gitlab.release import GitlabRelease +from ogr.services.gitlab.service import GitlabService +from ogr.services.gitlab.user import GitlabUser __all__ = [ GitlabIssue.__name__, diff --git a/ogr/services/gitlab/comments.py b/ogr/services/gitlab/comments.py index a8a5d87b..7dc7fb54 100644 --- a/ogr/services/gitlab/comments.py +++ b/ogr/services/gitlab/comments.py @@ -8,9 +8,9 @@ import gitlab.exceptions from gitlab.v4.objects import ( ProjectIssueNote, - ProjectMergeRequestNote, ProjectIssueNoteAwardEmoji, ProjectMergeRequestAwardEmoji, + ProjectMergeRequestNote, ) from ogr.abstract import Comment, IssueComment, PRComment, Reaction diff --git a/ogr/services/gitlab/flag.py b/ogr/services/gitlab/flag.py index 1dfdbd86..68e8d503 100644 --- a/ogr/services/gitlab/flag.py +++ b/ogr/services/gitlab/flag.py @@ -1,8 +1,8 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -import logging import datetime +import logging from typing import List import gitlab diff --git a/ogr/services/gitlab/issue.py b/ogr/services/gitlab/issue.py index 99819af2..8b941e97 100644 --- a/ogr/services/gitlab/issue.py +++ b/ogr/services/gitlab/issue.py @@ -2,12 +2,12 @@ # SPDX-License-Identifier: MIT import datetime -from typing import List, Optional, Dict, Union +from typing import Dict, List, Optional, Union import gitlab from gitlab.v4.objects import Issue as _GitlabIssue -from ogr.abstract import IssueComment, IssueStatus, Issue +from ogr.abstract import Issue, IssueComment, IssueStatus from ogr.exceptions import GitlabAPIException, IssueTrackerDisabled from ogr.services import gitlab as ogr_gitlab from ogr.services.base import BaseIssue diff --git a/ogr/services/gitlab/project.py b/ogr/services/gitlab/project.py index 1676665e..a2cb8967 100644 --- a/ogr/services/gitlab/project.py +++ b/ogr/services/gitlab/project.py @@ -2,23 +2,24 @@ # SPDX-License-Identifier: MIT import logging -from typing import Any, List, Optional, Dict, Set, Union +from typing import Any, Dict, List, Optional, Set, Union import gitlab from gitlab.exceptions import GitlabGetError -from gitlab.v4.objects import Project as GitlabObjectsProject, ProjectCommit +from gitlab.v4.objects import Project as GitlabObjectsProject +from gitlab.v4.objects import ProjectCommit from ogr.abstract import ( - PullRequest, - Issue, - Release, + AccessLevel, + CommitComment, + CommitFlag, + CommitStatus, GitTag, + Issue, IssueStatus, - CommitFlag, PRStatus, - CommitComment, - CommitStatus, - AccessLevel, + PullRequest, + Release, ) from ogr.exceptions import GitlabAPIException, OperationNotSupported from ogr.services import gitlab as ogr_gitlab diff --git a/ogr/services/gitlab/pull_request.py b/ogr/services/gitlab/pull_request.py index 5a2ece79..95d0f667 100644 --- a/ogr/services/gitlab/pull_request.py +++ b/ogr/services/gitlab/pull_request.py @@ -2,15 +2,14 @@ # SPDX-License-Identifier: MIT import datetime +from typing import Dict, List, Optional import gitlab import requests -from typing import Dict, List, Optional - -from gitlab.v4.objects import MergeRequest as _GitlabMergeRequest from gitlab.exceptions import GitlabGetError +from gitlab.v4.objects import MergeRequest as _GitlabMergeRequest -from ogr.abstract import PullRequest, PRComment, PRStatus, MergeCommitStatus +from ogr.abstract import MergeCommitStatus, PRComment, PRStatus, PullRequest from ogr.exceptions import GitlabAPIException, OgrNetworkError from ogr.services import gitlab as ogr_gitlab from ogr.services.base import BasePullRequest diff --git a/ogr/services/gitlab/release.py b/ogr/services/gitlab/release.py index 832a43a2..ef66689c 100644 --- a/ogr/services/gitlab/release.py +++ b/ogr/services/gitlab/release.py @@ -1,14 +1,14 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from gitlab.v4.objects import ProjectRelease as _GitlabRelease - import datetime -from typing import Optional, List +from typing import List, Optional -from ogr.abstract import Release, GitTag -from ogr.services import gitlab as ogr_gitlab +from gitlab.v4.objects import ProjectRelease as _GitlabRelease + +from ogr.abstract import GitTag, Release from ogr.exceptions import OperationNotSupported +from ogr.services import gitlab as ogr_gitlab class GitlabRelease(Release): diff --git a/ogr/services/gitlab/service.py b/ogr/services/gitlab/service.py index efa99616..da8bc2df 100644 --- a/ogr/services/gitlab/service.py +++ b/ogr/services/gitlab/service.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import logging -from typing import Optional, List +from typing import List, Optional import gitlab diff --git a/ogr/services/gitlab/user.py b/ogr/services/gitlab/user.py index 1358e8f6..207eb2e8 100644 --- a/ogr/services/gitlab/user.py +++ b/ogr/services/gitlab/user.py @@ -3,9 +3,9 @@ from typing import List +from ogr.exceptions import OperationNotSupported from ogr.services import gitlab as ogr_gitlab from ogr.services.base import BaseGitUser -from ogr.exceptions import OperationNotSupported class GitlabUser(BaseGitUser): diff --git a/ogr/services/pagure/__init__.py b/ogr/services/pagure/__init__.py index 1ff9c940..4d76f920 100644 --- a/ogr/services/pagure/__init__.py +++ b/ogr/services/pagure/__init__.py @@ -1,13 +1,13 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from ogr.services.pagure.release import PagureRelease -from ogr.services.pagure.user import PagureUser -from ogr.services.pagure.project import PagureProject -from ogr.services.pagure.service import PagureService from ogr.services.pagure.comments import PagureIssueComment, PagurePRComment from ogr.services.pagure.issue import PagureIssue +from ogr.services.pagure.project import PagureProject from ogr.services.pagure.pull_request import PagurePullRequest +from ogr.services.pagure.release import PagureRelease +from ogr.services.pagure.service import PagureService +from ogr.services.pagure.user import PagureUser __all__ = [ PagurePullRequest.__name__, diff --git a/ogr/services/pagure/flag.py b/ogr/services/pagure/flag.py index a456bd8f..f3cf953e 100644 --- a/ogr/services/pagure/flag.py +++ b/ogr/services/pagure/flag.py @@ -2,8 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import List, Dict, Any - +from typing import Any, Dict, List from ogr.abstract import CommitFlag, CommitStatus from ogr.services import pagure as ogr_pagure diff --git a/ogr/services/pagure/issue.py b/ogr/services/pagure/issue.py index 1bfc0af5..bfc6330b 100644 --- a/ogr/services/pagure/issue.py +++ b/ogr/services/pagure/issue.py @@ -2,9 +2,9 @@ # SPDX-License-Identifier: MIT import datetime -from typing import List, Optional, Dict, Union, Any, cast +from typing import Any, Dict, List, Optional, Union, cast -from ogr.abstract import IssueComment, IssueStatus, Issue +from ogr.abstract import Issue, IssueComment, IssueStatus from ogr.exceptions import ( IssueTrackerDisabled, OperationNotSupported, diff --git a/ogr/services/pagure/project.py b/ogr/services/pagure/project.py index 41a376cc..3e46c77e 100644 --- a/ogr/services/pagure/project.py +++ b/ogr/services/pagure/project.py @@ -2,27 +2,27 @@ # SPDX-License-Identifier: MIT import logging -from typing import List, Optional, Dict, Set, Iterable +from typing import Dict, Iterable, List, Optional, Set from urllib.parse import urlparse from ogr.abstract import ( - PRStatus, - GitTag, - CommitFlag, + AccessLevel, CommitComment, + CommitFlag, CommitStatus, - PullRequest, + GitTag, Issue, IssueStatus, + PRStatus, + PullRequest, Release, - AccessLevel, ) from ogr.exceptions import ( - PagureAPIException, OgrException, OperationNotSupported, + PagureAPIException, ) -from ogr.read_only import if_readonly, GitProjectReadOnly +from ogr.read_only import GitProjectReadOnly, if_readonly from ogr.services import pagure as ogr_pagure from ogr.services.base import BaseGitProject from ogr.services.pagure.flag import PagureCommitFlag diff --git a/ogr/services/pagure/pull_request.py b/ogr/services/pagure/pull_request.py index d20681f0..7a9bda2a 100644 --- a/ogr/services/pagure/pull_request.py +++ b/ogr/services/pagure/pull_request.py @@ -3,10 +3,9 @@ import datetime import logging -from typing import List, Optional, Dict, Any, Union +from typing import Any, Dict, List, Optional, Union -from ogr.abstract import PRStatus, CommitFlag, CommitStatus -from ogr.abstract import PullRequest, PRComment +from ogr.abstract import CommitFlag, CommitStatus, PRComment, PRStatus, PullRequest from ogr.exceptions import PagureAPIException from ogr.services import pagure as ogr_pagure from ogr.services.base import BasePullRequest diff --git a/ogr/services/pagure/release.py b/ogr/services/pagure/release.py index a3233a99..57c837bb 100644 --- a/ogr/services/pagure/release.py +++ b/ogr/services/pagure/release.py @@ -5,8 +5,8 @@ from typing import List, Optional from ogr.abstract import GitTag, Release -from ogr.services import pagure as ogr_pagure from ogr.exceptions import OperationNotSupported, PagureAPIException +from ogr.services import pagure as ogr_pagure class PagureRelease(Release): diff --git a/ogr/services/pagure/service.py b/ogr/services/pagure/service.py index a51edd91..00c89034 100644 --- a/ogr/services/pagure/service.py +++ b/ogr/services/pagure/service.py @@ -8,11 +8,11 @@ import urllib3 from ogr.exceptions import ( - PagureAPIException, + GitForgeInternalError, OgrException, - OperationNotSupported, OgrNetworkError, - GitForgeInternalError, + OperationNotSupported, + PagureAPIException, ) from ogr.factory import use_for_service from ogr.parsing import parse_git_repo diff --git a/ogr/services/pagure/user.py b/ogr/services/pagure/user.py index beb049c9..df63ce85 100644 --- a/ogr/services/pagure/user.py +++ b/ogr/services/pagure/user.py @@ -3,10 +3,10 @@ from typing import List +from ogr.exceptions import OperationNotSupported from ogr.services import pagure as ogr_pagure from ogr.services.base import BaseGitUser from ogr.services.pagure.project import PagureProject -from ogr.exceptions import OperationNotSupported class PagureUser(BaseGitUser): diff --git a/ogr/utils.py b/ogr/utils.py index 0e2959c6..6dbea16b 100644 --- a/ogr/utils.py +++ b/ogr/utils.py @@ -4,7 +4,7 @@ import functools import logging import re -from typing import Callable, List, Union, Match, Optional, Dict, Tuple, Any +from typing import Any, Callable, Dict, List, Match, Optional, Tuple, Union from ogr.abstract import AnyComment, Comment diff --git a/pyproject.toml b/pyproject.toml index 5afda406..021dfc02 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -73,7 +73,7 @@ select = [ "COM", # flake8-commas "E", # pycodestyle Error "F", # Pyflakes - # "I", # isort + "I", # isort # "PERF",# Perflint # "PIE", # flake8-pie # "PT", # flake8-pytest-style, would be nice to enable diff --git a/tests/integration/factory/test_factory.py b/tests/integration/factory/test_factory.py index d5538150..4d8c68ab 100644 --- a/tests/integration/factory/test_factory.py +++ b/tests/integration/factory/test_factory.py @@ -2,11 +2,13 @@ # SPDX-License-Identifier: MIT import os -from requre.online_replacing import record_requests_for_all_methods -from requre.utils import get_datafile_filename import unittest from pathlib import Path -from ogr import GithubService, PagureService, get_project, GitlabService + +from requre.online_replacing import record_requests_for_all_methods +from requre.utils import get_datafile_filename + +from ogr import GithubService, GitlabService, PagureService, get_project from ogr.services.github import GithubProject from ogr.services.gitlab import GitlabProject from ogr.services.pagure import PagureProject diff --git a/tests/integration/github/base.py b/tests/integration/github/base.py index 15d20ac4..e57dad0b 100644 --- a/tests/integration/github/base.py +++ b/tests/integration/github/base.py @@ -2,8 +2,8 @@ # SPDX-License-Identifier: MIT import os -from pathlib import Path import unittest +from pathlib import Path from requre.utils import get_datafile_filename diff --git a/tests/integration/github/base_app.py b/tests/integration/github/base_app.py index 20d5f48d..09268d80 100644 --- a/tests/integration/github/base_app.py +++ b/tests/integration/github/base_app.py @@ -1,14 +1,15 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from ogr.services.github.service import GithubService import os -from pathlib import Path import tempfile import unittest +from pathlib import Path -from requre.utils import get_datafile_filename from requre.online_replacing import record_requests_for_all_methods +from requre.utils import get_datafile_filename + +from ogr.services.github.service import GithubService @record_requests_for_all_methods() diff --git a/tests/integration/github/test_app.py b/tests/integration/github/test_app.py index 4d67ccb1..6d7702d7 100644 --- a/tests/integration/github/test_app.py +++ b/tests/integration/github/test_app.py @@ -3,14 +3,14 @@ import tempfile from pathlib import Path + import pytest +from requre.online_replacing import record_requests_for_all_methods from ogr import GithubService -from ogr.services.github.project import GithubProject from ogr.exceptions import OgrException - +from ogr.services.github.project import GithubProject from tests.integration.github.base_app import GithubAppTests -from requre.online_replacing import record_requests_for_all_methods @record_requests_for_all_methods() diff --git a/tests/integration/github/test_check_run.py b/tests/integration/github/test_check_run.py index c2c29d33..fe68a2d4 100644 --- a/tests/integration/github/test_check_run.py +++ b/tests/integration/github/test_check_run.py @@ -2,18 +2,18 @@ # SPDX-License-Identifier: MIT from datetime import datetime -from ogr.services.github.check_run import ( - GithubCheckRunResult, - GithubCheckRunStatus, - create_github_check_run_output, -) import pytest from requre.online_replacing import record_requests_for_all_methods -from tests.integration.github.base_app import GithubAppTests from ogr.exceptions import OperationNotSupported from ogr.services.github import GithubProject +from ogr.services.github.check_run import ( + GithubCheckRunResult, + GithubCheckRunStatus, + create_github_check_run_output, +) +from tests.integration.github.base_app import GithubAppTests @record_requests_for_all_methods() diff --git a/tests/integration/github/test_forks.py b/tests/integration/github/test_forks.py index c8dee776..e20f068e 100644 --- a/tests/integration/github/test_forks.py +++ b/tests/integration/github/test_forks.py @@ -2,8 +2,8 @@ # SPDX-License-Identifier: MIT from requre.online_replacing import record_requests_for_all_methods -from ogr.exceptions import GithubAPIException +from ogr.exceptions import GithubAPIException from tests.integration.github.base import GithubTests diff --git a/tests/integration/github/test_generic_commands.py b/tests/integration/github/test_generic_commands.py index e1cf4d0f..c27d75eb 100644 --- a/tests/integration/github/test_generic_commands.py +++ b/tests/integration/github/test_generic_commands.py @@ -6,9 +6,9 @@ import pytest from requre.online_replacing import record_requests_for_all_methods -from tests.integration.github.base import GithubTests from ogr.abstract import AccessLevel, CommitStatus from ogr.exceptions import GithubAPIException +from tests.integration.github.base import GithubTests @record_requests_for_all_methods() diff --git a/tests/integration/github/test_issues.py b/tests/integration/github/test_issues.py index 244bf7fc..a25c19e7 100644 --- a/tests/integration/github/test_issues.py +++ b/tests/integration/github/test_issues.py @@ -4,13 +4,13 @@ import pytest from requre.online_replacing import record_requests_for_all_methods -from tests.integration.github.base import GithubTests from ogr.abstract import IssueStatus from ogr.exceptions import ( GithubAPIException, IssueTrackerDisabled, OperationNotSupported, ) +from tests.integration.github.base import GithubTests @record_requests_for_all_methods() diff --git a/tests/integration/github/test_pull_requests.py b/tests/integration/github/test_pull_requests.py index 17022ab7..589f1b1e 100644 --- a/tests/integration/github/test_pull_requests.py +++ b/tests/integration/github/test_pull_requests.py @@ -4,9 +4,9 @@ import pytest from requre.online_replacing import record_requests_for_all_methods -from tests.integration.github.base import GithubTests -from ogr.abstract import PRStatus, MergeCommitStatus +from ogr.abstract import MergeCommitStatus, PRStatus from ogr.exceptions import GithubAPIException +from tests.integration.github.base import GithubTests @record_requests_for_all_methods() diff --git a/tests/integration/github/test_readonly.py b/tests/integration/github/test_readonly.py index 7e2bad15..b5cb33c2 100644 --- a/tests/integration/github/test_readonly.py +++ b/tests/integration/github/test_readonly.py @@ -2,12 +2,14 @@ # SPDX-License-Identifier: MIT import os -from pathlib import Path import unittest -from ogr.services.github import GithubService +from pathlib import Path + from requre.online_replacing import record_requests_for_all_methods from requre.utils import get_datafile_filename +from ogr.services.github import GithubService + @record_requests_for_all_methods() class ReadOnly(unittest.TestCase): diff --git a/tests/integration/github/test_retries.py b/tests/integration/github/test_retries.py index f61c9342..961381df 100644 --- a/tests/integration/github/test_retries.py +++ b/tests/integration/github/test_retries.py @@ -2,12 +2,12 @@ # SPDX-License-Identifier: MIT import pytest - -from ogr import GithubService from flexmock import flexmock -from urllib3.connectionpool import HTTPSConnectionPool -from github.GithubException import BadCredentialsException from github import Github +from github.GithubException import BadCredentialsException +from urllib3.connectionpool import HTTPSConnectionPool + +from ogr import GithubService @pytest.mark.skip(reason="Will fail until flexmock is fixed") diff --git a/tests/integration/github/test_service.py b/tests/integration/github/test_service.py index 5b032887..e3a62e5b 100644 --- a/tests/integration/github/test_service.py +++ b/tests/integration/github/test_service.py @@ -5,9 +5,9 @@ from github import GithubException, UnknownObjectException from requre.online_replacing import record_requests_for_all_methods -from tests.integration.github.base import GithubTests from ogr.exceptions import GithubAPIException from ogr.services.github.pull_request import GithubPullRequest +from tests.integration.github.base import GithubTests @record_requests_for_all_methods() diff --git a/tests/integration/gitlab/base.py b/tests/integration/gitlab/base.py index a9f1b52d..2573ea26 100644 --- a/tests/integration/gitlab/base.py +++ b/tests/integration/gitlab/base.py @@ -2,8 +2,8 @@ # SPDX-License-Identifier: MIT import os -from pathlib import Path import unittest +from pathlib import Path from requre.utils import get_datafile_filename diff --git a/tests/integration/gitlab/test_forks.py b/tests/integration/gitlab/test_forks.py index 890bbaed..373f74a4 100644 --- a/tests/integration/gitlab/test_forks.py +++ b/tests/integration/gitlab/test_forks.py @@ -3,8 +3,8 @@ from requre.online_replacing import record_requests_for_all_methods -from tests.integration.gitlab.base import GitlabTests from ogr.exceptions import OperationNotSupported +from tests.integration.gitlab.base import GitlabTests @record_requests_for_all_methods() diff --git a/tests/integration/gitlab/test_generic_commands.py b/tests/integration/gitlab/test_generic_commands.py index f24aadbd..1b71c16c 100644 --- a/tests/integration/gitlab/test_generic_commands.py +++ b/tests/integration/gitlab/test_generic_commands.py @@ -4,10 +4,10 @@ from datetime import datetime import pytest +from requre.online_replacing import record_requests_for_all_methods from ogr.abstract import AccessLevel, CommitStatus from ogr.exceptions import GitlabAPIException -from requre.online_replacing import record_requests_for_all_methods from tests.integration.gitlab.base import GitlabTests diff --git a/tests/integration/gitlab/test_issues.py b/tests/integration/gitlab/test_issues.py index 454f8cea..b2906c2f 100644 --- a/tests/integration/gitlab/test_issues.py +++ b/tests/integration/gitlab/test_issues.py @@ -2,10 +2,10 @@ # SPDX-License-Identifier: MIT from requre.online_replacing import record_requests_for_all_methods -from ogr.exceptions import IssueTrackerDisabled -from tests.integration.gitlab.base import GitlabTests from ogr.abstract import IssueStatus +from ogr.exceptions import IssueTrackerDisabled +from tests.integration.gitlab.base import GitlabTests @record_requests_for_all_methods() diff --git a/tests/integration/gitlab/test_pull_requests.py b/tests/integration/gitlab/test_pull_requests.py index 4b08083a..99b0ad9d 100644 --- a/tests/integration/gitlab/test_pull_requests.py +++ b/tests/integration/gitlab/test_pull_requests.py @@ -4,9 +4,9 @@ import pytest from requre.online_replacing import record_requests_for_all_methods -from tests.integration.gitlab.base import GitlabTests -from ogr.abstract import PRStatus, CommitStatus, MergeCommitStatus +from ogr.abstract import CommitStatus, MergeCommitStatus, PRStatus from ogr.exceptions import GitlabAPIException +from tests.integration.gitlab.base import GitlabTests @record_requests_for_all_methods() diff --git a/tests/integration/gitlab/test_releases.py b/tests/integration/gitlab/test_releases.py index af10ba26..f30bf997 100644 --- a/tests/integration/gitlab/test_releases.py +++ b/tests/integration/gitlab/test_releases.py @@ -3,8 +3,8 @@ from requre.online_replacing import record_requests_for_all_methods -from tests.integration.gitlab.base import GitlabTests from ogr.exceptions import OperationNotSupported +from tests.integration.gitlab.base import GitlabTests @record_requests_for_all_methods() diff --git a/tests/integration/gitlab/test_service.py b/tests/integration/gitlab/test_service.py index 987cdff6..7db67152 100644 --- a/tests/integration/gitlab/test_service.py +++ b/tests/integration/gitlab/test_service.py @@ -5,11 +5,10 @@ from gitlab import GitlabGetError from requre.online_replacing import record_requests_for_all_methods -from tests.integration.gitlab.base import GitlabTests - from ogr import GitlabService from ogr.exceptions import GitlabAPIException from ogr.services.gitlab.pull_request import GitlabPullRequest +from tests.integration.gitlab.base import GitlabTests @record_requests_for_all_methods() diff --git a/tests/integration/pagure/test_forks.py b/tests/integration/pagure/test_forks.py index b93afc70..9bdf2981 100644 --- a/tests/integration/pagure/test_forks.py +++ b/tests/integration/pagure/test_forks.py @@ -3,8 +3,8 @@ from requre.online_replacing import record_requests_for_all_methods -from tests.integration.pagure.base import PagureTests from ogr.exceptions import OperationNotSupported, PagureAPIException +from tests.integration.pagure.base import PagureTests @record_requests_for_all_methods() diff --git a/tests/integration/pagure/test_generic_commands.py b/tests/integration/pagure/test_generic_commands.py index 339d5d9e..9cdddbeb 100644 --- a/tests/integration/pagure/test_generic_commands.py +++ b/tests/integration/pagure/test_generic_commands.py @@ -2,12 +2,11 @@ # SPDX-License-Identifier: MIT import pytest -from ogr.exceptions import GitForgeInternalError - from requre.online_replacing import record_requests_for_all_methods -from tests.integration.pagure.base import PagureTests from ogr.abstract import AccessLevel +from ogr.exceptions import GitForgeInternalError +from tests.integration.pagure.base import PagureTests @record_requests_for_all_methods() diff --git a/tests/integration/pagure/test_issues.py b/tests/integration/pagure/test_issues.py index 13512241..a4c027be 100644 --- a/tests/integration/pagure/test_issues.py +++ b/tests/integration/pagure/test_issues.py @@ -2,10 +2,10 @@ # SPDX-License-Identifier: MIT from requre.online_replacing import record_requests_for_all_methods -from ogr.exceptions import IssueTrackerDisabled -from tests.integration.pagure.base import PagureTests from ogr.abstract import IssueStatus +from ogr.exceptions import IssueTrackerDisabled +from tests.integration.pagure.base import PagureTests @record_requests_for_all_methods() diff --git a/tests/integration/pagure/test_project_token.py b/tests/integration/pagure/test_project_token.py index 8dabf126..62ad386e 100644 --- a/tests/integration/pagure/test_project_token.py +++ b/tests/integration/pagure/test_project_token.py @@ -5,13 +5,13 @@ from datetime import datetime import pytest -from requre.utils import get_datafile_filename from requre.online_replacing import record_requests_for_all_methods +from requre.utils import get_datafile_filename -from tests.integration.pagure.base import PagureTests from ogr import PagureService -from ogr.abstract import IssueStatus, CommitStatus +from ogr.abstract import CommitStatus, IssueStatus from ogr.exceptions import PagureAPIException +from tests.integration.pagure.base import PagureTests @record_requests_for_all_methods() diff --git a/tests/integration/pagure/test_pull_requests.py b/tests/integration/pagure/test_pull_requests.py index b5b9f18b..b5cee7af 100644 --- a/tests/integration/pagure/test_pull_requests.py +++ b/tests/integration/pagure/test_pull_requests.py @@ -3,8 +3,8 @@ from requre.online_replacing import record_requests_for_all_methods +from ogr.abstract import CommitStatus, PRStatus from tests.integration.pagure.base import PagureTests -from ogr.abstract import PRStatus, CommitStatus @record_requests_for_all_methods() diff --git a/tests/integration/pagure/test_service.py b/tests/integration/pagure/test_service.py index 4f8e7594..b5051623 100644 --- a/tests/integration/pagure/test_service.py +++ b/tests/integration/pagure/test_service.py @@ -4,8 +4,8 @@ import pytest from requre.online_replacing import record_requests_for_all_methods -from tests.integration.pagure.base import PagureTests from ogr.exceptions import OgrException +from tests.integration.pagure.base import PagureTests @record_requests_for_all_methods() diff --git a/tests/unit/test_factory.py b/tests/unit/test_factory.py index a9977dcb..a77efa04 100644 --- a/tests/unit/test_factory.py +++ b/tests/unit/test_factory.py @@ -4,14 +4,12 @@ from typing import Set import pytest -from flexmock import Mock -from flexmock import flexmock - +from flexmock import Mock, flexmock from urllib3.util import Retry -from ogr import PagureService, GitlabService, GithubService +from ogr import GithubService, GitlabService, PagureService from ogr.exceptions import OgrException -from ogr.factory import get_service_class, get_project, get_instances_from_dict +from ogr.factory import get_instances_from_dict, get_project, get_service_class from ogr.services.github import GithubProject from ogr.services.gitlab import GitlabProject from ogr.services.pagure import PagureProject diff --git a/tests/unit/test_github.py b/tests/unit/test_github.py index 507f84d8..2c615775 100644 --- a/tests/unit/test_github.py +++ b/tests/unit/test_github.py @@ -8,16 +8,16 @@ from flexmock import flexmock from ogr import GithubService -from ogr.services.github.project import GithubProject -from ogr.services.github.pull_request import GithubPullRequest +from ogr.abstract import AuthMethod +from ogr.exceptions import GithubAPIException +from ogr.services.github.auth_providers.token import TokenAuthentication +from ogr.services.github.auth_providers.tokman import Tokman from ogr.services.github.check_run import ( - create_github_check_run_output, GithubCheckRunOutput, + create_github_check_run_output, ) -from ogr.services.github.auth_providers.tokman import Tokman -from ogr.services.github.auth_providers.token import TokenAuthentication -from ogr.abstract import AuthMethod -from ogr.exceptions import GithubAPIException +from ogr.services.github.project import GithubProject +from ogr.services.github.pull_request import GithubPullRequest @pytest.fixture diff --git a/tests/unit/test_parsing.py b/tests/unit/test_parsing.py index e7b4579f..f77cd6d0 100644 --- a/tests/unit/test_parsing.py +++ b/tests/unit/test_parsing.py @@ -3,7 +3,7 @@ import pytest -from ogr.parsing import parse_git_repo, RepoUrl +from ogr.parsing import RepoUrl, parse_git_repo @pytest.mark.parametrize( From 6bfb367c4e192a70fabcabbd6d84d1718875812b Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 18:53:21 +0200 Subject: [PATCH 07/16] ci(ruff): enable flake8-pie Signed-off-by: Matej Focko --- ogr/exceptions.py | 2 -- pyproject.toml | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/ogr/exceptions.py b/ogr/exceptions.py index 5b090a8e..9e261b90 100644 --- a/ogr/exceptions.py +++ b/ogr/exceptions.py @@ -10,8 +10,6 @@ class OgrException(Exception): """Something went wrong during our execution.""" - pass - class APIException(OgrException): """Generic API exception.""" diff --git a/pyproject.toml b/pyproject.toml index 021dfc02..a24d52f6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -75,7 +75,7 @@ select = [ "F", # Pyflakes "I", # isort # "PERF",# Perflint - # "PIE", # flake8-pie + "PIE", # flake8-pie # "PT", # flake8-pytest-style, would be nice to enable # "RET", # flake8-return # "RUF", # Ruff-specific rules From 6ceebdd731ea49b144100d0e591c853831435ec7 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 18:56:37 +0200 Subject: [PATCH 08/16] ci(ruff): enable flake8-return Signed-off-by: Matej Focko --- ogr/read_only.py | 28 ++++++++++++++-------------- ogr/services/github/check_run.py | 3 ++- ogr/services/github/project.py | 12 ++++++------ ogr/services/github/pull_request.py | 4 ++-- ogr/services/gitlab/project.py | 12 ++++++------ ogr/services/gitlab/pull_request.py | 6 +++--- ogr/services/gitlab/service.py | 9 ++------- ogr/services/pagure/issue.py | 3 ++- ogr/services/pagure/project.py | 12 ++++++------ ogr/services/pagure/service.py | 21 +++++++++------------ pyproject.toml | 2 +- tests/integration/gitlab/base.py | 4 +++- tests/unit/test_github.py | 14 ++++---------- 13 files changed, 60 insertions(+), 70 deletions(-) diff --git a/ogr/read_only.py b/ogr/read_only.py index c090a81b..46313792 100644 --- a/ogr/read_only.py +++ b/ogr/read_only.py @@ -73,20 +73,20 @@ def decorator_readonly(func): def readonly_func(self, *args, **kwargs): if not self.read_only: return func(self, *args, **kwargs) - else: - args_str = str(args)[1:-1] - kwargs_str = ", ".join(f"{k}={v!r}" for k, v in kwargs.items()) - # add , in case there are also args, what has to be separated - if args and kwargs: - kwargs_str = ", " + kwargs_str - log_output( - f"{log_message} {self.__class__.__name__}." - f"{func.__name__}({args_str}{kwargs_str})", - ) - if return_function: - return return_function(self, *args, **kwargs) - else: - return return_value + + args_str = str(args)[1:-1] + kwargs_str = ", ".join(f"{k}={v!r}" for k, v in kwargs.items()) + # add , in case there are also args, what has to be separated + if args and kwargs: + kwargs_str = ", " + kwargs_str + log_output( + f"{log_message} {self.__class__.__name__}." + f"{func.__name__}({args_str}{kwargs_str})", + ) + if return_function: + return return_function(self, *args, **kwargs) + + return return_value return readonly_func diff --git a/ogr/services/github/check_run.py b/ogr/services/github/check_run.py index 30bdf327..245537a5 100644 --- a/ogr/services/github/check_run.py +++ b/ogr/services/github/check_run.py @@ -290,7 +290,8 @@ def get( raise OperationNotSupported( "Cannot retrieve check run by both ID and commit hash", ) - elif not (check_run_id is not None or commit_sha): + + if not (check_run_id is not None or commit_sha): raise OperationNotSupported("Cannot retrieve check run by no criteria") if check_run_id is not None: diff --git a/ogr/services/github/project.py b/ogr/services/github/project.py index f2de24b4..f3969e89 100644 --- a/ogr/services/github/project.py +++ b/ogr/services/github/project.py @@ -197,12 +197,12 @@ def get_fork(self, create: bool = True) -> Optional["GithubProject"]: if not self.is_forked(): if create: return self.fork_create() - else: - logger.info( - f"Fork of {self.github_repo.full_name}" - " does not exist and we were asked not to create it.", - ) - return None + + logger.info( + f"Fork of {self.github_repo.full_name}" + " does not exist and we were asked not to create it.", + ) + return None return self._construct_fork_project() def get_owners(self) -> List[str]: diff --git a/ogr/services/github/pull_request.py b/ogr/services/github/pull_request.py index e7160c93..da884e17 100644 --- a/ogr/services/github/pull_request.py +++ b/ogr/services/github/pull_request.py @@ -112,8 +112,8 @@ def merge_commit_sha(self) -> str: def merge_commit_status(self) -> MergeCommitStatus: if self._raw_pr.mergeable: return MergeCommitStatus.can_be_merged - else: - return MergeCommitStatus.cannot_be_merged + + return MergeCommitStatus.cannot_be_merged @property def source_project(self) -> "ogr_github.GithubProject": diff --git a/ogr/services/gitlab/project.py b/ogr/services/gitlab/project.py index a2cb8967..ecf995cc 100644 --- a/ogr/services/gitlab/project.py +++ b/ogr/services/gitlab/project.py @@ -146,12 +146,12 @@ def get_fork(self, create: bool = True) -> Optional["GitlabProject"]: if not self.is_forked(): if create: return self.fork_create() - else: - logger.info( - f"Fork of {self.gitlab_repo.attributes['name']}" - " does not exist and we were asked not to create it.", - ) - return None + + logger.info( + f"Fork of {self.gitlab_repo.attributes['name']}" + " does not exist and we were asked not to create it.", + ) + return None return self._construct_fork_project() def get_owners(self) -> List[str]: diff --git a/ogr/services/gitlab/pull_request.py b/ogr/services/gitlab/pull_request.py index 95d0f667..1846c69d 100644 --- a/ogr/services/gitlab/pull_request.py +++ b/ogr/services/gitlab/pull_request.py @@ -125,11 +125,11 @@ def merge_commit_sha(self) -> Optional[str]: @property def merge_commit_status(self) -> MergeCommitStatus: status = self._raw_pr.merge_status - if status in self._merge_commit_status: - return self._merge_commit_status[status] - else: + if status not in self._merge_commit_status: raise GitlabAPIException(f"Invalid merge_status {status}") + return self._merge_commit_status[status] + @property def source_project(self) -> "ogr_gitlab.GitlabProject": if self._source_project is None: diff --git a/ogr/services/gitlab/service.py b/ogr/services/gitlab/service.py index da8bc2df..40e9047e 100644 --- a/ogr/services/gitlab/service.py +++ b/ogr/services/gitlab/service.py @@ -64,12 +64,11 @@ def __str__(self) -> str: f", token='{self.token[:1]}***{self.token[-1:]}'" if self.token else "" ) ssl_str = ", ssl_verify=False" if not self.ssl_verify else "" - str_result = ( + return ( f"GitlabService(instance_url='{self.instance_url}'" f"{token_str}" f"{ssl_str})" ) - return str_result def __eq__(self, o: object) -> bool: if not issubclass(o.__class__, GitlabService): @@ -151,8 +150,6 @@ def list_projects( else: raise OperationNotSupported - gitlab_projects: List[GitProject] - if language: # group.projects.list gives us a GroupProject instance # in order to be able to filter by language we need Project instance @@ -166,7 +163,7 @@ def list_projects( ] else: projects_to_convert = projects - gitlab_projects = [ + return [ GitlabProject( repo=project.attributes["path"], namespace=project.attributes["namespace"]["full_path"], @@ -174,5 +171,3 @@ def list_projects( ) for project in projects_to_convert ] - - return gitlab_projects diff --git a/ogr/services/pagure/issue.py b/ogr/services/pagure/issue.py index bfc6330b..d0ce84b0 100644 --- a/ogr/services/pagure/issue.py +++ b/ogr/services/pagure/issue.py @@ -135,7 +135,8 @@ def create( payload["private"] = "true" if assignees and len(assignees) > 1: raise OperationNotSupported("Pagure does not support multiple assignees") - elif assignees: + + if assignees: payload["assignee"] = assignees[0] new_issue = project._call_project_api("new_issue", data=payload, method="POST")[ diff --git a/ogr/services/pagure/project.py b/ogr/services/pagure/project.py index 3e46c77e..581d75f2 100644 --- a/ogr/services/pagure/project.py +++ b/ogr/services/pagure/project.py @@ -324,12 +324,12 @@ def get_fork(self, create: bool = True) -> Optional["PagureProject"]: if not self.is_forked(): if create: return self.fork_create() - else: - logger.info( - f"Fork of {self.repo}" - " does not exist and we were asked not to create it.", - ) - return None + + logger.info( + f"Fork of {self.repo}" + " does not exist and we were asked not to create it.", + ) + return None return self._construct_fork_project() def exists(self) -> bool: diff --git a/ogr/services/pagure/service.py b/ogr/services/pagure/service.py index 00c89034..2328668a 100644 --- a/ogr/services/pagure/service.py +++ b/ogr/services/pagure/service.py @@ -68,13 +68,12 @@ def __str__(self) -> str: insecure_str = ", insecure=True" if self.insecure else "" readonly_str = ", read_only=True" if self.read_only else "" - str_result = ( + return ( f"PagureService(instance_url='{self.instance_url}'" f"{token_str}" f"{readonly_str}" f"{insecure_str})" ) - return str_result def __eq__(self, o: object) -> bool: if not issubclass(o.__class__, PagureService): @@ -94,12 +93,12 @@ def __hash__(self) -> int: def get_project(self, **kwargs) -> "PagureProject": if "username" in kwargs: return PagureProject(service=self, **kwargs) - else: - return PagureProject( - service=self, - username=self.user.get_username(), - **kwargs, - ) + + return PagureProject( + service=self, + username=self.user.get_username(), + **kwargs, + ) def get_project_from_url(self, url: str) -> "PagureProject": repo_url = parse_git_repo(potential_url=url) @@ -109,13 +108,12 @@ def get_project_from_url(self, url: str) -> "PagureProject": if not repo_url.is_fork: repo_url.username = None - project = self.get_project( + return self.get_project( repo=repo_url.repo, namespace=repo_url.namespace, is_fork=repo_url.is_fork, username=repo_url.username, ) - return project @property def user(self) -> "PagureUser": @@ -318,8 +316,7 @@ def get_error_codes(self): Dictionary with all error codes. """ request_url = self.get_api_url("error_codes") - return_value = self.call_api(request_url) - return return_value + return self.call_api(request_url) def change_token(self, token: str): self._token = token diff --git a/pyproject.toml b/pyproject.toml index a24d52f6..01f020ea 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -77,7 +77,7 @@ select = [ # "PERF",# Perflint "PIE", # flake8-pie # "PT", # flake8-pytest-style, would be nice to enable - # "RET", # flake8-return + "RET", # flake8-return # "RUF", # Ruff-specific rules # "SIM", # flake8-simplify # "UP", # pyupgrade diff --git a/tests/integration/gitlab/base.py b/tests/integration/gitlab/base.py index 2573ea26..6e76e82d 100644 --- a/tests/integration/gitlab/base.py +++ b/tests/integration/gitlab/base.py @@ -19,8 +19,10 @@ def setUp(self): raise OSError( "You are in Requre write mode, please set GITLAB_TOKEN env variables", ) - elif not self.token: + + if not self.token: self.token = "some_token" + self._service = None self._project = None diff --git a/tests/unit/test_github.py b/tests/unit/test_github.py index 2c615775..13ec2cec 100644 --- a/tests/unit/test_github.py +++ b/tests/unit/test_github.py @@ -45,8 +45,7 @@ def github_project(mock_github_repo): @pytest.fixture def mock_pull_request(): def mock_pull_request_factory(id): - mock = flexmock(id=id) - return mock + return flexmock(id=id) return mock_pull_request_factory @@ -54,8 +53,7 @@ def mock_pull_request_factory(id): @pytest.fixture def mock_github_repo(mock_pull_request): def mock_github_repo_factory(): - mock = flexmock(create_pull=mock_pull_request(42)) - return mock + return flexmock(create_pull=mock_pull_request(42)) return mock_github_repo_factory @@ -158,7 +156,7 @@ def test_create_github_check_run_output( @pytest.fixture def github_service_with_multiple_auth_methods(): - service = GithubService( + return GithubService( token="abcdef", github_app_id="123", github_app_private_key="id_rsa", @@ -167,8 +165,6 @@ def github_service_with_multiple_auth_methods(): github_authentication=None, ) - return service - def test_multiple_auth_methods_default_is_tokman( github_service_with_multiple_auth_methods, @@ -188,13 +184,11 @@ def test_set_reset_customized_auth_method(github_service_with_multiple_auth_meth @pytest.fixture def github_service_with_one_auth_method(): - service = GithubService( + return GithubService( tokman_instance_url="http://tokman:8080", github_authentication=None, ) - return service - def test_no_multiple_auth_methods_default_is_tokman( github_service_with_one_auth_method, From f16f117dc7398365c341056a8f08fda0c1f9e71f Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 18:58:51 +0200 Subject: [PATCH 09/16] ci(ruff): enable flake8-simplify Signed-off-by: Matej Focko --- ogr/__init__.py | 6 ++---- ogr/services/gitlab/service.py | 4 +--- pyproject.toml | 2 +- tests/integration/factory/test_factory.py | 19 +++++++++---------- 4 files changed, 13 insertions(+), 18 deletions(-) diff --git a/ogr/__init__.py b/ogr/__init__.py index ff0beba6..3b215011 100644 --- a/ogr/__init__.py +++ b/ogr/__init__.py @@ -5,6 +5,7 @@ Module providing one api for multiple git services (github/gitlab/pagure) """ +import contextlib from importlib.metadata import PackageNotFoundError, distribution from ogr.abstract import AuthMethod @@ -18,11 +19,8 @@ from ogr.services.gitlab import GitlabService from ogr.services.pagure import PagureService -try: +with contextlib.suppress(PackageNotFoundError): __version__ = distribution(__name__).version -except PackageNotFoundError: - # package is not installed - pass __all__ = [ GithubService.__name__, diff --git a/ogr/services/gitlab/service.py b/ogr/services/gitlab/service.py index 40e9047e..cefca898 100644 --- a/ogr/services/gitlab/service.py +++ b/ogr/services/gitlab/service.py @@ -157,9 +157,7 @@ def list_projects( self.gitlab_instance.projects.get(item.attributes["id"]) for item in projects if language - in self.gitlab_instance.projects.get(item.attributes["id"]) - .languages() - .keys() + in self.gitlab_instance.projects.get(item.attributes["id"]).languages() ] else: projects_to_convert = projects diff --git a/pyproject.toml b/pyproject.toml index 01f020ea..d06c0fe5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -79,7 +79,7 @@ select = [ # "PT", # flake8-pytest-style, would be nice to enable "RET", # flake8-return # "RUF", # Ruff-specific rules - # "SIM", # flake8-simplify + "SIM", # flake8-simplify # "UP", # pyupgrade "W", # pycodestyle Warning ] diff --git a/tests/integration/factory/test_factory.py b/tests/integration/factory/test_factory.py index 4d8c68ab..5d5ca75e 100644 --- a/tests/integration/factory/test_factory.py +++ b/tests/integration/factory/test_factory.py @@ -23,16 +23,15 @@ def setUp(self): self.github_token = os.environ.get("GITHUB_TOKEN") self.pagure_token = os.environ.get("PAGURE_TOKEN") self.gitlab_token = os.environ.get("GITLAB_TOKEN") or "some_token" - if not Path(get_datafile_filename(obj=self)).exists(): - if ( - not self.github_token - or not self.pagure_token - or not os.environ.get("GITLAB_TOKEN") - ): - raise OSError( - "You are in requre write mode, please set GITHUB_TOKEN PAGURE_TOKEN" - " GITLAB_TOKEN env variables", - ) + if not Path(get_datafile_filename(obj=self)).exists() and ( + not self.github_token + or not self.pagure_token + or not os.environ.get("GITLAB_TOKEN") + ): + raise OSError( + "You are in requre write mode, please set GITHUB_TOKEN PAGURE_TOKEN" + " GITLAB_TOKEN env variables", + ) @property def github_service(self): From 98d40bfe76078eddbcc8248e9546c3fbc7c4e6e6 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 19:01:46 +0200 Subject: [PATCH 10/16] ci(ruff): enable flake8-pytest-style Signed-off-by: Matej Focko --- pyproject.toml | 2 +- tests/integration/github/test_forks.py | 3 ++- .../integration/github/test_generic_commands.py | 5 +++-- tests/integration/github/test_issues.py | 6 +++--- tests/integration/github/test_service.py | 8 ++++---- .../integration/gitlab/test_generic_commands.py | 5 +++-- tests/integration/gitlab/test_issues.py | 3 ++- tests/integration/pagure/test_forks.py | 8 +++++--- .../integration/pagure/test_generic_commands.py | 5 +++-- tests/integration/pagure/test_issues.py | 3 ++- tests/unit/test_factory.py | 16 ++++++++-------- tests/unit/test_github.py | 16 ++++++++-------- tests/unit/test_parsing.py | 2 +- tests/unit/test_utils.py | 4 ++-- 14 files changed, 47 insertions(+), 39 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index d06c0fe5..743ccb6f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -76,7 +76,7 @@ select = [ "I", # isort # "PERF",# Perflint "PIE", # flake8-pie -# "PT", # flake8-pytest-style, would be nice to enable + "PT", # flake8-pytest-style "RET", # flake8-return # "RUF", # Ruff-specific rules "SIM", # flake8-simplify diff --git a/tests/integration/github/test_forks.py b/tests/integration/github/test_forks.py index e20f068e..16970e9b 100644 --- a/tests/integration/github/test_forks.py +++ b/tests/integration/github/test_forks.py @@ -1,6 +1,7 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT +import pytest from requre.online_replacing import record_requests_for_all_methods from ogr.exceptions import GithubAPIException @@ -19,7 +20,7 @@ def test_nonexisting_fork(self): repo="omfeprkfmwpefmwpefkmwpeofjwepof", is_fork=True, ) - with self.assertRaises(GithubAPIException) as ex: + with pytest.raises(GithubAPIException) as ex: self.ogr_nonexisting_fork.get_description() s = str(ex.exception.__cause__) assert "Not Found" in s diff --git a/tests/integration/github/test_generic_commands.py b/tests/integration/github/test_generic_commands.py index c27d75eb..03c84aaf 100644 --- a/tests/integration/github/test_generic_commands.py +++ b/tests/integration/github/test_generic_commands.py @@ -88,7 +88,7 @@ def test_get_files(self): assert any("python-ogr.spec" in f for f in files) def test_nonexisting_file(self): - with self.assertRaises(FileNotFoundError): + with pytest.raises(FileNotFoundError): self.ogr_project.get_file_content(".blablabla_nonexisting_file") def test_parent_project(self): @@ -104,7 +104,8 @@ def test_commit_flags(self): def test_get_sha_from_branch(self): commit_sha = self.hello_world_project.get_sha_from_branch("test-for-flock") - assert commit_sha and commit_sha.startswith("e2282f3") + assert commit_sha + assert commit_sha.startswith("e2282f3") def test_get_sha_from_branch_non_existing(self): commit_sha = self.hello_world_project.get_sha_from_branch("non-existing") diff --git a/tests/integration/github/test_issues.py b/tests/integration/github/test_issues.py index a25c19e7..32377c22 100644 --- a/tests/integration/github/test_issues.py +++ b/tests/integration/github/test_issues.py @@ -19,7 +19,7 @@ class Issues(GithubTests): description = "This is a description" def test_issue_list(self): - with self.assertRaises(IssueTrackerDisabled): + with pytest.raises(IssueTrackerDisabled): issue_list = self.ogr_fork.get_issue_list() issue_list_all = self.ogr_project.get_issue_list(status=IssueStatus.all) @@ -47,7 +47,7 @@ def test_create_issue(self): assert issue_label.name == label def test_create_private_issue(self): - with self.assertRaises(OperationNotSupported): + with pytest.raises(OperationNotSupported): self.hello_world_project.create_issue( title=self.title, body=self.description, @@ -204,7 +204,7 @@ def test_get_comment(self): assert comment.body == "this is a comment" def test_create_with_disabled_issues(self): - with self.assertRaises(IssueTrackerDisabled): + with pytest.raises(IssueTrackerDisabled): self.hello_world_project.get_fork().create_issue( "Testing issue", "shouldn't be created", diff --git a/tests/integration/github/test_service.py b/tests/integration/github/test_service.py index e3a62e5b..fda040be 100644 --- a/tests/integration/github/test_service.py +++ b/tests/integration/github/test_service.py @@ -22,7 +22,7 @@ def test_project_create(self): repo=name_of_the_repo, namespace=self.service.user.get_username(), ) - with self.assertRaises(GithubException): + with pytest.raises(GithubException): _ = project.github_repo new_project = self.service.project_create(name_of_the_repo) @@ -47,7 +47,7 @@ def test_project_create_with_description(self): repo=name_of_the_repo, namespace=self.service.user.get_username(), ) - with self.assertRaises(GithubException): + with pytest.raises(GithubException): _ = project.github_repo new_project = self.service.project_create( @@ -76,7 +76,7 @@ def test_project_create_in_the_group(self): repo=name_of_the_repo, namespace=namespace_of_the_repo, ) - with self.assertRaises(UnknownObjectException): + with pytest.raises(UnknownObjectException): _ = project.github_repo new_project = self.service.project_create( @@ -103,7 +103,7 @@ def test_project_create_duplicate(self): repo=name_of_the_repo, namespace=self.service.user.get_username(), ) - with self.assertRaises(GithubException): + with pytest.raises(GithubException): _ = project.github_repo self.service.project_create(name_of_the_repo) diff --git a/tests/integration/gitlab/test_generic_commands.py b/tests/integration/gitlab/test_generic_commands.py index 1b71c16c..8c8d49a2 100644 --- a/tests/integration/gitlab/test_generic_commands.py +++ b/tests/integration/gitlab/test_generic_commands.py @@ -70,7 +70,7 @@ def test_get_files(self): assert "README.md" in files def test_nonexisting_file(self): - with self.assertRaises(FileNotFoundError): + with pytest.raises(FileNotFoundError): self.project.get_file_content(".blablabla_nonexisting_file") def test_username(self): @@ -121,7 +121,8 @@ def test_get_git_urls(self): def test_get_sha_from_branch(self): commit_sha = self.project.get_sha_from_branch("change") - assert commit_sha and commit_sha.startswith("d490ec67") + assert commit_sha + assert commit_sha.startswith("d490ec67") def test_get_sha_from_branch_non_existing(self): commit_sha = self.project.get_sha_from_branch("non-existing") diff --git a/tests/integration/gitlab/test_issues.py b/tests/integration/gitlab/test_issues.py index b2906c2f..c030e189 100644 --- a/tests/integration/gitlab/test_issues.py +++ b/tests/integration/gitlab/test_issues.py @@ -1,6 +1,7 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT +import pytest from requre.online_replacing import record_requests_for_all_methods from ogr.abstract import IssueStatus @@ -242,5 +243,5 @@ def test_create_with_disabled_issues(self): namespace="packit-service", repo="private-testing-repo", ) - with self.assertRaises(IssueTrackerDisabled): + with pytest.raises(IssueTrackerDisabled): project.create_issue("Testing issue", "shouldn't be created") diff --git a/tests/integration/pagure/test_forks.py b/tests/integration/pagure/test_forks.py index 9bdf2981..a8337b3e 100644 --- a/tests/integration/pagure/test_forks.py +++ b/tests/integration/pagure/test_forks.py @@ -1,6 +1,7 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT +import pytest from requre.online_replacing import record_requests_for_all_methods from ogr.exceptions import OperationNotSupported, PagureAPIException @@ -17,7 +18,8 @@ def test_fork(self): a = self.ogr_fork.parent assert a is_forked = a.is_forked() - assert is_forked and isinstance(is_forked, bool) + assert is_forked + assert isinstance(is_forked, bool) fork = a.get_fork(create=False) assert fork assert fork.is_fork @@ -37,7 +39,7 @@ def test_nonexisting_fork(self): is_fork=True, ) assert not ogr_project_non_existing_fork.exists() - with self.assertRaises(PagureAPIException) as ex: + with pytest.raises(PagureAPIException) as ex: ogr_project_non_existing_fork.get_description() assert "Project not found" in ex.exception.pagure_error @@ -69,5 +71,5 @@ def test_create_fork(self): assert len(old_forks) == len(new_forks) - 1 def test_create_fork_with_namespace(self): - with self.assertRaises(OperationNotSupported): + with pytest.raises(OperationNotSupported): self.ogr_project.fork_create(namespace="some_random_namespace") diff --git a/tests/integration/pagure/test_generic_commands.py b/tests/integration/pagure/test_generic_commands.py index 9cdddbeb..a3dd4382 100644 --- a/tests/integration/pagure/test_generic_commands.py +++ b/tests/integration/pagure/test_generic_commands.py @@ -91,7 +91,7 @@ def test_get_files(self): assert {"a/b/lib.c", "a/b/main.c", "a/b/some_other_lib.c"}.issubset(files) def test_nonexisting_file(self): - with self.assertRaises(FileNotFoundError) as _: + with pytest.raises(FileNotFoundError) as _: self.ogr_project.get_file_content(".blablabla_nonexisting_file") def test_no_file_server_error(self): @@ -154,7 +154,8 @@ def test_delete(self): def test_get_sha_from_branch(self): commit_sha = self.ogr_project.get_sha_from_branch("testPR") - assert commit_sha and commit_sha.startswith("1b491a6") + assert commit_sha + assert commit_sha.startswith("1b491a6") def test_get_sha_from_branch_non_existing(self): commit_sha = self.ogr_project.get_sha_from_branch("non-existing") diff --git a/tests/integration/pagure/test_issues.py b/tests/integration/pagure/test_issues.py index a4c027be..a627ebc1 100644 --- a/tests/integration/pagure/test_issues.py +++ b/tests/integration/pagure/test_issues.py @@ -1,6 +1,7 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT +import pytest from requre.online_replacing import record_requests_for_all_methods from ogr.abstract import IssueStatus @@ -134,7 +135,7 @@ def test_get_comment(self): assert comment.body == "example issue comment" def test_create_with_disabled_issues(self): - with self.assertRaises(IssueTrackerDisabled): + with pytest.raises(IssueTrackerDisabled): self.ogr_project.get_fork().create_issue( "Testing issue", "shouldn't be created", diff --git a/tests/unit/test_factory.py b/tests/unit/test_factory.py index a77efa04..9654cff8 100644 --- a/tests/unit/test_factory.py +++ b/tests/unit/test_factory.py @@ -16,7 +16,7 @@ @pytest.mark.parametrize( - "url,mapping,result", + ("url", "mapping", "result"), [ ("https://github.com/packit-service/ogr", None, GithubService), ("github.com/packit-service/ogr", None, GithubService), @@ -77,7 +77,7 @@ def test_get_service_class(url, mapping, result): @pytest.mark.parametrize( - "url,mapping", + ("url", "mapping"), [ ("https://unknown.com/packit-service/ogr", None), ("unknown.com/packit-service/ogr", None), @@ -93,7 +93,7 @@ def test_get_service_class_not_found(url, mapping): @pytest.mark.parametrize( - "url,mapping,instances,force_custom_instance,result", + ("url", "mapping", "instances", "force_custom_instance", "result"), [ ( "https://github.com/packit-service/ogr", @@ -289,7 +289,7 @@ def test_get_project(url, mapping, instances, force_custom_instance, result): @pytest.mark.parametrize( - "url,mapping,instances,exc_str", + ("url", "mapping", "instances", "exc_str"), [ ( "https://unknown.com/packit-service/ogr", @@ -345,7 +345,7 @@ def test_get_project_not_found(url, mapping, instances, exc_str): @pytest.mark.parametrize( - "instances_in_dict,result_instances", + ("instances_in_dict", "result_instances"), [ ({}, set()), ({"github.com": {"token": "abcd"}}, {GithubService(token="abcd")}), @@ -402,7 +402,7 @@ def test_get_instances_from_dict(instances_in_dict, result_instances: Set): @pytest.mark.parametrize( - "instances_in_dict,result_instances", + ("instances_in_dict", "result_instances"), [ ( {"github.com": {"token": "abcd", "github_app_id": "123"}}, @@ -458,7 +458,7 @@ def test_get_instances_from_dict_multiple_auth(instances_in_dict, result_instanc @pytest.mark.parametrize( - "instances_in_dict,result_max_retries_total", + ("instances_in_dict", "result_max_retries_total"), [ ( { @@ -518,7 +518,7 @@ def test_get_github_instance_with_retries(instances_in_dict, result_max_retries_ @pytest.mark.parametrize( - "instances_in_dict,error_str", + ("instances_in_dict", "error_str"), [ ({"unknown": {"token": "abcd"}}, "No matching service was found for url"), ( diff --git a/tests/unit/test_github.py b/tests/unit/test_github.py index 13ec2cec..3735560e 100644 --- a/tests/unit/test_github.py +++ b/tests/unit/test_github.py @@ -20,7 +20,7 @@ from ogr.services.github.pull_request import GithubPullRequest -@pytest.fixture +@pytest.fixture() def github_project(mock_github_repo): github_project = GithubProject( repo="test_repo", @@ -42,7 +42,7 @@ def github_project(mock_github_repo): return github_project -@pytest.fixture +@pytest.fixture() def mock_pull_request(): def mock_pull_request_factory(id): return flexmock(id=id) @@ -50,7 +50,7 @@ def mock_pull_request_factory(id): return mock_pull_request_factory -@pytest.fixture +@pytest.fixture() def mock_github_repo(mock_pull_request): def mock_github_repo_factory(): return flexmock(create_pull=mock_pull_request(42)) @@ -122,8 +122,8 @@ def test_hostname(self): @pytest.mark.parametrize( - "title, summary, text, expected", - ( + ("title", "summary", "text", "expected"), + [ ( "test", "test summary", @@ -143,7 +143,7 @@ def test_hostname(self): "text": "# Random title\n\n- [ ] TODO list\n---\n_italics_", }, ), - ), + ], ) def test_create_github_check_run_output( title: str, @@ -154,7 +154,7 @@ def test_create_github_check_run_output( assert create_github_check_run_output(title, summary, text) == expected -@pytest.fixture +@pytest.fixture() def github_service_with_multiple_auth_methods(): return GithubService( token="abcdef", @@ -182,7 +182,7 @@ def test_set_reset_customized_auth_method(github_service_with_multiple_auth_meth assert isinstance(service.authentication, Tokman) -@pytest.fixture +@pytest.fixture() def github_service_with_one_auth_method(): return GithubService( tokman_instance_url="http://tokman:8080", diff --git a/tests/unit/test_parsing.py b/tests/unit/test_parsing.py index f77cd6d0..c5d0f91f 100644 --- a/tests/unit/test_parsing.py +++ b/tests/unit/test_parsing.py @@ -7,7 +7,7 @@ @pytest.mark.parametrize( - "url,expected", + ("url", "expected"), [ ( "https://host.name/namespace/repo", diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index 7e2ec301..7ccc319d 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -48,7 +48,7 @@ def test_filter_comments_empty(): @pytest.mark.parametrize( - "filter_str,number_of_result", + ("filter_str", "number_of_result"), [ ("unknown", 0), ("def", 1), @@ -63,7 +63,7 @@ def test_filter_comments(comments, filter_str, number_of_result): @pytest.mark.parametrize( - "filter_str,starts_with,number_of_groups", + ("filter_str", "starts_with", "number_of_groups"), [ ("unknown", None, 0), ("def", "Abc", 1), From 2cd1c6ac27cf1a42bfb51a89b2db5612b6800fac Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 19:02:07 +0200 Subject: [PATCH 11/16] ci(ruff): enable pyupgrade Signed-off-by: Matej Focko --- ogr/abstract.py | 79 ++++++++++++++--------------- ogr/exceptions.py | 4 +- ogr/factory.py | 19 +++---- ogr/parsing.py | 8 +-- ogr/services/base.py | 10 ++-- ogr/services/github/check_run.py | 10 ++-- ogr/services/github/comments.py | 4 +- ogr/services/github/flag.py | 3 +- ogr/services/github/issue.py | 14 ++--- ogr/services/github/project.py | 44 ++++++++-------- ogr/services/github/pull_request.py | 10 ++-- ogr/services/github/release.py | 4 +- ogr/services/github/service.py | 10 ++-- ogr/services/github/user.py | 6 +-- ogr/services/gitlab/comments.py | 4 +- ogr/services/gitlab/flag.py | 3 +- ogr/services/gitlab/issue.py | 16 +++--- ogr/services/gitlab/project.py | 46 ++++++++--------- ogr/services/gitlab/pull_request.py | 12 ++--- ogr/services/gitlab/release.py | 4 +- ogr/services/gitlab/service.py | 4 +- ogr/services/gitlab/user.py | 5 +- ogr/services/pagure/comments.py | 4 +- ogr/services/pagure/flag.py | 6 +-- ogr/services/pagure/issue.py | 18 +++---- ogr/services/pagure/project.py | 49 +++++++++--------- ogr/services/pagure/pull_request.py | 12 ++--- ogr/services/pagure/release.py | 4 +- ogr/services/pagure/service.py | 6 +-- ogr/services/pagure/user.py | 5 +- ogr/utils.py | 23 +++++---- pyproject.toml | 2 +- tests/unit/test_factory.py | 3 +- 33 files changed, 223 insertions(+), 228 deletions(-) diff --git a/ogr/abstract.py b/ogr/abstract.py index fa8b618c..6a493cb2 100644 --- a/ogr/abstract.py +++ b/ogr/abstract.py @@ -3,16 +3,13 @@ import datetime import functools +from collections.abc import Sequence from enum import Enum, IntEnum +from re import Match from typing import ( Any, Callable, - Dict, - List, - Match, Optional, - Sequence, - Set, TypeVar, Union, ) @@ -236,7 +233,7 @@ def edited(self) -> datetime.datetime: """Datetime of last edit of the comment.""" return self._edited - def get_reactions(self) -> List[Reaction]: + def get_reactions(self) -> list[Reaction]: """Returns list of reactions.""" raise NotImplementedError() @@ -334,7 +331,7 @@ def created(self) -> datetime.datetime: raise NotImplementedError() @property - def labels(self) -> List: + def labels(self) -> list: """Labels of the issue.""" raise NotImplementedError() @@ -359,8 +356,8 @@ def create( title: str, body: str, private: Optional[bool] = None, - labels: Optional[List[str]] = None, - assignees: Optional[List[str]] = None, + labels: Optional[list[str]] = None, + assignees: Optional[list[str]] = None, ) -> "Issue": """ Open new issue. @@ -407,8 +404,8 @@ def get_list( status: IssueStatus = IssueStatus.open, author: Optional[str] = None, assignee: Optional[str] = None, - labels: Optional[List[str]] = None, - ) -> List["Issue"]: + labels: Optional[list[str]] = None, + ) -> list["Issue"]: """ List of issues. @@ -433,7 +430,7 @@ def get_list( """ raise NotImplementedError() - def _get_all_comments(self) -> List[IssueComment]: + def _get_all_comments(self) -> list[IssueComment]: """ Get list of all issue comments. @@ -447,7 +444,7 @@ def get_comments( filter_regex: str = None, reverse: bool = False, author: str = None, - ) -> List[IssueComment]: + ) -> list[IssueComment]: """ Get list of issue comments. @@ -626,7 +623,7 @@ def created(self) -> datetime.datetime: raise NotImplementedError() @property - def labels(self) -> List[Any]: + def labels(self) -> list[Any]: """Labels of the pull request.""" raise NotImplementedError() @@ -743,7 +740,7 @@ def get(project: Any, id: int) -> "PullRequest": raise NotImplementedError() @staticmethod - def get_list(project: Any, status: PRStatus = PRStatus.open) -> List["PullRequest"]: + def get_list(project: Any, status: PRStatus = PRStatus.open) -> list["PullRequest"]: """ List of pull requests. @@ -779,7 +776,7 @@ def update_info( """ raise NotImplementedError() - def _get_all_comments(self) -> List[PRComment]: + def _get_all_comments(self) -> list[PRComment]: """ Get list of all pull request comments. @@ -793,7 +790,7 @@ def get_comments( filter_regex: Optional[str] = None, reverse: bool = False, author: Optional[str] = None, - ) -> List["PRComment"]: + ) -> list["PRComment"]: """ Get list of pull request comments. @@ -814,7 +811,7 @@ def get_comments( """ raise NotImplementedError() - def get_all_commits(self) -> List[str]: + def get_all_commits(self) -> list[str]: """ Returns: List of commit hashes of commits in pull request. @@ -898,7 +895,7 @@ def add_label(self, *labels: str) -> None: """ raise NotImplementedError() - def get_statuses(self) -> List["CommitFlag"]: + def get_statuses(self) -> list["CommitFlag"]: """ Returns statuses for latest commit on pull request. @@ -921,7 +918,7 @@ def get_comment(self, comment_id: int) -> PRComment: class CommitFlag(OgrAbstractClass): - _states: Dict[str, CommitStatus] = {} + _states: dict[str, CommitStatus] = {} def __init__( self, @@ -987,7 +984,7 @@ def _from_raw_commit_flag(self) -> None: raise NotImplementedError() @staticmethod - def get(project: Any, commit: str) -> List["CommitFlag"]: + def get(project: Any, commit: str) -> list["CommitFlag"]: """ Acquire commit statuses for given commit in the project. @@ -1196,7 +1193,7 @@ def get_latest(project: Any) -> Optional["Release"]: raise NotImplementedError() @staticmethod - def get_list(project: Any) -> List["Release"]: + def get_list(project: Any) -> list["Release"]: """ Returns: List of the objects that represent releases. @@ -1358,7 +1355,7 @@ def list_projects( user: str = None, search_pattern: str = None, language: str = None, - ) -> List["GitProject"]: + ) -> list["GitProject"]: """ List projects for given criteria. @@ -1460,7 +1457,7 @@ def has_issues(self) -> bool: """`True` if issues are enabled on the project.""" raise NotImplementedError() - def get_branches(self) -> List[str]: + def get_branches(self) -> list[str]: """ Returns: List with names of branches in the project. @@ -1492,28 +1489,28 @@ def get_fork(self, create: bool = True) -> Optional["GitProject"]: """ raise NotImplementedError() - def get_owners(self) -> List[str]: + def get_owners(self) -> list[str]: """ Returns: List of usernames of project owners. """ raise NotImplementedError() - def who_can_close_issue(self) -> Set[str]: + def who_can_close_issue(self) -> set[str]: """ Returns: Names of all users who have permission to modify an issue. """ raise NotImplementedError() - def who_can_merge_pr(self) -> Set[str]: + def who_can_merge_pr(self) -> set[str]: """ Returns: Names of all users who have permission to modify pull request. """ raise NotImplementedError() - def which_groups_can_merge_pr(self) -> Set[str]: + def which_groups_can_merge_pr(self) -> set[str]: """ Returns: Names of all groups that have permission to modify pull request. @@ -1580,8 +1577,8 @@ def get_issue_list( status: IssueStatus = IssueStatus.open, author: Optional[str] = None, assignee: Optional[str] = None, - labels: Optional[List[str]] = None, - ) -> List["Issue"]: + labels: Optional[list[str]] = None, + ) -> list["Issue"]: """ List of issues. @@ -1634,8 +1631,8 @@ def create_issue( title: str, body: str, private: Optional[bool] = None, - labels: Optional[List[str]] = None, - assignees: Optional[List[str]] = None, + labels: Optional[list[str]] = None, + assignees: Optional[list[str]] = None, ) -> Issue: """ Open new issue. @@ -1664,7 +1661,7 @@ def create_issue( """ raise NotImplementedError() - def get_pr_list(self, status: PRStatus = PRStatus.open) -> List["PullRequest"]: + def get_pr_list(self, status: PRStatus = PRStatus.open) -> list["PullRequest"]: """ List of pull requests. @@ -1690,7 +1687,7 @@ def get_pr(self, pr_id: int) -> "PullRequest": """ raise NotImplementedError() - def get_tags(self) -> List["GitTag"]: + def get_tags(self) -> list["GitTag"]: """ Returns: List of objects that represent tags. @@ -1739,7 +1736,7 @@ def get_latest_release(self) -> Optional[Release]: """ raise NotImplementedError() - def get_releases(self) -> List[Release]: + def get_releases(self) -> list[Release]: """ Returns: List of the objects that represent releases. @@ -1820,7 +1817,7 @@ def commit_comment( """ raise NotImplementedError() - def get_commit_comments(self, commit: str) -> List[CommitComment]: + def get_commit_comments(self, commit: str) -> list[CommitComment]: """ Get comments for a commit. @@ -1859,7 +1856,7 @@ def set_commit_status( """ raise NotImplementedError() - def get_commit_statuses(self, commit: str) -> List[CommitFlag]: + def get_commit_statuses(self, commit: str) -> list[CommitFlag]: """ Get statuses of the commit. @@ -1871,7 +1868,7 @@ def get_commit_statuses(self, commit: str) -> List[CommitFlag]: """ raise NotImplementedError() - def get_git_urls(self) -> Dict[str, str]: + def get_git_urls(self) -> dict[str, str]: """ Get git URLs for the project. @@ -1930,7 +1927,7 @@ def get_files( ref: str = None, filter_regex: str = None, recursive: bool = False, - ) -> List[str]: + ) -> list[str]: """ Get a list of file paths of the repo. @@ -1972,14 +1969,14 @@ def get_sha_from_branch(self, branch: str) -> Optional[str]: """ raise NotImplementedError() - def get_contributors(self) -> Set[str]: + def get_contributors(self) -> set[str]: """ Returns: Set of all contributors to the given project. """ raise NotImplementedError() - def users_with_write_access(self) -> Set[str]: + def users_with_write_access(self) -> set[str]: """ Returns: List of users who have write access to the project diff --git a/ogr/exceptions.py b/ogr/exceptions.py index 9e261b90..d0b12772 100644 --- a/ogr/exceptions.py +++ b/ogr/exceptions.py @@ -1,7 +1,7 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from typing import Any, Dict, Optional +from typing import Any, Optional import github import gitlab @@ -26,7 +26,7 @@ def __init__( self, *args: Any, pagure_error: Optional[str] = None, - pagure_response: Optional[Dict[str, Any]] = None, + pagure_response: Optional[dict[str, Any]] = None, response_code: Optional[int] = None, ) -> None: super().__init__(*args) diff --git a/ogr/factory.py b/ogr/factory.py index 6d379308..81829fce 100644 --- a/ogr/factory.py +++ b/ogr/factory.py @@ -2,13 +2,14 @@ # SPDX-License-Identifier: MIT import functools -from typing import Dict, Iterable, Optional, Set, Type +from collections.abc import Iterable +from typing import Optional from ogr.abstract import GitProject, GitService from ogr.exceptions import OgrException from ogr.parsing import parse_git_repo -_SERVICE_MAPPING: Dict[str, Type[GitService]] = {} +_SERVICE_MAPPING: dict[str, type[GitService]] = {} def use_for_service(service: str, _func=None): @@ -42,7 +43,7 @@ class PagureService(BaseGitService): def decorator_cover(func): @functools.wraps(func) - def covered_func(kls: Type[GitService]): + def covered_func(kls: type[GitService]): _SERVICE_MAPPING[service] = kls return kls @@ -53,7 +54,7 @@ def covered_func(kls: Type[GitService]): def get_project( url, - service_mapping_update: Dict[str, Type[GitService]] = None, + service_mapping_update: dict[str, type[GitService]] = None, custom_instances: Iterable[GitService] = None, force_custom_instance: bool = True, **kwargs, @@ -111,8 +112,8 @@ def get_project( def get_service_class_or_none( url: str, - service_mapping_update: Dict[str, Type[GitService]] = None, -) -> Optional[Type[GitService]]: + service_mapping_update: dict[str, type[GitService]] = None, +) -> Optional[type[GitService]]: """ Get the matching service class from the URL. @@ -141,8 +142,8 @@ def get_service_class_or_none( def get_service_class( url: str, - service_mapping_update: Dict[str, Type[GitService]] = None, -) -> Type[GitService]: + service_mapping_update: dict[str, type[GitService]] = None, +) -> type[GitService]: """ Get the matching service class from the URL. @@ -165,7 +166,7 @@ def get_service_class( raise OgrException("No matching service was found.") -def get_instances_from_dict(instances: Dict) -> Set[GitService]: +def get_instances_from_dict(instances: dict) -> set[GitService]: """ Load the service instances from the dictionary in the following form: diff --git a/ogr/parsing.py b/ogr/parsing.py index 5e3cc507..17923780 100644 --- a/ogr/parsing.py +++ b/ogr/parsing.py @@ -1,7 +1,7 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from typing import List, Optional, Tuple +from typing import Optional from urllib.parse import ParseResult, urlparse @@ -121,7 +121,7 @@ def _parse_username(self, parsed: ParseResult) -> bool: return True @staticmethod - def _prepare_path(parsed: ParseResult) -> Tuple[str, List[str]]: + def _prepare_path(parsed: ParseResult) -> tuple[str, list[str]]: # path starts with '/', strip it away path = parsed.path.lstrip("/") @@ -131,7 +131,7 @@ def _prepare_path(parsed: ParseResult) -> Tuple[str, List[str]]: return path, path.split("/") - def _check_fork(self, splits: List[str]) -> List[str]: + def _check_fork(self, splits: list[str]) -> list[str]: if self.is_fork: # we got pagure fork but SSH url self.username = splits[0] @@ -154,7 +154,7 @@ def _check_fork(self, splits: List[str]) -> List[str]: self.username = splits[0] return splits[:-1] - def _parsed_path(self, path: str, splits: List[str]) -> Optional["RepoUrl"]: + def _parsed_path(self, path: str, splits: list[str]) -> Optional["RepoUrl"]: if len(splits) == 1: self.namespace = self.username self.repo = path diff --git a/ogr/services/base.py b/ogr/services/base.py index 365eb186..02f38886 100644 --- a/ogr/services/base.py +++ b/ogr/services/base.py @@ -1,7 +1,7 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from typing import Any, List, Optional +from typing import Any, Optional from urllib.request import urlopen from ogr.abstract import ( @@ -67,7 +67,7 @@ def search( reverse: bool = False, description: bool = True, ): - all_comments: List[Any] = self.get_comments(reverse=reverse) + all_comments: list[Any] = self.get_comments(reverse=reverse) if description: description_content = self.description if reverse: @@ -77,7 +77,7 @@ def search( return search_in_comments(comments=all_comments, filter_regex=filter_regex) - def get_statuses(self) -> List[CommitFlag]: + def get_statuses(self) -> list[CommitFlag]: commit = self.get_all_commits()[-1] return self.target_project.get_commit_statuses(commit) @@ -92,8 +92,8 @@ def get_comments( filter_regex: str = None, reverse: bool = False, author: str = None, - ) -> List[IssueComment]: - all_comments: List[IssueComment] = self._get_all_comments() + ) -> list[IssueComment]: + all_comments: list[IssueComment] = self._get_all_comments() return filter_comments(all_comments, filter_regex, reverse, author) def can_close(self, username: str) -> bool: diff --git a/ogr/services/github/check_run.py b/ogr/services/github/check_run.py index 245537a5..2f45306c 100644 --- a/ogr/services/github/check_run.py +++ b/ogr/services/github/check_run.py @@ -3,7 +3,7 @@ import datetime from enum import Enum -from typing import Any, Dict, List, Optional, Union +from typing import Any, Optional, Union from github.CheckRun import CheckRun from github.CheckRunOutput import CheckRunOutput @@ -14,7 +14,7 @@ from ogr.exceptions import OperationNotSupported from ogr.services import github as ogr_github -GithubCheckRunOutput = Dict[str, Union[str, List[Dict[str, Union[str, int]]]]] +GithubCheckRunOutput = dict[str, Union[str, list[dict[str, Union[str, int]]]]] class GithubCheckRunStatus(Enum): @@ -59,7 +59,7 @@ def create_github_check_run_output( title: str, summary: str, text: Optional[str] = None, - annotations: Optional[List[Dict[str, Union[str, int]]]] = None, + annotations: Optional[list[dict[str, Union[str, int]]]] = None, ) -> GithubCheckRunOutput: """ Helper function for constructing valid GitHub output for check run. @@ -236,7 +236,7 @@ def get_list( commit_sha: str, name: Optional[str] = None, status: Optional[GithubCheckRunStatus] = None, - ) -> List["GithubCheckRun"]: + ) -> list["GithubCheckRun"]: """ Returns list of GitHub check runs. @@ -317,7 +317,7 @@ def create( conclusion: Optional[GithubCheckRunResult] = None, completed_at: Optional[datetime.datetime] = None, output: Optional[GithubCheckRunOutput] = None, - actions: Optional[List[Dict[str, str]]] = None, + actions: Optional[list[dict[str, str]]] = None, ) -> "GithubCheckRun": """ Creates new check run. diff --git a/ogr/services/github/comments.py b/ogr/services/github/comments.py index a6ffd4e0..d5449cc0 100644 --- a/ogr/services/github/comments.py +++ b/ogr/services/github/comments.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import List, Union +from typing import Union from github.IssueComment import IssueComment as _GithubIssueComment from github.PullRequestComment import PullRequestComment as _GithubPullRequestComment @@ -43,7 +43,7 @@ def body(self, new_body: str) -> None: def edited(self) -> datetime.datetime: return self._raw_comment.updated_at - def get_reactions(self) -> List[Reaction]: + def get_reactions(self) -> list[Reaction]: return [ GithubReaction(reaction) for reaction in self._raw_comment.get_reactions() ] diff --git a/ogr/services/github/flag.py b/ogr/services/github/flag.py index 8cf9c2da..df20a5f6 100644 --- a/ogr/services/github/flag.py +++ b/ogr/services/github/flag.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: MIT import datetime -from typing import List from github import UnknownObjectException @@ -30,7 +29,7 @@ def _from_raw_commit_flag(self): self.uid = self._raw_commit_flag.id @staticmethod - def get(project: "ogr_github.GithubProject", commit: str) -> List["CommitFlag"]: + def get(project: "ogr_github.GithubProject", commit: str) -> list["CommitFlag"]: statuses = project.github_repo.get_commit(commit).get_statuses() try: diff --git a/ogr/services/github/issue.py b/ogr/services/github/issue.py index 3fbf5530..6095e66d 100644 --- a/ogr/services/github/issue.py +++ b/ogr/services/github/issue.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import Dict, List, Optional, Union +from typing import Optional, Union import github from github import UnknownObjectException @@ -75,7 +75,7 @@ def created(self) -> datetime.datetime: return self._raw_issue.created_at @property - def labels(self) -> List: + def labels(self) -> list: return list(self._raw_issue.get_labels()) def __str__(self) -> str: @@ -87,7 +87,7 @@ def create( title: str, body: str, private: Optional[bool] = None, - labels: Optional[List[str]] = None, + labels: Optional[list[str]] = None, assignees: Optional[list] = None, ) -> "Issue": if private: @@ -120,12 +120,12 @@ def get_list( status: IssueStatus = IssueStatus.open, author: Optional[str] = None, assignee: Optional[str] = None, - labels: Optional[List[str]] = None, - ) -> List["Issue"]: + labels: Optional[list[str]] = None, + ) -> list["Issue"]: if not project.has_issues: raise IssueTrackerDisabled() - parameters: Dict[str, Union[str, List[str]]] = { + parameters: dict[str, Union[str, list[str]]] = { "state": status.name, "sort": "updated", "direction": "desc", @@ -149,7 +149,7 @@ def get_list( except UnknownObjectException: return [] - def _get_all_comments(self) -> List[IssueComment]: + def _get_all_comments(self) -> list[IssueComment]: return [ GithubIssueComment(parent=self, raw_comment=raw_comment) for raw_comment in self._raw_issue.get_comments() diff --git a/ogr/services/github/project.py b/ogr/services/github/project.py index f3969e89..f017a23d 100644 --- a/ogr/services/github/project.py +++ b/ogr/services/github/project.py @@ -3,7 +3,7 @@ import datetime import logging -from typing import Dict, List, Optional, Set, Union +from typing import Optional, Union import github from github import UnknownObjectException @@ -160,7 +160,7 @@ def parent(self) -> Optional["GithubProject"]: def default_branch(self): return self.github_repo.default_branch - def get_branches(self) -> List[str]: + def get_branches(self) -> list[str]: return [branch.name for branch in self.github_repo.get_branches()] def get_description(self) -> str: @@ -205,11 +205,11 @@ def get_fork(self, create: bool = True) -> Optional["GithubProject"]: return None return self._construct_fork_project() - def get_owners(self) -> List[str]: + def get_owners(self) -> list[str]: # in case of github, repository has only one owner return [self.github_repo.owner.login] - def __get_collaborators(self) -> Set[str]: + def __get_collaborators(self) -> set[str]: try: collaborators = self._get_collaborators_with_permission() except github.GithubException: @@ -225,10 +225,10 @@ def __get_collaborators(self) -> Set[str]: return set(usernames) - def who_can_close_issue(self) -> Set[str]: + def who_can_close_issue(self) -> set[str]: return self.__get_collaborators() - def who_can_merge_pr(self) -> Set[str]: + def who_can_merge_pr(self) -> set[str]: return self.__get_collaborators() def can_merge_pr(self, username) -> bool: @@ -257,8 +257,8 @@ def get_issue_list( status: IssueStatus = IssueStatus.open, author: Optional[str] = None, assignee: Optional[str] = None, - labels: Optional[List[str]] = None, - ) -> List[Issue]: + labels: Optional[list[str]] = None, + ) -> list[Issue]: pass @indirect(GithubIssue.get) @@ -271,8 +271,8 @@ def create_issue( title: str, body: str, private: Optional[bool] = None, - labels: Optional[List[str]] = None, - assignees: Optional[List[str]] = None, + labels: Optional[list[str]] = None, + assignees: Optional[list[str]] = None, ) -> Issue: pass @@ -280,7 +280,7 @@ def delete(self) -> None: self.github_repo.delete() @indirect(GithubPullRequest.get_list) - def get_pr_list(self, status: PRStatus = PRStatus.open) -> List[PullRequest]: + def get_pr_list(self, status: PRStatus = PRStatus.open) -> list[PullRequest]: pass @indirect(GithubPullRequest.get) @@ -355,7 +355,7 @@ def _commit_comment_from_github_object( sha=raw_commit_coment.commit_id, ) - def get_commit_comments(self, commit: str) -> List[CommitComment]: + def get_commit_comments(self, commit: str) -> list[CommitComment]: github_commit: Commit = self.github_repo.get_commit(commit) return [ self._commit_comment_from_github_object(comment) @@ -379,7 +379,7 @@ def set_commit_status( pass @indirect(GithubCommitFlag.get) - def get_commit_statuses(self, commit: str) -> List[CommitFlag]: + def get_commit_statuses(self, commit: str) -> list[CommitFlag]: pass @indirect(GithubCheckRun.get) @@ -402,7 +402,7 @@ def create_check_run( conclusion: Optional[GithubCheckRunResult] = None, completed_at: Optional[datetime.datetime] = None, output: Optional[GithubCheckRunOutput] = None, - actions: Optional[List[Dict[str, str]]] = None, + actions: Optional[list[dict[str, str]]] = None, ) -> "GithubCheckRun": pass @@ -412,10 +412,10 @@ def get_check_runs( commit_sha: str, name: Optional[str] = None, status: Optional[GithubCheckRunStatus] = None, - ) -> List["GithubCheckRun"]: + ) -> list["GithubCheckRun"]: pass - def get_git_urls(self) -> Dict[str, str]: + def get_git_urls(self) -> dict[str, str]: return {"git": self.github_repo.clone_url, "ssh": self.github_repo.ssh_url} @if_readonly(return_function=GitProjectReadOnly.fork_create) @@ -450,7 +450,7 @@ def get_files( ref: str = None, filter_regex: str = None, recursive: bool = False, - ) -> List[str]: + ) -> list[str]: ref = ref or self.default_branch paths = [] contents = self.github_repo.get_contents(path="", ref=ref) @@ -525,14 +525,14 @@ def get_latest_release(self) -> Optional[GithubRelease]: pass @indirect(GithubRelease.get_list) - def get_releases(self) -> List[Release]: + def get_releases(self) -> list[Release]: pass @indirect(GithubRelease.create) def create_release(self, tag: str, name: str, message: str) -> GithubRelease: pass - def get_forks(self) -> List["GithubProject"]: + def get_forks(self) -> list["GithubProject"]: return [ self.service.get_project_from_github_repository(fork) for fork in self.github_repo.get_forks() @@ -542,7 +542,7 @@ def get_forks(self) -> List["GithubProject"]: def get_web_url(self) -> str: return self.github_repo.html_url - def get_tags(self) -> List["GitTag"]: + def get_tags(self) -> list["GitTag"]: return [GitTag(tag.name, tag.commit.sha) for tag in self.github_repo.get_tags()] def get_sha_from_branch(self, branch: str) -> Optional[str]: @@ -553,12 +553,12 @@ def get_sha_from_branch(self, branch: str) -> Optional[str]: return None raise GithubAPIException from ex - def get_contributors(self) -> Set[str]: + def get_contributors(self) -> set[str]: """ Returns: Logins of contributors to the project. """ return {c.login for c in self.github_repo.get_contributors()} - def users_with_write_access(self) -> Set[str]: + def users_with_write_access(self) -> set[str]: return self.__get_collaborators() diff --git a/ogr/services/github/pull_request.py b/ogr/services/github/pull_request.py index da884e17..c1f9c4bc 100644 --- a/ogr/services/github/pull_request.py +++ b/ogr/services/github/pull_request.py @@ -3,7 +3,7 @@ import datetime import logging -from typing import List, Optional, Union +from typing import Optional, Union import github import requests @@ -77,7 +77,7 @@ def created(self) -> datetime.datetime: return self._raw_pr.created_at @property - def labels(self) -> List[GithubLabel]: + def labels(self) -> list[GithubLabel]: return list(self._raw_pr.get_labels()) @property @@ -190,7 +190,7 @@ def get(project: "ogr_github.GithubProject", pr_id: int) -> "PullRequest": def get_list( project: "ogr_github.GithubProject", status: PRStatus = PRStatus.open, - ) -> List["PullRequest"]: + ) -> 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", @@ -220,13 +220,13 @@ def update_info( except Exception as ex: raise GithubAPIException("there was an error while updating the PR") from ex - def _get_all_comments(self) -> List[PRComment]: + def _get_all_comments(self) -> list[PRComment]: return [ GithubPRComment(parent=self, raw_comment=raw_comment) for raw_comment in self._raw_pr.get_issue_comments() ] - def get_all_commits(self) -> List[str]: + def get_all_commits(self) -> list[str]: return [commit.sha for commit in self._raw_pr.get_commits()] def comment( diff --git a/ogr/services/github/release.py b/ogr/services/github/release.py index 7d263599..cf406d21 100644 --- a/ogr/services/github/release.py +++ b/ogr/services/github/release.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import List, Optional +from typing import Optional from github import GithubException from github.GitRelease import GitRelease as PyGithubRelease @@ -96,7 +96,7 @@ def get_latest(project: "ogr_github.GithubProject") -> Optional["Release"]: raise GithubAPIException from ex @staticmethod - def get_list(project: "ogr_github.GithubProject") -> List["Release"]: + def get_list(project: "ogr_github.GithubProject") -> list["Release"]: releases = project.github_repo.get_releases() return [GithubRelease(release, project) for release in releases] diff --git a/ogr/services/github/service.py b/ogr/services/github/service.py index bfb09765..f569e7b8 100644 --- a/ogr/services/github/service.py +++ b/ogr/services/github/service.py @@ -3,7 +3,7 @@ import logging import re -from typing import Dict, List, Optional, Type, Union +from typing import Optional, Union import github import github.GithubObject @@ -37,7 +37,7 @@ @use_for_service("github.com") class GithubService(BaseGitService): # class parameter could be used to mock Github class api - github_class: Type[github.Github] + github_class: type[github.Github] instance_url = "https://github.com" def __init__( @@ -62,7 +62,7 @@ def __init__( self.read_only = read_only self._default_auth_method = github_authentication self._other_auth_method: GithubAuthentication = None - self._auth_methods: Dict[AuthMethod, GithubAuthentication] = {} + self._auth_methods: dict[AuthMethod, GithubAuthentication] = {} if isinstance(max_retries, Retry): self._max_retries = max_retries @@ -221,7 +221,7 @@ def list_projects( user: str = None, search_pattern: str = None, language: str = None, - ) -> List[GitProject]: + ) -> list[GitProject]: search_query = "" if user: @@ -230,7 +230,7 @@ def list_projects( if language: search_query += f" language:{language}" - projects: List[GitProject] + projects: list[GitProject] projects = [ GithubProject( repo=repo.name, diff --git a/ogr/services/github/user.py b/ogr/services/github/user.py index 20ed1543..221c9a3e 100644 --- a/ogr/services/github/user.py +++ b/ogr/services/github/user.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT from collections import namedtuple -from typing import List, Optional +from typing import Optional from ogr.services import github as ogr_github from ogr.services.base import BaseGitUser @@ -48,7 +48,7 @@ def get_email(self) -> Optional[str]: # Return the first email we received return user_emails[0]["email"] - def get_projects(self) -> List["ogr_github.GithubProject"]: + def get_projects(self) -> list["ogr_github.GithubProject"]: raw_repos = self._github_user.get_repos(affiliation="owner") return [ GithubProject( @@ -60,5 +60,5 @@ def get_projects(self) -> List["ogr_github.GithubProject"]: for repo in raw_repos ] - def get_forks(self) -> List["ogr_github.GithubProject"]: + def get_forks(self) -> list["ogr_github.GithubProject"]: return [project for project in self.get_projects() if project.github_repo.fork] diff --git a/ogr/services/gitlab/comments.py b/ogr/services/gitlab/comments.py index 7dc7fb54..7d39c1da 100644 --- a/ogr/services/gitlab/comments.py +++ b/ogr/services/gitlab/comments.py @@ -3,7 +3,7 @@ import datetime import logging -from typing import List, Union +from typing import Union import gitlab.exceptions from gitlab.v4.objects import ( @@ -52,7 +52,7 @@ def body(self, new_body: str) -> None: def edited(self) -> datetime.datetime: return self._raw_comment.updated_at - def get_reactions(self) -> List[Reaction]: + def get_reactions(self) -> list[Reaction]: return [ GitlabReaction(reaction) for reaction in self._raw_comment.awardemojis.list() diff --git a/ogr/services/gitlab/flag.py b/ogr/services/gitlab/flag.py index 68e8d503..a19c7a62 100644 --- a/ogr/services/gitlab/flag.py +++ b/ogr/services/gitlab/flag.py @@ -3,7 +3,6 @@ import datetime import logging -from typing import List import gitlab @@ -49,7 +48,7 @@ def _from_raw_commit_flag(self): self.url = self._raw_commit_flag.target_url @staticmethod - def get(project: "ogr_gitlab.GitlabProject", commit: str) -> List["CommitFlag"]: + def get(project: "ogr_gitlab.GitlabProject", commit: str) -> list["CommitFlag"]: try: commit_object = project.gitlab_repo.commits.get(commit) except gitlab.exceptions.GitlabGetError as ex: diff --git a/ogr/services/gitlab/issue.py b/ogr/services/gitlab/issue.py index 8b941e97..90f28ae1 100644 --- a/ogr/services/gitlab/issue.py +++ b/ogr/services/gitlab/issue.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import Dict, List, Optional, Union +from typing import Optional, Union import gitlab from gitlab.v4.objects import Issue as _GitlabIssue @@ -71,7 +71,7 @@ def created(self) -> datetime.datetime: return self._raw_issue.created_at @property - def labels(self) -> List: + def labels(self) -> list: return self._raw_issue.labels def __str__(self) -> str: @@ -83,8 +83,8 @@ def create( title: str, body: str, private: Optional[bool] = None, - labels: Optional[List[str]] = None, - assignees: Optional[List[str]] = None, + labels: Optional[list[str]] = None, + assignees: Optional[list[str]] = None, ) -> "Issue": if not project.has_issues: raise IssueTrackerDisabled() @@ -123,13 +123,13 @@ def get_list( status: IssueStatus = IssueStatus.open, author: Optional[str] = None, assignee: Optional[str] = None, - labels: Optional[List[str]] = None, - ) -> List["Issue"]: + labels: Optional[list[str]] = None, + ) -> list["Issue"]: if not project.has_issues: raise IssueTrackerDisabled() # Gitlab API has status 'opened', not 'open' - parameters: Dict[str, Union[str, List[str], bool]] = { + parameters: dict[str, Union[str, list[str], bool]] = { "state": status.name if status != IssueStatus.open else "opened", "order_by": "updated_at", "sort": "desc", @@ -145,7 +145,7 @@ def get_list( issues = project.gitlab_repo.issues.list(**parameters) return [GitlabIssue(issue, project) for issue in issues] - def _get_all_comments(self) -> List[IssueComment]: + def _get_all_comments(self) -> list[IssueComment]: return [ GitlabIssueComment(parent=self, raw_comment=raw_comment) for raw_comment in self._raw_issue.notes.list(sort="asc", all=True) diff --git a/ogr/services/gitlab/project.py b/ogr/services/gitlab/project.py index ecf995cc..012fc98e 100644 --- a/ogr/services/gitlab/project.py +++ b/ogr/services/gitlab/project.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import logging -from typing import Any, Dict, List, Optional, Set, Union +from typing import Any, Optional, Union import gitlab from gitlab.exceptions import GitlabGetError @@ -154,12 +154,12 @@ def get_fork(self, create: bool = True) -> Optional["GitlabProject"]: return None return self._construct_fork_project() - def get_owners(self) -> List[str]: + def get_owners(self) -> list[str]: return self._get_collaborators_with_given_access( access_levels=[gitlab.const.OWNER_ACCESS], ) - def who_can_close_issue(self) -> Set[str]: + def who_can_close_issue(self) -> set[str]: return set( self._get_collaborators_with_given_access( access_levels=[ @@ -171,7 +171,7 @@ def who_can_close_issue(self) -> Set[str]: ), ) - def who_can_merge_pr(self) -> Set[str]: + def who_can_merge_pr(self) -> set[str]: return set( self._get_collaborators_with_given_access( access_levels=[ @@ -190,8 +190,8 @@ def delete(self) -> None: def _get_collaborators_with_given_access( self, - access_levels: List[int], - ) -> List[str]: + access_levels: list[int], + ) -> list[str]: """ Get all project collaborators with one of the given access levels. Access levels: @@ -249,7 +249,7 @@ def request_access(self) -> None: raise GitlabAPIException("Unable to request access") from e @indirect(GitlabPullRequest.get_list) - def get_pr_list(self, status: PRStatus = PRStatus.open) -> List["PullRequest"]: + def get_pr_list(self, status: PRStatus = PRStatus.open) -> list["PullRequest"]: pass def get_sha_from_tag(self, tag_name: str) -> str: @@ -300,7 +300,7 @@ def _commit_comment_from_gitlab_object(raw_comment, commit) -> CommitComment: author=raw_comment.author["username"], ) - def get_commit_comments(self, commit: str) -> List[CommitComment]: + def get_commit_comments(self, commit: str) -> list[CommitComment]: try: commit_object: ProjectCommit = self.gitlab_repo.commits.get(commit) except gitlab.exceptions.GitlabGetError as ex: @@ -325,10 +325,10 @@ def set_commit_status( pass @indirect(GitlabCommitFlag.get) - def get_commit_statuses(self, commit: str) -> List[CommitFlag]: + def get_commit_statuses(self, commit: str) -> list[CommitFlag]: pass - def get_git_urls(self) -> Dict[str, str]: + def get_git_urls(self) -> dict[str, str]: return { "git": self.gitlab_repo.attributes["http_url_to_repo"], "ssh": self.gitlab_repo.attributes["ssh_url_to_repo"], @@ -356,7 +356,7 @@ def fork_create(self, namespace: Optional[str] = None) -> "GitlabProject": def change_token(self, new_token: str): self.service.change_token(new_token) - def get_branches(self) -> List[str]: + def get_branches(self) -> list[str]: return [branch.name for branch in self.gitlab_repo.branches.list(all=True)] def get_file_content(self, path, ref=None) -> str: @@ -374,7 +374,7 @@ def get_files( ref: str = None, filter_regex: str = None, recursive: bool = False, - ) -> List[str]: + ) -> list[str]: ref = ref or self.default_branch paths = [ file_dict["path"] @@ -396,8 +396,8 @@ def get_issue_list( status: IssueStatus = IssueStatus.open, author: Optional[str] = None, assignee: Optional[str] = None, - labels: Optional[List[str]] = None, - ) -> List[Issue]: + labels: Optional[list[str]] = None, + ) -> list[Issue]: pass @indirect(GitlabIssue.get) @@ -410,8 +410,8 @@ def create_issue( title: str, body: str, private: Optional[bool] = None, - labels: Optional[List[str]] = None, - assignees: Optional[List[str]] = None, + labels: Optional[list[str]] = None, + assignees: Optional[list[str]] = None, ) -> Issue: pass @@ -419,7 +419,7 @@ def create_issue( def get_pr(self, pr_id: int) -> PullRequest: pass - def get_tags(self) -> List["GitTag"]: + def get_tags(self) -> list["GitTag"]: tags = self.gitlab_repo.tags.list() return [GitTag(tag.name, tag.commit["id"]) for tag in tags] @@ -428,7 +428,7 @@ def _git_tag_from_tag_name(self, tag_name: str) -> GitTag: return GitTag(name=git_tag.name, commit_sha=git_tag.commit["id"]) @indirect(GitlabRelease.get_list) - def get_releases(self) -> List[Release]: + def get_releases(self) -> list[Release]: pass @indirect(GitlabRelease.get) @@ -458,7 +458,7 @@ def list_labels(self): """ return list(self.gitlab_repo.labels.list()) - def get_forks(self) -> List["GitlabProject"]: + def get_forks(self) -> list["GitlabProject"]: try: forks = self.gitlab_repo.forks.list() except KeyError as ex: @@ -506,7 +506,7 @@ def update_labels(self, labels): @staticmethod def _normalize_label_color(color): if not color.startswith("#"): - return "#{}".format(color) + return f"#{color}" return color def get_web_url(self) -> str: @@ -520,20 +520,20 @@ def get_sha_from_branch(self, branch: str) -> Optional[str]: return None raise GitlabAPIException from ex - def get_contributors(self) -> Set[str]: + def get_contributors(self) -> set[str]: """ Returns: Unique authors of the commits in the project. """ - def format_contributor(contributor: Dict[str, Any]) -> str: + def format_contributor(contributor: dict[str, Any]) -> str: return f"{contributor['name']} <{contributor['email']}>" return set( map(format_contributor, self.gitlab_repo.repository_contributors(all=True)), ) - def users_with_write_access(self) -> Set[str]: + def users_with_write_access(self) -> set[str]: return set( self._get_collaborators_with_given_access( access_levels=[ diff --git a/ogr/services/gitlab/pull_request.py b/ogr/services/gitlab/pull_request.py index 1846c69d..425798f2 100644 --- a/ogr/services/gitlab/pull_request.py +++ b/ogr/services/gitlab/pull_request.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import Dict, List, Optional +from typing import Optional import gitlab import requests @@ -20,7 +20,7 @@ class GitlabPullRequest(BasePullRequest): _raw_pr: _GitlabMergeRequest _target_project: "ogr_gitlab.GitlabProject" _source_project: "ogr_gitlab.GitlabProject" = None - _merge_commit_status: Dict[str, MergeCommitStatus] = { + _merge_commit_status: dict[str, MergeCommitStatus] = { "can_be_merged": MergeCommitStatus.can_be_merged, "cannot_be_merged": MergeCommitStatus.cannot_be_merged, "unchecked": MergeCommitStatus.unchecked, @@ -79,7 +79,7 @@ def created(self) -> datetime.datetime: return self._raw_pr.created_at @property - def labels(self) -> List[str]: + def labels(self) -> list[str]: return self._raw_pr.labels @property @@ -238,7 +238,7 @@ def get(project: "ogr_gitlab.GitlabProject", pr_id: int) -> "PullRequest": def get_list( project: "ogr_gitlab.GitlabProject", status: PRStatus = PRStatus.open, - ) -> List["PullRequest"]: + ) -> list["PullRequest"]: # Gitlab API has status 'opened', not 'open' mrs = project.gitlab_repo.mergerequests.list( state=status.name if status != PRStatus.open else "opened", @@ -260,13 +260,13 @@ def update_info( self._raw_pr.save() return self - def _get_all_comments(self) -> List[PRComment]: + def _get_all_comments(self) -> list[PRComment]: return [ GitlabPRComment(parent=self, raw_comment=raw_comment) for raw_comment in self._raw_pr.notes.list(sort="asc", all=True) ] - def get_all_commits(self) -> List[str]: + def get_all_commits(self) -> list[str]: return [commit.id for commit in self._raw_pr.commits()] def comment( diff --git a/ogr/services/gitlab/release.py b/ogr/services/gitlab/release.py index ef66689c..c399a72b 100644 --- a/ogr/services/gitlab/release.py +++ b/ogr/services/gitlab/release.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import List, Optional +from typing import Optional from gitlab.v4.objects import ProjectRelease as _GitlabRelease @@ -63,7 +63,7 @@ def get_latest(project: "ogr_gitlab.GitlabProject") -> Optional["Release"]: return GitlabRelease(releases[0], project) if releases else None @staticmethod - def get_list(project: "ogr_gitlab.GitlabProject") -> List["Release"]: + def get_list(project: "ogr_gitlab.GitlabProject") -> list["Release"]: if not hasattr(project.gitlab_repo, "releases"): raise OperationNotSupported( "This version of python-gitlab does not support release, please upgrade.", diff --git a/ogr/services/gitlab/service.py b/ogr/services/gitlab/service.py index cefca898..728cce06 100644 --- a/ogr/services/gitlab/service.py +++ b/ogr/services/gitlab/service.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import logging -from typing import List, Optional +from typing import Optional import gitlab @@ -140,7 +140,7 @@ def list_projects( user: str = None, search_pattern: str = None, language: str = None, - ) -> List[GitProject]: + ) -> list[GitProject]: if namespace: group = self.gitlab_instance.groups.get(namespace) projects = group.projects.list(all=True) diff --git a/ogr/services/gitlab/user.py b/ogr/services/gitlab/user.py index 207eb2e8..34e85a90 100644 --- a/ogr/services/gitlab/user.py +++ b/ogr/services/gitlab/user.py @@ -1,7 +1,6 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from typing import List from ogr.exceptions import OperationNotSupported from ogr.services import gitlab as ogr_gitlab @@ -27,8 +26,8 @@ def get_username(self) -> str: def get_email(self) -> str: return self._gitlab_user.email - def get_projects(self) -> List["ogr_gitlab.GitlabProject"]: + def get_projects(self) -> list["ogr_gitlab.GitlabProject"]: raise OperationNotSupported - def get_forks(self) -> List["ogr_gitlab.GitlabProject"]: + def get_forks(self) -> list["ogr_gitlab.GitlabProject"]: raise OperationNotSupported diff --git a/ogr/services/pagure/comments.py b/ogr/services/pagure/comments.py index a10e723f..154ed213 100644 --- a/ogr/services/pagure/comments.py +++ b/ogr/services/pagure/comments.py @@ -2,14 +2,14 @@ # SPDX-License-Identifier: MIT import datetime -from typing import Any, Dict, Optional +from typing import Any, Optional from ogr.abstract import Comment, IssueComment, PRComment from ogr.exceptions import OperationNotSupported class PagureComment(Comment): - def _from_raw_comment(self, raw_comment: Dict[str, Any]) -> None: + def _from_raw_comment(self, raw_comment: dict[str, Any]) -> None: self._body = raw_comment["comment"] self._id = raw_comment["id"] self._author = raw_comment["user"]["name"] diff --git a/ogr/services/pagure/flag.py b/ogr/services/pagure/flag.py index f3cf953e..55e69d52 100644 --- a/ogr/services/pagure/flag.py +++ b/ogr/services/pagure/flag.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import Any, Dict, List +from typing import Any from ogr.abstract import CommitFlag, CommitStatus from ogr.services import pagure as ogr_pagure @@ -29,7 +29,7 @@ def _from_raw_commit_flag(self): self.url = self._raw_commit_flag["url"] @staticmethod - def get(project: "ogr_pagure.PagureProject", commit: str) -> List["CommitFlag"]: + def get(project: "ogr_pagure.PagureProject", commit: str) -> list["CommitFlag"]: response = project._call_project_api("c", commit, "flag") return [ PagureCommitFlag(raw_commit_flag=flag, project=project) @@ -53,7 +53,7 @@ def set( if trim: description = description[:140] - data: Dict[str, Any] = { + data: dict[str, Any] = { "username": context, "comment": description, "url": target_url, diff --git a/ogr/services/pagure/issue.py b/ogr/services/pagure/issue.py index d0ce84b0..9a983898 100644 --- a/ogr/services/pagure/issue.py +++ b/ogr/services/pagure/issue.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import Any, Dict, List, Optional, Union, cast +from typing import Any, Optional, Union, cast from ogr.abstract import Issue, IssueComment, IssueStatus from ogr.exceptions import ( @@ -84,7 +84,7 @@ def created(self) -> datetime.datetime: return datetime.datetime.fromtimestamp(int(self._raw_issue["date_created"])) @property - def labels(self) -> List[str]: + def labels(self) -> list[str]: return self._raw_issue["tags"] def __str__(self) -> str: @@ -122,8 +122,8 @@ def create( title: str, body: str, private: Optional[bool] = None, - labels: Optional[List[str]] = None, - assignees: Optional[List[str]] = None, + labels: Optional[list[str]] = None, + assignees: Optional[list[str]] = None, ) -> "Issue": if not project.has_issues: raise IssueTrackerDisabled() @@ -158,12 +158,12 @@ def get_list( status: IssueStatus = IssueStatus.open, author: Optional[str] = None, assignee: Optional[str] = None, - labels: Optional[List[str]] = None, - ) -> List["Issue"]: + labels: Optional[list[str]] = None, + ) -> list["Issue"]: if not project.has_issues: raise IssueTrackerDisabled() - payload: Dict[str, Union[str, List[str], int]] = { + payload: dict[str, Union[str, list[str], int]] = { "status": status.name.capitalize(), "page": 1, "per_page": 100, @@ -175,7 +175,7 @@ def get_list( if labels: payload["tags"] = labels - raw_issues: List[Any] = [] + raw_issues: list[Any] = [] while True: issues_info = project._call_project_api("issues", params=payload) @@ -186,7 +186,7 @@ def get_list( return [PagureIssue(issue_dict, project) for issue_dict in raw_issues] - def _get_all_comments(self) -> List[IssueComment]: + def _get_all_comments(self) -> list[IssueComment]: self.__update() raw_comments = self._raw_issue["comments"] return [ diff --git a/ogr/services/pagure/project.py b/ogr/services/pagure/project.py index 581d75f2..e12a4774 100644 --- a/ogr/services/pagure/project.py +++ b/ogr/services/pagure/project.py @@ -2,7 +2,8 @@ # SPDX-License-Identifier: MIT import logging -from typing import Dict, Iterable, List, Optional, Set +from collections.abc import Iterable +from typing import Optional from urllib.parse import urlparse from ogr.abstract import ( @@ -174,7 +175,7 @@ def _get_project_url(self, *args, add_fork_part=True, add_api_endpoint_part=True def get_project_info(self): return self._call_project_api(method="GET") - def get_branches(self) -> List[str]: + def get_branches(self) -> list[str]: return_value = self._call_project_api("git", "branches", method="GET") return return_value["branches"] @@ -199,12 +200,12 @@ def has_issues(self) -> bool: options = self._call_project_api("options", method="GET") return options["settings"]["issue_tracker"] - def get_owners(self) -> List[str]: + def get_owners(self) -> list[str]: project = self.get_project_info() return project["access_users"]["owner"] - def who_can_close_issue(self) -> Set[str]: - users: Set[str] = set() + def who_can_close_issue(self) -> set[str]: + users: set[str] = set() project = self.get_project_info() users.update(project["access_users"]["admin"]) users.update(project["access_users"]["commit"]) @@ -212,16 +213,16 @@ def who_can_close_issue(self) -> Set[str]: users.update(project["access_users"]["owner"]) return users - def who_can_merge_pr(self) -> Set[str]: - users: Set[str] = set() + def who_can_merge_pr(self) -> set[str]: + users: set[str] = set() project = self.get_project_info() users.update(project["access_users"]["admin"]) users.update(project["access_users"]["commit"]) users.update(project["access_users"]["owner"]) return users - def which_groups_can_merge_pr(self) -> Set[str]: - groups: Set[str] = set() + def which_groups_can_merge_pr(self) -> set[str]: + groups: set[str] = set() project = self.get_project_info() groups.update(project["access_groups"]["admin"]) groups.update(project["access_groups"]["commit"]) @@ -239,8 +240,8 @@ def get_issue_list( status: IssueStatus = IssueStatus.open, author: Optional[str] = None, assignee: Optional[str] = None, - labels: Optional[List[str]] = None, - ) -> List[Issue]: + labels: Optional[list[str]] = None, + ) -> list[Issue]: pass @indirect(PagureIssue.get) @@ -256,8 +257,8 @@ def create_issue( title: str, body: str, private: Optional[bool] = None, - labels: Optional[List[str]] = None, - assignees: Optional[List[str]] = None, + labels: Optional[list[str]] = None, + assignees: Optional[list[str]] = None, ) -> Issue: pass @@ -267,7 +268,7 @@ def get_pr_list( status: PRStatus = PRStatus.open, assignee=None, author=None, - ) -> List[PullRequest]: + ) -> list[PullRequest]: pass @indirect(PagurePullRequest.get) @@ -373,7 +374,7 @@ def parent(self) -> Optional["PagureProject"]: ) return None - def get_git_urls(self) -> Dict[str, str]: + def get_git_urls(self) -> dict[str, str]: return_value = self._call_project_api("git", "urls") return return_value["urls"] @@ -457,7 +458,7 @@ def commit_comment( ) -> CommitComment: raise OperationNotSupported("Commit comments are not supported on Pagure.") - def get_commit_comments(self, commit: str) -> List[CommitComment]: + def get_commit_comments(self, commit: str) -> list[CommitComment]: raise OperationNotSupported("Commit comments are not supported on Pagure.") @if_readonly(return_function=GitProjectReadOnly.set_commit_status) @@ -476,19 +477,19 @@ def set_commit_status( pass @indirect(PagureCommitFlag.get) - def get_commit_statuses(self, commit: str) -> List[CommitFlag]: + def get_commit_statuses(self, commit: str) -> list[CommitFlag]: pass - def get_tags(self) -> List[GitTag]: + def get_tags(self) -> list[GitTag]: response = self._call_project_api("git", "tags", params={"with_commits": True}) return [GitTag(name=n, commit_sha=c) for n, c in response["tags"].items()] - def get_tags_dict(self) -> Dict[str, GitTag]: + def get_tags_dict(self) -> dict[str, GitTag]: response = self._call_project_api("git", "tags", params={"with_commits": True}) return {n: GitTag(name=n, commit_sha=c) for n, c in response["tags"].items()} @indirect(PagureRelease.get_list) - def get_releases(self) -> List[Release]: + def get_releases(self) -> list[Release]: pass @indirect(PagureRelease.get) @@ -509,7 +510,7 @@ def create_release( ) -> Release: pass - def get_forks(self) -> List["PagureProject"]: + def get_forks(self) -> list["PagureProject"]: forks_url = self.service.get_api_url("projects") projects_response = self.service.call_api( url=forks_url, @@ -561,7 +562,7 @@ def get_files( ref: str = None, filter_regex: str = None, recursive: bool = False, - ) -> List[str]: + ) -> list[str]: ref = ref or self.default_branch paths = list(self.__get_files(".", ref, recursive)) if filter_regex: @@ -578,10 +579,10 @@ def get_sha_from_branch(self, branch: str) -> Optional[str]: return branches.get(branch) - def get_contributors(self) -> Set[str]: + def get_contributors(self) -> set[str]: raise OperationNotSupported("Pagure doesn't provide list of contributors") - def users_with_write_access(self) -> Set[str]: + def users_with_write_access(self) -> set[str]: users_with_access = self.get_project_info()["access_users"] result = set() for access_level in ["commit", "admin", "owner"]: diff --git a/ogr/services/pagure/pull_request.py b/ogr/services/pagure/pull_request.py index 7a9bda2a..c4d67473 100644 --- a/ogr/services/pagure/pull_request.py +++ b/ogr/services/pagure/pull_request.py @@ -3,7 +3,7 @@ import datetime import logging -from typing import Any, Dict, List, Optional, Union +from typing import Any, Optional, Union from ogr.abstract import CommitFlag, CommitStatus, PRComment, PRStatus, PullRequest from ogr.exceptions import PagureAPIException @@ -196,7 +196,7 @@ def get_list( status: PRStatus = PRStatus.open, assignee=None, author=None, - ) -> List["PullRequest"]: + ) -> list["PullRequest"]: payload = {"page": 1, "status": status.name.capitalize()} if assignee is not None: payload["assignee"] = assignee @@ -234,7 +234,7 @@ def update_info( except Exception as ex: raise PagureAPIException("there was an error while updating the PR") from ex - def _get_all_comments(self) -> List[PRComment]: + def _get_all_comments(self) -> list[PRComment]: self.__update() raw_comments = self._raw_pr["comments"] return [ @@ -249,7 +249,7 @@ def comment( filename: Optional[str] = None, row: Optional[int] = None, ) -> "PRComment": - payload: Dict[str, Any] = {"comment": body} + payload: dict[str, Any] = {"comment": body} if commit is not None: payload["commit"] = commit if filename is not None: @@ -283,7 +283,7 @@ def merge(self) -> "PullRequest": self.__dirty = True return self - def get_statuses(self) -> List[CommitFlag]: + def get_statuses(self) -> list[CommitFlag]: self.__update() return self.target_project.get_commit_statuses(self._raw_pr["commit_stop"]) @@ -314,7 +314,7 @@ def set_flag( Returns: Dictionary with the response received from Pagure. """ - data: Dict[str, Union[str, int]] = { + data: dict[str, Union[str, int]] = { "username": username, "comment": comment, "url": url, diff --git a/ogr/services/pagure/release.py b/ogr/services/pagure/release.py index 57c837bb..98360099 100644 --- a/ogr/services/pagure/release.py +++ b/ogr/services/pagure/release.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import List, Optional +from typing import Optional from ogr.abstract import GitTag, Release from ogr.exceptions import OperationNotSupported, PagureAPIException @@ -58,7 +58,7 @@ def get_latest(project: "ogr_pagure.PagureProject") -> Optional["Release"]: raise OperationNotSupported("Pagure API does not provide timestamps") @staticmethod - def get_list(project: "ogr_pagure.PagureProject") -> List["Release"]: + def get_list(project: "ogr_pagure.PagureProject") -> list["Release"]: # git tag for Pagure is shown as Release in Pagure UI git_tags = project.get_tags() return [PagureRelease(git_tag, project) for git_tag in git_tags] diff --git a/ogr/services/pagure/service.py b/ogr/services/pagure/service.py index 2328668a..6a1957e7 100644 --- a/ogr/services/pagure/service.py +++ b/ogr/services/pagure/service.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import logging -from typing import List, Optional, Union +from typing import Optional, Union import requests import urllib3 @@ -293,7 +293,7 @@ def get_api_url(self, *args, add_api_endpoint_part: bool = True) -> str: Returns: String """ - args_list: List[str] = [] + args_list: list[str] = [] args_list += filter(lambda x: x is not None, args) @@ -371,5 +371,5 @@ def list_projects( user: str = None, search_pattern: str = None, language: str = None, - ) -> List[GitProject]: + ) -> list[GitProject]: raise OperationNotSupported diff --git a/ogr/services/pagure/user.py b/ogr/services/pagure/user.py index df63ce85..afae6f8b 100644 --- a/ogr/services/pagure/user.py +++ b/ogr/services/pagure/user.py @@ -1,7 +1,6 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from typing import List from ogr.exceptions import OperationNotSupported from ogr.services import pagure as ogr_pagure @@ -24,7 +23,7 @@ def get_username(self) -> str: return_value = self.service.call_api(url=request_url, method="POST", data={}) return return_value["username"] - def get_projects(self) -> List["PagureProject"]: + def get_projects(self) -> list["PagureProject"]: user_url = self.service.get_api_url("user", self.get_username()) raw_projects = self.service.call_api(user_url)["repos"] @@ -37,7 +36,7 @@ def get_projects(self) -> List["PagureProject"]: for project in raw_projects ] - def get_forks(self) -> List["PagureProject"]: + def get_forks(self) -> list["PagureProject"]: user_url = self.service.get_api_url("user", self.get_username()) raw_forks = self.service.call_api(user_url)["forks"] diff --git a/ogr/utils.py b/ogr/utils.py index 6dbea16b..1f5f02b5 100644 --- a/ogr/utils.py +++ b/ogr/utils.py @@ -4,7 +4,8 @@ import functools import logging import re -from typing import Any, Callable, Dict, List, Match, Optional, Tuple, Union +from re import Match +from typing import Any, Callable, Optional, Union from ogr.abstract import AnyComment, Comment @@ -12,11 +13,11 @@ def filter_comments( - comments: List[AnyComment], + comments: list[AnyComment], filter_regex: Optional[str] = None, reverse: bool = False, author: Optional[str] = None, -) -> List[AnyComment]: +) -> list[AnyComment]: """ Filters comments from the given list. @@ -55,7 +56,7 @@ def filter_comments( def search_in_comments( - comments: List[Union[str, Comment]], + comments: list[Union[str, Comment]], filter_regex: str, ) -> Optional[Match[str]]: """ @@ -95,11 +96,11 @@ def __init__( status_code: int, ok: bool, content: bytes, - json: Optional[Dict[Any, Any]] = None, + json: Optional[dict[Any, Any]] = None, reason: Optional[str] = None, - headers: Optional[List[Tuple[Any, Any]]] = None, - links: Optional[List[str]] = None, - exception: Optional[Dict[Any, Any]] = None, + headers: Optional[list[tuple[Any, Any]]] = None, + links: Optional[list[str]] = None, + exception: Optional[dict[Any, Any]] = None, ) -> None: self.status_code = status_code self.ok = ok @@ -137,7 +138,7 @@ def __eq__(self, o: object) -> bool: and self.exception == o.exception ) - def to_json_format(self) -> Dict[str, Any]: + def to_json_format(self) -> dict[str, Any]: """ Returns: Response in a JSON format. @@ -159,7 +160,7 @@ def to_json_format(self) -> Dict[str, Any]: output["exception"] = self.exception return output - def json(self) -> Optional[Dict[Any, Any]]: + def json(self) -> Optional[dict[Any, Any]]: """ Returns: JSON content of the response. @@ -167,7 +168,7 @@ def json(self) -> Optional[Dict[Any, Any]]: return self.json_content -def filter_paths(paths: List[str], filter_regex: str) -> List[str]: +def filter_paths(paths: list[str], filter_regex: str) -> list[str]: """ Filters paths from the given list. diff --git a/pyproject.toml b/pyproject.toml index 743ccb6f..96f6b3df 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -80,7 +80,7 @@ select = [ "RET", # flake8-return # "RUF", # Ruff-specific rules "SIM", # flake8-simplify - # "UP", # pyupgrade + "UP", # pyupgrade "W", # pycodestyle Warning ] diff --git a/tests/unit/test_factory.py b/tests/unit/test_factory.py index 9654cff8..2de1e4c2 100644 --- a/tests/unit/test_factory.py +++ b/tests/unit/test_factory.py @@ -1,7 +1,6 @@ # Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT -from typing import Set import pytest from flexmock import Mock, flexmock @@ -396,7 +395,7 @@ def test_get_project_not_found(url, mapping, instances, exc_str): ), ], ) -def test_get_instances_from_dict(instances_in_dict, result_instances: Set): +def test_get_instances_from_dict(instances_in_dict, result_instances: set): services = get_instances_from_dict(instances=instances_in_dict) assert services == result_instances From 4edd3701507e543be20b452c018162b43f960cdc Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 19:03:58 +0200 Subject: [PATCH 12/16] ci: disable pre-commit's flake8 and pyupgrade They are included with the ruff, there is no need to have duplicit checks that take more time than the whole ruff suite itself. Signed-off-by: Matej Focko --- .pre-commit-config.yaml | 9 --------- 1 file changed, 9 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 92fbdcb7..66519dcc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,10 +3,6 @@ # pre-commit install -t pre-commit -t pre-push repos: - - repo: https://github.com/asottile/pyupgrade - rev: v3.10.1 - hooks: - - id: pyupgrade - repo: https://github.com/psf/black rev: 23.9.1 hooks: @@ -29,11 +25,6 @@ repos: - id: end-of-file-fixer - id: mixed-line-ending - id: trailing-whitespace - - repo: https://github.com/PyCQA/flake8 - rev: 6.1.0 - hooks: - - id: flake8 - args: [--max-line-length=100] - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.5.1 hooks: From ce9655d5dc4eb06b10655b4393c51adafca0c802 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 24 Sep 2023 22:57:21 +0200 Subject: [PATCH 13/16] ci(ruff): enable the perflint and ruff rules * enable the performance rules in ruff * enable the Ruff-specific rules in ruff * disable check for ambiguous characters in comments; I intend to use guillemets Signed-off-by: Matej Focko --- ogr/abstract.py | 27 ++++++++-------- ogr/factory.py | 8 ++--- ogr/read_only.py | 8 ++--- ogr/services/base.py | 8 ++--- .../github/auth_providers/github_app.py | 6 ++-- ogr/services/github/auth_providers/token.py | 2 +- ogr/services/github/auth_providers/tokman.py | 5 ++- ogr/services/github/flag.py | 3 +- ogr/services/github/project.py | 14 ++++---- ogr/services/github/pull_request.py | 2 +- ogr/services/github/service.py | 18 +++++------ ogr/services/gitlab/flag.py | 3 +- ogr/services/gitlab/project.py | 10 +++--- ogr/services/gitlab/pull_request.py | 6 ++-- ogr/services/gitlab/service.py | 8 ++--- ogr/services/pagure/flag.py | 8 ++--- ogr/services/pagure/project.py | 32 +++++++++---------- ogr/services/pagure/pull_request.py | 2 +- ogr/services/pagure/service.py | 18 +++++------ pyproject.toml | 11 ++++--- .../integration/github/test_pull_requests.py | 11 ++----- 21 files changed, 105 insertions(+), 105 deletions(-) diff --git a/ogr/abstract.py b/ogr/abstract.py index 6a493cb2..4d4391bf 100644 --- a/ogr/abstract.py +++ b/ogr/abstract.py @@ -9,6 +9,7 @@ from typing import ( Any, Callable, + ClassVar, Optional, TypeVar, Union, @@ -152,7 +153,7 @@ def __new__(cls, name, bases, namespace): class OgrAbstractClass(metaclass=CatchCommonErrors): def __repr__(self) -> str: - return f"<{str(self)}>" + return f"<{self!s}>" class Reaction(OgrAbstractClass): @@ -441,9 +442,9 @@ def _get_all_comments(self) -> list[IssueComment]: def get_comments( self, - filter_regex: str = None, + filter_regex: Optional[str] = None, reverse: bool = False, - author: str = None, + author: Optional[str] = None, ) -> list[IssueComment]: """ Get list of issue comments. @@ -706,7 +707,7 @@ def create( body: str, target_branch: str, source_branch: str, - fork_username: str = None, + fork_username: Optional[str] = None, ) -> "PullRequest": """ Create new pull request. @@ -918,7 +919,7 @@ def get_comment(self, comment_id: int) -> PRComment: class CommitFlag(OgrAbstractClass): - _states: dict[str, CommitStatus] = {} + _states: ClassVar[dict[str, CommitStatus]] = {} def __init__( self, @@ -1351,10 +1352,10 @@ def project_create( def list_projects( self, - namespace: str = None, - user: str = None, - search_pattern: str = None, - language: str = None, + namespace: Optional[str] = None, + user: Optional[str] = None, + search_pattern: Optional[str] = None, + language: Optional[str] = None, ) -> list["GitProject"]: """ List projects for given criteria. @@ -1773,7 +1774,7 @@ def create_pr( body: str, target_branch: str, source_branch: str, - fork_username: str = None, + fork_username: Optional[str] = None, ) -> "PullRequest": """ Create new pull request. @@ -1904,7 +1905,7 @@ def change_token(self, new_token: str) -> None: """ raise NotImplementedError - def get_file_content(self, path: str, ref: str = None) -> str: + def get_file_content(self, path: str, ref: Optional[str] = None) -> str: """ Get a content of the file in the repo. @@ -1924,8 +1925,8 @@ def get_file_content(self, path: str, ref: str = None) -> str: def get_files( self, - ref: str = None, - filter_regex: str = None, + ref: Optional[str] = None, + filter_regex: Optional[str] = None, recursive: bool = False, ) -> list[str]: """ diff --git a/ogr/factory.py b/ogr/factory.py index 81829fce..e2ccc154 100644 --- a/ogr/factory.py +++ b/ogr/factory.py @@ -54,8 +54,8 @@ def covered_func(kls: type[GitService]): def get_project( url, - service_mapping_update: dict[str, type[GitService]] = None, - custom_instances: Iterable[GitService] = None, + service_mapping_update: Optional[dict[str, type[GitService]]] = None, + custom_instances: Optional[Iterable[GitService]] = None, force_custom_instance: bool = True, **kwargs, ) -> GitProject: @@ -112,7 +112,7 @@ def get_project( def get_service_class_or_none( url: str, - service_mapping_update: dict[str, type[GitService]] = None, + service_mapping_update: Optional[dict[str, type[GitService]]] = None, ) -> Optional[type[GitService]]: """ Get the matching service class from the URL. @@ -142,7 +142,7 @@ def get_service_class_or_none( def get_service_class( url: str, - service_mapping_update: dict[str, type[GitService]] = None, + service_mapping_update: Optional[dict[str, type[GitService]]] = None, ) -> type[GitService]: """ Get the matching service class from the URL. diff --git a/ogr/read_only.py b/ogr/read_only.py index 46313792..66bb6c33 100644 --- a/ogr/read_only.py +++ b/ogr/read_only.py @@ -174,7 +174,7 @@ def create_pr( body: str, target_branch: str, source_branch: str, - fork_username: str = None, + fork_username: Optional[str] = None, ) -> "PullRequest": return PullRequestReadOnly( title=title, @@ -194,9 +194,9 @@ def pr_comment( original_object: Any, pr_id: int, body: str, - commit: str = None, - filename: str = None, - row: int = None, + commit: Optional[str] = None, + filename: Optional[str] = None, + row: Optional[int] = None, ) -> "PRComment": pull_request = original_object.get_pr(pr_id) log_output(pull_request) diff --git a/ogr/services/base.py b/ogr/services/base.py index 02f38886..6c89637e 100644 --- a/ogr/services/base.py +++ b/ogr/services/base.py @@ -54,9 +54,9 @@ def target_branch_head_commit(self) -> str: def get_comments( self, - filter_regex: str = None, + filter_regex: Optional[str] = None, reverse: bool = False, - author: str = None, + author: Optional[str] = None, ): all_comments = self._get_all_comments() return filter_comments(all_comments, filter_regex, reverse, author) @@ -89,9 +89,9 @@ class BaseGitUser(GitUser): class BaseIssue(Issue): def get_comments( self, - filter_regex: str = None, + filter_regex: Optional[str] = None, reverse: bool = False, - author: str = None, + author: Optional[str] = None, ) -> list[IssueComment]: all_comments: list[IssueComment] = self._get_all_comments() return filter_comments(all_comments, filter_regex, reverse, author) diff --git a/ogr/services/github/auth_providers/github_app.py b/ogr/services/github/auth_providers/github_app.py index 9fa3f992..25633540 100644 --- a/ogr/services/github/auth_providers/github_app.py +++ b/ogr/services/github/auth_providers/github_app.py @@ -104,9 +104,9 @@ def get_token(self, namespace: str, repo: str) -> str: @staticmethod def try_create( - github_app_id: str = None, - github_app_private_key: str = None, - github_app_private_key_path: str = None, + github_app_id: Optional[str] = None, + github_app_private_key: Optional[str] = None, + github_app_private_key_path: Optional[str] = None, **_, ) -> Optional["GithubApp"]: return ( diff --git a/ogr/services/github/auth_providers/token.py b/ogr/services/github/auth_providers/token.py index e6172d9e..392d255c 100644 --- a/ogr/services/github/auth_providers/token.py +++ b/ogr/services/github/auth_providers/token.py @@ -34,7 +34,7 @@ def get_token(self, namespace: str, repo: str) -> str: @staticmethod def try_create( - token: str = None, + token: Optional[str] = None, max_retries: Union[int, Retry] = 0, **_, ) -> Optional["TokenAuthentication"]: diff --git a/ogr/services/github/auth_providers/tokman.py b/ogr/services/github/auth_providers/tokman.py index c261a1e9..a47d28eb 100644 --- a/ogr/services/github/auth_providers/tokman.py +++ b/ogr/services/github/auth_providers/tokman.py @@ -43,5 +43,8 @@ def get_token(self, namespace: str, repo: str) -> str: return response.json().get("access_token", None) @staticmethod - def try_create(tokman_instance_url: str = None, **_) -> Optional["Tokman"]: + def try_create( + tokman_instance_url: Optional[str] = None, + **_, + ) -> Optional["Tokman"]: return Tokman(tokman_instance_url) if tokman_instance_url else None diff --git a/ogr/services/github/flag.py b/ogr/services/github/flag.py index df20a5f6..b94405f8 100644 --- a/ogr/services/github/flag.py +++ b/ogr/services/github/flag.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT import datetime +from typing import ClassVar from github import UnknownObjectException @@ -11,7 +12,7 @@ class GithubCommitFlag(BaseCommitFlag): - _states = { + _states: ClassVar[dict[str, CommitStatus]] = { "pending": CommitStatus.pending, "success": CommitStatus.success, "failure": CommitStatus.failure, diff --git a/ogr/services/github/project.py b/ogr/services/github/project.py index f017a23d..881df96e 100644 --- a/ogr/services/github/project.py +++ b/ogr/services/github/project.py @@ -3,7 +3,7 @@ import datetime import logging -from typing import Optional, Union +from typing import ClassVar, Optional, Union import github from github import UnknownObjectException @@ -46,7 +46,7 @@ class GithubProject(BaseGitProject): service: "ogr_github.GithubService" # Permission levels that can merge PRs - CAN_MERGE_PERMS = ["admin", "write"] + CAN_MERGE_PERMS: ClassVar[set[str]] = {"admin", "write"} def __init__( self, @@ -319,7 +319,7 @@ def create_pr( body: str, target_branch: str, source_branch: str, - fork_username: str = None, + fork_username: Optional[str] = None, ) -> PullRequest: pass @@ -331,8 +331,8 @@ def commit_comment( self, commit: str, body: str, - filename: str = None, - row: int = None, + filename: Optional[str] = None, + row: Optional[int] = None, ) -> CommitComment: github_commit: Commit = self.github_repo.get_commit(commit) if filename and row: @@ -447,8 +447,8 @@ def get_file_content(self, path: str, ref=None) -> str: def get_files( self, - ref: str = None, - filter_regex: str = None, + ref: Optional[str] = None, + filter_regex: Optional[str] = None, recursive: bool = False, ) -> list[str]: ref = ref or self.default_branch diff --git a/ogr/services/github/pull_request.py b/ogr/services/github/pull_request.py index c1f9c4bc..0c964bd9 100644 --- a/ogr/services/github/pull_request.py +++ b/ogr/services/github/pull_request.py @@ -136,7 +136,7 @@ def create( body: str, target_branch: str, source_branch: str, - fork_username: str = None, + fork_username: Optional[str] = None, ) -> "PullRequest": """ The default behavior is the pull request is made to the immediate parent repository diff --git a/ogr/services/github/service.py b/ogr/services/github/service.py index f569e7b8..b4452294 100644 --- a/ogr/services/github/service.py +++ b/ogr/services/github/service.py @@ -44,10 +44,10 @@ def __init__( self, token=None, read_only=False, - github_app_id: str = None, - github_app_private_key: str = None, - github_app_private_key_path: str = None, - tokman_instance_url: str = None, + github_app_id: Optional[str] = None, + github_app_private_key: Optional[str] = None, + github_app_private_key_path: Optional[str] = None, + tokman_instance_url: Optional[str] = None, github_authentication: GithubAuthentication = None, max_retries: Union[int, Retry] = 0, **kwargs, @@ -127,7 +127,7 @@ def github(self): def __str__(self) -> str: readonly_str = ", read_only=True" if self.read_only else "" - arguments = f", github_authentication={str(self.authentication)}{readonly_str}" + arguments = f", github_authentication={self.authentication!s}{readonly_str}" if arguments: # remove the first '- ' @@ -217,10 +217,10 @@ def get_pygithub_instance(self, namespace: str, repo: str) -> PyGithubInstance: def list_projects( self, - namespace: str = None, - user: str = None, - search_pattern: str = None, - language: str = None, + namespace: Optional[str] = None, + user: Optional[str] = None, + search_pattern: Optional[str] = None, + language: Optional[str] = None, ) -> list[GitProject]: search_query = "" diff --git a/ogr/services/gitlab/flag.py b/ogr/services/gitlab/flag.py index a19c7a62..d8c04261 100644 --- a/ogr/services/gitlab/flag.py +++ b/ogr/services/gitlab/flag.py @@ -3,6 +3,7 @@ import datetime import logging +from typing import ClassVar import gitlab @@ -15,7 +16,7 @@ class GitlabCommitFlag(BaseCommitFlag): - _states = { + _states: ClassVar[dict[str, CommitStatus]] = { "pending": CommitStatus.pending, "success": CommitStatus.success, "failed": CommitStatus.failure, diff --git a/ogr/services/gitlab/project.py b/ogr/services/gitlab/project.py index 012fc98e..40c8b0f0 100644 --- a/ogr/services/gitlab/project.py +++ b/ogr/services/gitlab/project.py @@ -267,7 +267,7 @@ def create_pr( body: str, target_branch: str, source_branch: str, - fork_username: str = None, + fork_username: Optional[str] = None, ) -> "PullRequest": pass @@ -275,8 +275,8 @@ def commit_comment( self, commit: str, body: str, - filename: str = None, - row: int = None, + filename: Optional[str] = None, + row: Optional[int] = None, ) -> "CommitComment": try: commit_object: ProjectCommit = self.gitlab_repo.commits.get(commit) @@ -371,8 +371,8 @@ def get_file_content(self, path, ref=None) -> str: def get_files( self, - ref: str = None, - filter_regex: str = None, + ref: Optional[str] = None, + filter_regex: Optional[str] = None, recursive: bool = False, ) -> list[str]: ref = ref or self.default_branch diff --git a/ogr/services/gitlab/pull_request.py b/ogr/services/gitlab/pull_request.py index 425798f2..5c3d810d 100644 --- a/ogr/services/gitlab/pull_request.py +++ b/ogr/services/gitlab/pull_request.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import Optional +from typing import ClassVar, Optional import gitlab import requests @@ -20,7 +20,7 @@ class GitlabPullRequest(BasePullRequest): _raw_pr: _GitlabMergeRequest _target_project: "ogr_gitlab.GitlabProject" _source_project: "ogr_gitlab.GitlabProject" = None - _merge_commit_status: dict[str, MergeCommitStatus] = { + _merge_commit_status: ClassVar[dict[str, MergeCommitStatus]] = { "can_be_merged": MergeCommitStatus.can_be_merged, "cannot_be_merged": MergeCommitStatus.cannot_be_merged, "unchecked": MergeCommitStatus.unchecked, @@ -150,7 +150,7 @@ def create( body: str, target_branch: str, source_branch: str, - fork_username: str = None, + fork_username: Optional[str] = None, ) -> "PullRequest": """ How to create PR: diff --git a/ogr/services/gitlab/service.py b/ogr/services/gitlab/service.py index 728cce06..25c6e23d 100644 --- a/ogr/services/gitlab/service.py +++ b/ogr/services/gitlab/service.py @@ -136,10 +136,10 @@ def project_create( def list_projects( self, - namespace: str = None, - user: str = None, - search_pattern: str = None, - language: str = None, + namespace: Optional[str] = None, + user: Optional[str] = None, + search_pattern: Optional[str] = None, + language: Optional[str] = None, ) -> list[GitProject]: if namespace: group = self.gitlab_instance.groups.get(namespace) diff --git a/ogr/services/pagure/flag.py b/ogr/services/pagure/flag.py index 55e69d52..d6870fb3 100644 --- a/ogr/services/pagure/flag.py +++ b/ogr/services/pagure/flag.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT import datetime -from typing import Any +from typing import Any, ClassVar, Optional from ogr.abstract import CommitFlag, CommitStatus from ogr.services import pagure as ogr_pagure @@ -10,7 +10,7 @@ class PagureCommitFlag(BaseCommitFlag): - _states = { + _states: ClassVar[dict[str, CommitStatus]] = { "pending": CommitStatus.pending, "success": CommitStatus.success, "failure": CommitStatus.failure, @@ -44,9 +44,9 @@ def set( target_url: str, description: str, context: str, - percent: int = None, + percent: Optional[int] = None, trim: bool = False, - uid: str = None, + uid: Optional[str] = None, ) -> "CommitFlag": state = PagureCommitFlag._validate_state(state) diff --git a/ogr/services/pagure/project.py b/ogr/services/pagure/project.py index e12a4774..ca0af027 100644 --- a/ogr/services/pagure/project.py +++ b/ogr/services/pagure/project.py @@ -43,7 +43,7 @@ def __init__( repo: str, namespace: Optional[str], service: "ogr_pagure.PagureService", - username: str = None, + username: Optional[str] = None, is_fork: bool = False, ) -> None: super().__init__(repo, service, namespace) @@ -85,9 +85,9 @@ def _call_project_api( *args, add_fork_part: bool = True, add_api_endpoint_part: bool = True, - method: str = None, - params: dict = None, - data: dict = None, + method: Optional[str] = None, + params: Optional[dict] = None, + data: Optional[dict] = None, ) -> dict: """ Call project API endpoint. @@ -125,9 +125,9 @@ def _call_project_api_raw( *args, add_fork_part: bool = True, add_api_endpoint_part: bool = True, - method: str = None, - params: dict = None, - data: dict = None, + method: Optional[str] = None, + params: Optional[dict] = None, + data: Optional[dict] = None, ) -> RequestResponse: """ Call project API endpoint. @@ -283,7 +283,7 @@ def create_pr( body: str, target_branch: str, source_branch: str, - fork_username: str = None, + fork_username: Optional[str] = None, ) -> PullRequest: pass @@ -453,8 +453,8 @@ def commit_comment( self, commit: str, body: str, - filename: str = None, - row: int = None, + filename: Optional[str] = None, + row: Optional[int] = None, ) -> CommitComment: raise OperationNotSupported("Commit comments are not supported on Pagure.") @@ -470,8 +470,8 @@ def set_commit_status( target_url: str, description: str, context: str, - percent: int = None, - uid: str = None, + percent: Optional[int] = None, + uid: Optional[str] = None, trim: bool = False, ) -> "CommitFlag": pass @@ -539,7 +539,7 @@ def full_repo_name(self) -> str: def __get_files( self, path: str, - ref: str = None, + ref: Optional[str] = None, recursive: bool = False, ) -> Iterable[str]: subfolders = ["."] @@ -548,7 +548,7 @@ def __get_files( path = subfolders.pop() split_path = [] if path != ".": - split_path = ["f"] + path.split("/") + split_path = ["f", *path.split("/")] response = self._call_project_api("tree", ref, *split_path) for file in response["content"]: @@ -559,8 +559,8 @@ def __get_files( def get_files( self, - ref: str = None, - filter_regex: str = None, + ref: Optional[str] = None, + filter_regex: Optional[str] = None, recursive: bool = False, ) -> list[str]: ref = ref or self.default_branch diff --git a/ogr/services/pagure/pull_request.py b/ogr/services/pagure/pull_request.py index c4d67473..66c9e647 100644 --- a/ogr/services/pagure/pull_request.py +++ b/ogr/services/pagure/pull_request.py @@ -149,7 +149,7 @@ def create( body: str, target_branch: str, source_branch: str, - fork_username: str = None, + fork_username: Optional[str] = None, ) -> "PullRequest": data = { "title": title, diff --git a/ogr/services/pagure/service.py b/ogr/services/pagure/service.py index 6a1957e7..617310a1 100644 --- a/ogr/services/pagure/service.py +++ b/ogr/services/pagure/service.py @@ -34,7 +34,7 @@ class PagureService(BaseGitService): def __init__( self, - token: str = None, + token: Optional[str] = None, instance_url: str = "https://src.fedoraproject.org", read_only: bool = False, insecure: bool = False, @@ -122,8 +122,8 @@ def user(self) -> "PagureUser": def call_api( self, url: str, - method: str = None, - params: dict = None, + method: Optional[str] = None, + params: Optional[dict] = None, data=None, ) -> dict: """ @@ -186,8 +186,8 @@ def call_api( def call_api_raw( self, url: str, - method: str = None, - params: dict = None, + method: Optional[str] = None, + params: Optional[dict] = None, data=None, ): """ @@ -367,9 +367,9 @@ def project_create( def list_projects( self, - namespace: str = None, - user: str = None, - search_pattern: str = None, - language: str = None, + namespace: Optional[str] = None, + user: Optional[str] = None, + search_pattern: Optional[str] = None, + language: Optional[str] = None, ) -> list[GitProject]: raise OperationNotSupported diff --git a/pyproject.toml b/pyproject.toml index 96f6b3df..cef0d7cc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -74,20 +74,21 @@ select = [ "E", # pycodestyle Error "F", # Pyflakes "I", # isort - # "PERF",# Perflint + "PERF",# Perflint "PIE", # flake8-pie "PT", # flake8-pytest-style "RET", # flake8-return - # "RUF", # Ruff-specific rules + "RUF", # Ruff-specific rules "SIM", # flake8-simplify "UP", # pyupgrade "W", # pycodestyle Warning ] ignore = [ - "B017", # assert-raises-exception - "B022", # useless-contextlib-suppress - "RUF003"# Comment contains ambiguous character + "B017", # assert-raises-exception + "B022", # useless-contextlib-suppress + "RUF002", # you shall not touch my guillemets + "RUF003" # Comment contains ambiguous character ] line-length = 100 diff --git a/tests/integration/github/test_pull_requests.py b/tests/integration/github/test_pull_requests.py index 589f1b1e..e6848293 100644 --- a/tests/integration/github/test_pull_requests.py +++ b/tests/integration/github/test_pull_requests.py @@ -22,19 +22,12 @@ def test_pr_list(self): pr_list_closed = self.ogr_project.get_pr_list(status=PRStatus.closed) assert pr_list_closed assert len(pr_list_closed) >= 70 - - closed_pr_numbers = [] - for closed_pr in pr_list_closed: - closed_pr_numbers.append(closed_pr.id) - assert 93 in closed_pr_numbers + assert 93 in {pr.id for pr in pr_list_closed} pr_list_merged = self.ogr_project.get_pr_list(status=PRStatus.merged) assert pr_list_merged assert len(pr_list_merged) >= 1 - closed_pr_numbers = [] - for closed_pr in pr_list_merged: - closed_pr_numbers.append(closed_pr.id) - assert 93 not in closed_pr_numbers + assert 93 not in {pr.id for pr in pr_list_merged} pr_list = self.ogr_project.get_pr_list() assert pr_list From 441f4c1703edde29f0867b02680dabb7364ac94c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 12 Oct 2023 14:33:28 +0200 Subject: [PATCH 14/16] ci(ruff): remove unnecessary ignores Signed-off-by: Matej Focko --- pyproject.toml | 2 -- 1 file changed, 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index cef0d7cc..30190440 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -85,8 +85,6 @@ select = [ ] ignore = [ - "B017", # assert-raises-exception - "B022", # useless-contextlib-suppress "RUF002", # you shall not touch my guillemets "RUF003" # Comment contains ambiguous character ] From 1328c14ee915315184488dd2373b91fd4cf4d97f Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 12 Oct 2023 14:53:53 +0200 Subject: [PATCH 15/16] ci(tmt): allow running subset of the tests Signed-off-by: Matej Focko --- tests/full.fmf | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/full.fmf b/tests/full.fmf index 7635fa3f..773b10c0 100644 --- a/tests/full.fmf +++ b/tests/full.fmf @@ -22,5 +22,7 @@ tier: 1 tag: - basic -test: pytest-3 -v --cov=ogr --cov-report=term-missing . +test: pytest-3 -v --cov=ogr --cov-report=term-missing $TEST_TARGET duration: 30m +environment: + TEST_TARGET: . From 918245c1cfb82d17dd04f54ab704ed977b5fb18c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 12 Oct 2023 15:07:46 +0200 Subject: [PATCH 16/16] fix(tests): use correct attribute to get exception Signed-off-by: Matej Focko --- tests/integration/github/test_forks.py | 2 +- tests/integration/pagure/test_forks.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/integration/github/test_forks.py b/tests/integration/github/test_forks.py index 16970e9b..b9778aea 100644 --- a/tests/integration/github/test_forks.py +++ b/tests/integration/github/test_forks.py @@ -22,7 +22,7 @@ def test_nonexisting_fork(self): ) with pytest.raises(GithubAPIException) as ex: self.ogr_nonexisting_fork.get_description() - s = str(ex.exception.__cause__) + s = str(ex.value.__cause__) assert "Not Found" in s assert "404" in s diff --git a/tests/integration/pagure/test_forks.py b/tests/integration/pagure/test_forks.py index a8337b3e..76ff2405 100644 --- a/tests/integration/pagure/test_forks.py +++ b/tests/integration/pagure/test_forks.py @@ -41,7 +41,7 @@ def test_nonexisting_fork(self): assert not ogr_project_non_existing_fork.exists() with pytest.raises(PagureAPIException) as ex: ogr_project_non_existing_fork.get_description() - assert "Project not found" in ex.exception.pagure_error + assert "Project not found" in ex.value.pagure_error def test_fork_property(self): fork = self.ogr_project.get_fork()