Skip to content

Commit 58572af

Browse files
author
František Nečas
committed
Enforce strict Optional typing
Signed-off-by: František Nečas <[email protected]>
1 parent eeafa45 commit 58572af

24 files changed

+513
-162
lines changed

.pre-commit-config.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ repos:
3838
rev: v0.961
3939
hooks:
4040
- id: mypy
41-
args: [--no-strict-optional, --ignore-missing-imports]
41+
args: [--ignore-missing-imports]
4242
additional_dependencies:
4343
[types-pkg_resources, types-requests, types-Deprecated]
4444
- repo: https://github.com/packit/pre-commit-hooks

ogr/abstract.py

+15-13
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ def body(self, new_body: str) -> None:
217217
self._body = new_body
218218

219219
@property
220-
def id(self) -> int:
220+
def id(self) -> Optional[int]:
221221
return self._id
222222

223223
@property
@@ -226,12 +226,12 @@ def author(self) -> str:
226226
return self._author
227227

228228
@property
229-
def created(self) -> datetime.datetime:
229+
def created(self) -> Optional[datetime.datetime]:
230230
"""Datetime of creation of the comment."""
231231
return self._created
232232

233233
@property
234-
def edited(self) -> datetime.datetime:
234+
def edited(self) -> Optional[datetime.datetime]:
235235
"""Datetime of last edit of the comment."""
236236
return self._edited
237237

@@ -256,7 +256,7 @@ def add_reaction(self, reaction: str) -> Reaction:
256256

257257
class IssueComment(Comment):
258258
@property
259-
def issue(self) -> "Issue":
259+
def issue(self) -> Optional["Issue"]:
260260
"""Issue of issue comment."""
261261
return self._parent
262262

@@ -266,7 +266,7 @@ def __str__(self) -> str:
266266

267267
class PRComment(Comment):
268268
@property
269-
def pull_request(self) -> "PullRequest":
269+
def pull_request(self) -> Optional["PullRequest"]:
270270
"""Pull request of pull request comment."""
271271
return self._parent
272272

@@ -642,12 +642,12 @@ def head_commit(self) -> str:
642642
raise NotImplementedError()
643643

644644
@property
645-
def target_branch_head_commit(self) -> str:
645+
def target_branch_head_commit(self) -> Optional[str]:
646646
"""Commit hash of the HEAD commit of the target branch."""
647647
raise NotImplementedError()
648648

649649
@property
650-
def merge_commit_sha(self) -> str:
650+
def merge_commit_sha(self) -> Optional[str]:
651651
"""
652652
Commit hash of the merge commit of the pull request.
653653
@@ -1009,12 +1009,12 @@ def set(
10091009
raise NotImplementedError()
10101010

10111011
@property
1012-
def created(self) -> datetime.datetime:
1012+
def created(self) -> Optional[datetime.datetime]:
10131013
"""Datetime of creating the commit status."""
10141014
raise NotImplementedError()
10151015

10161016
@property
1017-
def edited(self) -> datetime.datetime:
1017+
def edited(self) -> Optional[datetime.datetime]:
10181018
"""Datetime of editing the commit status."""
10191019
raise NotImplementedError()
10201020

@@ -1230,7 +1230,7 @@ class GitService(OgrAbstractClass):
12301230
instance_url (str): URL of the git forge instance.
12311231
"""
12321232

1233-
instance_url: Optional[str] = None
1233+
instance_url: str
12341234

12351235
def __init__(self, **_: Any) -> None:
12361236
pass
@@ -1326,7 +1326,9 @@ def list_projects(
13261326

13271327

13281328
class GitProject(OgrAbstractClass):
1329-
def __init__(self, repo: str, service: GitService, namespace: str) -> None:
1329+
def __init__(
1330+
self, repo: str, service: GitService, namespace: Optional[str]
1331+
) -> None:
13301332
"""
13311333
Args:
13321334
repo: Name of the project.
@@ -1335,7 +1337,7 @@ def __init__(self, repo: str, service: GitService, namespace: str) -> None:
13351337
13361338
- GitHub: username or org name.
13371339
- GitLab: username or org name.
1338-
- Pagure: namespace (e.g. `"rpms"`).
1340+
- Pagure: namespace (e.g. `"rpms"`). May be none.
13391341
13401342
In case of forks: `"fork/{username}/{namespace}"`.
13411343
"""
@@ -1916,7 +1918,7 @@ def get_username(self) -> str:
19161918
"""
19171919
raise NotImplementedError()
19181920

1919-
def get_email(self) -> str:
1921+
def get_email(self) -> Optional[str]:
19201922
"""
19211923
Returns:
19221924
Email of the user.

ogr/factory.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,11 @@ def get_project(
8080
8181
Returns:
8282
`GitProject` using the matching implementation.
83+
84+
Raises:
85+
OgrException, if the url failed to be parsed or no matching
86+
project type was found.
87+
8388
"""
8489
mapping = service_mapping_update.copy() if service_mapping_update else {}
8590
custom_instances = custom_instances or []
@@ -88,6 +93,8 @@ def get_project(
8893

8994
kls = get_service_class(url=url, service_mapping_update=mapping)
9095
parsed_repo_url = parse_git_repo(url)
96+
if not parsed_repo_url:
97+
raise OgrException(f"Failed to parse url '{url}', invalid format.")
9198

9299
service = None
93100
if custom_instances:
@@ -131,8 +138,11 @@ def get_service_class_or_none(
131138
mapping.update(service_mapping_update)
132139

133140
parsed_url = parse_git_repo(url)
141+
if not parsed_url:
142+
return None
143+
134144
for service, service_kls in mapping.items():
135-
if service in parsed_url.hostname:
145+
if parsed_url.hostname and service in parsed_url.hostname:
136146
return service_kls
137147

138148
return None

ogr/parsing.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ class RepoUrl:
1010
Class that represents repo URL.
1111
1212
Attributes:
13-
repo (str): Name of the repository.
13+
repo (Optional[str]): Name of the repository. Can be None if parsing is being done.
1414
namespace (Optional[str]): Namespace of the repository, if has any.
1515
username (Optional[str]): Username of the repository owner, if can be
1616
specified.
@@ -22,7 +22,7 @@ class RepoUrl:
2222

2323
def __init__(
2424
self,
25-
repo: str,
25+
repo: Optional[str],
2626
namespace: Optional[str] = None,
2727
username: Optional[str] = None,
2828
is_fork: bool = False,

ogr/services/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def full_repo_name(self) -> str:
4949

5050
class BasePullRequest(PullRequest):
5151
@property
52-
def target_branch_head_commit(self) -> str:
52+
def target_branch_head_commit(self) -> Optional[str]:
5353
return self.target_project.get_sha_from_branch(self.target_branch)
5454

5555
def get_comments(

ogr/services/github/auth_providers/abstract.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ class GithubAuthentication:
1111
Represents a token manager for authentication via GitHub App.
1212
"""
1313

14-
def get_token(self, namespace: str, repo: str) -> str:
14+
def get_token(self, namespace: str, repo: str) -> Optional[str]:
1515
"""
1616
Get a GitHub token for requested repository.
1717
@@ -20,7 +20,8 @@ def get_token(self, namespace: str, repo: str) -> str:
2020
repo: Name of the repository.
2121
2222
Returns:
23-
A token that can be used in PyGithub instance for authentication.
23+
A token that can be used in PyGithub instance for authentication if it
24+
can be obtained, None otherwise.
2425
"""
2526
raise NotImplementedError()
2627

ogr/services/github/auth_providers/github_app.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111

1212

1313
class GithubApp(GithubAuthentication):
14-
def __init__(self, id: str, private_key: str, private_key_path: str) -> None:
14+
def __init__(
15+
self, id: str, private_key: Optional[str], private_key_path: Optional[str]
16+
) -> None:
1517
self.id = id
1618
self._private_key = private_key
1719
self._private_key_path = private_key_path
@@ -45,7 +47,7 @@ def __str__(self) -> str:
4547
return f"GithubApp({censored_id}{censored_private_key}{private_key_path})"
4648

4749
@property
48-
def private_key(self) -> str:
50+
def private_key(self) -> Optional[str]:
4951
if self._private_key:
5052
return self._private_key
5153

@@ -71,7 +73,7 @@ def integration(self) -> github.GithubIntegration:
7173
self._integration = github.GithubIntegration(self.id, self.private_key)
7274
return self._integration
7375

74-
def get_token(self, namespace: str, repo: str) -> str:
76+
def get_token(self, namespace: str, repo: str) -> Optional[str]:
7577
if not self.private_key:
7678
return None
7779

ogr/services/github/auth_providers/token.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010

1111

1212
class TokenAuthentication(GithubAuthentication):
13-
def __init__(self, token: str, max_retries: Union[int, Retry] = 0, **_) -> None:
13+
def __init__(
14+
self, token: Optional[str], max_retries: Union[int, Retry] = 0, **_
15+
) -> None:
1416
self._token = token
1517
self._pygithub_instance = github.Github(login_or_token=token, retry=max_retries)
1618

@@ -29,11 +31,11 @@ def __str__(self) -> str:
2931
def pygithub_instance(self) -> github.Github:
3032
return self._pygithub_instance
3133

32-
def get_token(self, namespace: str, repo: str) -> str:
34+
def get_token(self, namespace: str, repo: str) -> Optional[str]:
3335
return self._token
3436

3537
@staticmethod
3638
def try_create(
37-
token: str = None, max_retries: Union[int, Retry] = 0, **_
39+
token: Optional[str] = None, max_retries: Union[int, Retry] = 0, **_
3840
) -> Optional["TokenAuthentication"]:
3941
return TokenAuthentication(token, max_retries=max_retries)

ogr/services/github/flag.py

+9-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# SPDX-License-Identifier: MIT
33

44
import datetime
5-
from typing import List
5+
from typing import List, Optional
66

77
from github import UnknownObjectException
88

@@ -64,9 +64,13 @@ def set(
6464
return GithubCommitFlag(project=project, raw_commit_flag=status, commit=commit)
6565

6666
@property
67-
def created(self) -> datetime.datetime:
68-
return self._raw_commit_flag.created_at
67+
def created(self) -> Optional[datetime.datetime]:
68+
if self._raw_commit_flag:
69+
return self._raw_commit_flag.created_at
70+
return None
6971

7072
@property
71-
def edited(self) -> datetime.datetime:
72-
return self._raw_commit_flag.updated_at
73+
def edited(self) -> Optional[datetime.datetime]:
74+
if self._raw_commit_flag:
75+
return self._raw_commit_flag.updated_at
76+
return None

ogr/services/github/pull_request.py

+13-12
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
class GithubPullRequest(BasePullRequest):
2828
_raw_pr: _GithubPullRequest
2929
_target_project: "ogr_github.GithubProject"
30-
_source_project: "ogr_github.GithubProject" = None
30+
_source_project: Optional["ogr_github.GithubProject"] = None
3131

3232
@property
3333
def title(self) -> str:
@@ -148,17 +148,18 @@ def create(
148148
github_repo = project.github_repo
149149

150150
target_project = project
151-
if project.is_fork and fork_username is None:
152-
logger.warning(f"{project.full_repo_name} is fork, ignoring fork_repo.")
153-
source_branch = f"{project.namespace}:{source_branch}"
154-
github_repo = project.parent.github_repo
155-
target_project = project.parent
156-
elif fork_username:
157-
source_branch = f"{fork_username}:{source_branch}"
158-
if fork_username != project.namespace and project.parent is not None:
159-
github_repo = GithubPullRequest.__get_fork(
160-
fork_username, project.parent.github_repo
161-
)
151+
if project.parent:
152+
if project.is_fork and fork_username is None:
153+
logger.warning(f"{project.full_repo_name} is fork, ignoring fork_repo.")
154+
source_branch = f"{project.namespace}:{source_branch}"
155+
github_repo = project.parent.github_repo
156+
target_project = project.parent
157+
elif fork_username:
158+
source_branch = f"{fork_username}:{source_branch}"
159+
if fork_username != project.namespace and project.parent is not None:
160+
github_repo = GithubPullRequest.__get_fork(
161+
fork_username, project.parent.github_repo
162+
)
162163

163164
created_pr = github_repo.create_pull(
164165
title=title, body=body, base=target_branch, head=source_branch

ogr/services/github/release.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from github.GitRelease import GitRelease as PyGithubRelease
88

99
from ogr.abstract import Release, GitTag
10-
from ogr.exceptions import GithubAPIException
10+
from ogr.exceptions import GithubAPIException, OgrException
1111
from ogr.services import github as ogr_github
1212

1313

@@ -45,7 +45,10 @@ def body(self):
4545

4646
@property
4747
def git_tag(self) -> GitTag:
48-
return self.project.get_tag_from_tag_name(self.tag_name)
48+
tag = self.project.get_tag_from_tag_name(self.tag_name)
49+
if not tag:
50+
raise OgrException(f"No tag with name '{self.tag_name}' found.")
51+
return tag
4952

5053
@property
5154
def tag_name(self) -> str:

ogr/services/github/service.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,9 @@ def project_create(
183183
)
184184

185185
def get_pygithub_instance(self, namespace: str, repo: str) -> PyGithubInstance:
186-
token = self.authentication.get_token(namespace, repo)
186+
token = None
187+
if self.authentication:
188+
token = self.authentication.get_token(namespace, repo)
187189
return PyGithubInstance(login_or_token=token, retry=self._max_retries)
188190

189191
def list_projects(

ogr/services/gitlab/flag.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import logging
55
import datetime
6-
from typing import List
6+
from typing import List, Optional
77

88
import gitlab
99

@@ -93,9 +93,13 @@ def set(
9393
return GitlabCommitFlag(raw_commit_flag=raw_status, project=project)
9494

9595
@property
96-
def created(self) -> datetime.datetime:
97-
return datetime.datetime.strptime(
98-
self._raw_commit_flag.created_at, "%Y-%m-%dT%H:%M:%S.%fZ"
96+
def created(self) -> Optional[datetime.datetime]:
97+
return (
98+
datetime.datetime.strptime(
99+
self._raw_commit_flag.created_at, "%Y-%m-%dT%H:%M:%S.%fZ"
100+
)
101+
if self._raw_commit_flag
102+
else None
99103
)
100104

101105
@property

ogr/services/gitlab/issue.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def url(self) -> str:
4747
return self._raw_issue.web_url
4848

4949
@property
50-
def assignees(self) -> list:
50+
def assignees(self) -> Optional[list]:
5151
try:
5252
return self._raw_issue.assignees
5353
except AttributeError:

ogr/services/gitlab/project.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,8 @@ def parent(self) -> Optional["GitlabProject"]:
7575
return None
7676

7777
@property
78-
def default_branch(self) -> Optional[str]:
79-
return self.gitlab_repo.attributes.get("default_branch")
78+
def default_branch(self) -> str:
79+
return self.gitlab_repo.attributes["default_branch"]
8080

8181
def __str__(self) -> str:
8282
return f'GitlabProject(namespace="{self.namespace}", repo="{self.repo}")'

0 commit comments

Comments
 (0)