Skip to content

chore: enforce type-hints on most files in gitlab/v4/objects/ #1680

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions gitlab/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,10 +495,10 @@ def _check_redirects(self, result: requests.Response) -> None:
def _prepare_send_data(
self,
files: Optional[Dict[str, Any]] = None,
post_data: Optional[Dict[str, Any]] = None,
post_data: Optional[Union[Dict[str, Any], bytes]] = None,
raw: bool = False,
) -> Tuple[
Optional[Dict[str, Any]],
Optional[Union[Dict[str, Any], bytes]],
Optional[Union[Dict[str, Any], MultipartEncoder]],
str,
]:
Expand All @@ -508,6 +508,8 @@ def _prepare_send_data(
else:
# booleans does not exists for data (neither for MultipartEncoder):
# cast to string int to avoid: 'bool' object has no attribute 'encode'
if TYPE_CHECKING:
assert isinstance(post_data, dict)
for k, v in post_data.items():
if isinstance(v, bool):
post_data[k] = str(int(v))
Expand All @@ -527,7 +529,7 @@ def http_request(
verb: str,
path: str,
query_data: Optional[Dict[str, Any]] = None,
post_data: Optional[Dict[str, Any]] = None,
post_data: Optional[Union[Dict[str, Any], bytes]] = None,
raw: bool = False,
streamed: bool = False,
files: Optional[Dict[str, Any]] = None,
Expand All @@ -544,7 +546,7 @@ def http_request(
path (str): Path or full URL to query ('/projects' or
'http://whatever/v4/api/projecs')
query_data (dict): Data to send as query parameters
post_data (dict): Data to send in the body (will be converted to
post_data (dict|bytes): Data to send in the body (will be converted to
json by default)
raw (bool): If True, do not convert post_data to json
streamed (bool): Whether the data should be streamed
Expand Down Expand Up @@ -800,7 +802,7 @@ def http_put(
self,
path: str,
query_data: Optional[Dict[str, Any]] = None,
post_data: Optional[Dict[str, Any]] = None,
post_data: Optional[Union[Dict[str, Any], bytes]] = None,
raw: bool = False,
files: Optional[Dict[str, Any]] = None,
**kwargs: Any,
Expand All @@ -811,7 +813,7 @@ def http_put(
path (str): Path or full URL to query ('/projects' or
'http://whatever/v4/api/projecs')
query_data (dict): Data to send as query parameters
post_data (dict): Data to send in the body (will be converted to
post_data (dict|bytes): Data to send in the body (will be converted to
json by default)
raw (bool): If True, do not convert post_data to json
files (dict): The files to send to the server
Expand Down
2 changes: 2 additions & 0 deletions gitlab/v4/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ def do_project_export_download(self) -> None:
if TYPE_CHECKING:
assert export_status is not None
data = export_status.download()
if TYPE_CHECKING:
assert data is not None
sys.stdout.buffer.write(data)

except Exception as e:
Expand Down
16 changes: 14 additions & 2 deletions gitlab/v4/objects/appearance.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any, cast, Dict, Optional, Union

from gitlab import exceptions as exc
from gitlab.base import RequiredOptional, RESTManager, RESTObject
from gitlab.mixins import GetWithoutIdMixin, SaveMixin, UpdateMixin
Expand Down Expand Up @@ -32,7 +34,12 @@ class ApplicationAppearanceManager(GetWithoutIdMixin, UpdateMixin, RESTManager):
)

@exc.on_http_error(exc.GitlabUpdateError)
def update(self, id=None, new_data=None, **kwargs):
def update(
self,
id: Optional[Union[str, int]] = None,
new_data: Dict[str, Any] = None,
**kwargs: Any
) -> Dict[str, Any]:
"""Update an object on the server.
Args:
Expand All @@ -49,4 +56,9 @@ def update(self, id=None, new_data=None, **kwargs):
"""
new_data = new_data or {}
data = new_data.copy()
super(ApplicationAppearanceManager, self).update(id, data, **kwargs)
return super(ApplicationAppearanceManager, self).update(id, data, **kwargs)

def get(
self, id: Optional[Union[int, str]] = None, **kwargs: Any
) -> Optional[ApplicationAppearance]:
return cast(ApplicationAppearance, super().get(id=id, **kwargs))
7 changes: 7 additions & 0 deletions gitlab/v4/objects/badges.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any, cast, Union

from gitlab.base import RequiredOptional, RESTManager, RESTObject
from gitlab.mixins import BadgeRenderMixin, CRUDMixin, ObjectDeleteMixin, SaveMixin

Expand Down Expand Up @@ -31,3 +33,8 @@ class ProjectBadgeManager(BadgeRenderMixin, CRUDMixin, RESTManager):
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(required=("link_url", "image_url"))
_update_attrs = RequiredOptional(optional=("link_url", "image_url"))

def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectBadge:
return cast(ProjectBadge, super().get(id=id, lazy=lazy, **kwargs))
20 changes: 20 additions & 0 deletions gitlab/v4/objects/boards.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any, cast, Union

from gitlab.base import RequiredOptional, RESTManager, RESTObject
from gitlab.mixins import CRUDMixin, ObjectDeleteMixin, SaveMixin

Expand All @@ -24,6 +26,11 @@ class GroupBoardListManager(CRUDMixin, RESTManager):
_create_attrs = RequiredOptional(required=("label_id",))
_update_attrs = RequiredOptional(required=("position",))

def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupBoardList:
return cast(GroupBoardList, super().get(id=id, lazy=lazy, **kwargs))


class GroupBoard(SaveMixin, ObjectDeleteMixin, RESTObject):
lists: GroupBoardListManager
Expand All @@ -35,6 +42,9 @@ class GroupBoardManager(CRUDMixin, RESTManager):
_from_parent_attrs = {"group_id": "id"}
_create_attrs = RequiredOptional(required=("name",))

def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> GroupBoard:
return cast(GroupBoard, super().get(id=id, lazy=lazy, **kwargs))


class ProjectBoardList(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
Expand All @@ -47,6 +57,11 @@ class ProjectBoardListManager(CRUDMixin, RESTManager):
_create_attrs = RequiredOptional(required=("label_id",))
_update_attrs = RequiredOptional(required=("position",))

def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectBoardList:
return cast(ProjectBoardList, super().get(id=id, lazy=lazy, **kwargs))


class ProjectBoard(SaveMixin, ObjectDeleteMixin, RESTObject):
lists: ProjectBoardListManager
Expand All @@ -57,3 +72,8 @@ class ProjectBoardManager(CRUDMixin, RESTManager):
_obj_cls = ProjectBoard
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(required=("name",))

def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectBoard:
return cast(ProjectBoard, super().get(id=id, lazy=lazy, **kwargs))
14 changes: 10 additions & 4 deletions gitlab/v4/objects/clusters.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any, cast, Dict, Optional

from gitlab import exceptions as exc
from gitlab.base import RequiredOptional, RESTManager, RESTObject
from gitlab.mixins import CreateMixin, CRUDMixin, ObjectDeleteMixin, SaveMixin
Expand Down Expand Up @@ -33,7 +35,9 @@ class GroupClusterManager(CRUDMixin, RESTManager):
)

@exc.on_http_error(exc.GitlabStopError)
def create(self, data, **kwargs):
def create(
self, data: Optional[Dict[str, Any]] = None, **kwargs: Any
) -> GroupCluster:
"""Create a new object.

Args:
Expand All @@ -51,7 +55,7 @@ def create(self, data, **kwargs):
the data sent by the server
"""
path = f"{self.path}/user"
return CreateMixin.create(self, data, path=path, **kwargs)
return cast(GroupCluster, CreateMixin.create(self, data, path=path, **kwargs))


class ProjectCluster(SaveMixin, ObjectDeleteMixin, RESTObject):
Expand All @@ -77,7 +81,9 @@ class ProjectClusterManager(CRUDMixin, RESTManager):
)

@exc.on_http_error(exc.GitlabStopError)
def create(self, data, **kwargs):
def create(
self, data: Optional[Dict[str, Any]] = None, **kwargs: Any
) -> ProjectCluster:
"""Create a new object.

Args:
Expand All @@ -95,4 +101,4 @@ def create(self, data, **kwargs):
the data sent by the server
"""
path = f"{self.path}/user"
return CreateMixin.create(self, data, path=path, **kwargs)
return cast(ProjectCluster, CreateMixin.create(self, data, path=path, **kwargs))
6 changes: 5 additions & 1 deletion gitlab/v4/objects/container_registry.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any, TYPE_CHECKING

from gitlab import cli
from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject
Expand Down Expand Up @@ -36,7 +38,7 @@ class ProjectRegistryTagManager(DeleteMixin, RetrieveMixin, RESTManager):
optional=("keep_n", "name_regex_keep", "older_than"),
)
@exc.on_http_error(exc.GitlabDeleteError)
def delete_in_bulk(self, name_regex_delete, **kwargs):
def delete_in_bulk(self, name_regex_delete: str, **kwargs: Any) -> None:
"""Delete Tag in bulk
Args:
Expand All @@ -55,4 +57,6 @@ def delete_in_bulk(self, name_regex_delete, **kwargs):
valid_attrs = ["keep_n", "name_regex_keep", "older_than"]
data = {"name_regex_delete": name_regex_delete}
data.update({k: v for k, v in kwargs.items() if k in valid_attrs})
if TYPE_CHECKING:
assert self.path is not None
self.gitlab.http_delete(self.path, query_data=data, **kwargs)
16 changes: 14 additions & 2 deletions gitlab/v4/objects/deploy_keys.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from typing import Any, cast, Dict, Union

import requests

from gitlab import cli
from gitlab import exceptions as exc
from gitlab.base import RequiredOptional, RESTManager, RESTObject
Expand Down Expand Up @@ -33,7 +37,9 @@ class ProjectKeyManager(CRUDMixin, RESTManager):

@cli.register_custom_action("ProjectKeyManager", ("key_id",))
@exc.on_http_error(exc.GitlabProjectDeployKeyError)
def enable(self, key_id, **kwargs):
def enable(
self, key_id: int, **kwargs: Any
) -> Union[Dict[str, Any], requests.Response]:
"""Enable a deploy key for a project.
Args:
Expand All @@ -43,6 +49,12 @@ def enable(self, key_id, **kwargs):
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabProjectDeployKeyError: If the key could not be enabled
Returns:
A dict of the result.
"""
path = f"{self.path}/{key_id}/enable"
self.gitlab.http_post(path, **kwargs)
return self.gitlab.http_post(path, **kwargs)

def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> ProjectKey:
return cast(ProjectKey, super().get(id=id, lazy=lazy, **kwargs))
11 changes: 9 additions & 2 deletions gitlab/v4/objects/environments.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from typing import Any, Dict, Union

import requests

from gitlab import cli
from gitlab import exceptions as exc
from gitlab.base import RequiredOptional, RESTManager, RESTObject
Expand All @@ -19,7 +23,7 @@
class ProjectEnvironment(SaveMixin, ObjectDeleteMixin, RESTObject):
@cli.register_custom_action("ProjectEnvironment")
@exc.on_http_error(exc.GitlabStopError)
def stop(self, **kwargs):
def stop(self, **kwargs: Any) -> Union[Dict[str, Any], requests.Response]:
"""Stop the environment.

Args:
Expand All @@ -28,9 +32,12 @@ def stop(self, **kwargs):
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabStopError: If the operation failed

Returns:
A dict of the result.
"""
path = f"{self.manager.path}/{self.get_id()}/stop"
self.manager.gitlab.http_post(path, **kwargs)
return self.manager.gitlab.http_post(path, **kwargs)


class ProjectEnvironmentManager(
Expand Down
22 changes: 22 additions & 0 deletions gitlab/v4/objects/export_import.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any, cast, Optional, Union

from gitlab.base import RequiredOptional, RESTManager, RESTObject
from gitlab.mixins import CreateMixin, DownloadMixin, GetWithoutIdMixin, RefreshMixin

Expand All @@ -22,6 +24,11 @@ class GroupExportManager(GetWithoutIdMixin, CreateMixin, RESTManager):
_obj_cls = GroupExport
_from_parent_attrs = {"group_id": "id"}

def get(
self, id: Optional[Union[int, str]] = None, **kwargs: Any
) -> Optional[GroupExport]:
return cast(GroupExport, super().get(id=id, **kwargs))


class GroupImport(RESTObject):
_id_attr = None
Expand All @@ -32,6 +39,11 @@ class GroupImportManager(GetWithoutIdMixin, RESTManager):
_obj_cls = GroupImport
_from_parent_attrs = {"group_id": "id"}

def get(
self, id: Optional[Union[int, str]] = None, **kwargs: Any
) -> Optional[GroupImport]:
return cast(GroupImport, super().get(id=id, **kwargs))


class ProjectExport(DownloadMixin, RefreshMixin, RESTObject):
_id_attr = None
Expand All @@ -43,6 +55,11 @@ class ProjectExportManager(GetWithoutIdMixin, CreateMixin, RESTManager):
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(optional=("description",))

def get(
self, id: Optional[Union[int, str]] = None, **kwargs: Any
) -> Optional[ProjectExport]:
return cast(ProjectExport, super().get(id=id, **kwargs))


class ProjectImport(RefreshMixin, RESTObject):
_id_attr = None
Expand All @@ -52,3 +69,8 @@ class ProjectImportManager(GetWithoutIdMixin, RESTManager):
_path = "/projects/%(project_id)s/import"
_obj_cls = ProjectImport
_from_parent_attrs = {"project_id": "id"}

def get(
self, id: Optional[Union[int, str]] = None, **kwargs: Any
) -> Optional[ProjectImport]:
return cast(ProjectImport, super().get(id=id, **kwargs))
24 changes: 16 additions & 8 deletions gitlab/v4/objects/features.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
"""
GitLab API:
https://docs.gitlab.com/ee/api/features.html
"""
from typing import Any, Optional, TYPE_CHECKING, Union

from gitlab import exceptions as exc
from gitlab import utils
from gitlab.base import RESTManager, RESTObject
Expand All @@ -20,14 +26,14 @@ class FeatureManager(ListMixin, DeleteMixin, RESTManager):
@exc.on_http_error(exc.GitlabSetError)
def set(
self,
name,
value,
feature_group=None,
user=None,
group=None,
project=None,
**kwargs,
):
name: str,
value: Union[bool, int],
feature_group: Optional[str] = None,
user: Optional[str] = None,
group: Optional[str] = None,
project: Optional[str] = None,
**kwargs: Any,
) -> Feature:
"""Create or update the object.
Args:
Expand Down Expand Up @@ -56,4 +62,6 @@ def set(
}
data = utils.remove_none_from_dict(data)
server_data = self.gitlab.http_post(path, post_data=data, **kwargs)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
return self._obj_cls(self, server_data)
4 changes: 3 additions & 1 deletion gitlab/v4/objects/ldap.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any, List, Union

from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject, RESTObjectList

Expand All @@ -17,7 +19,7 @@ class LDAPGroupManager(RESTManager):
_list_filters = ("search", "provider")

@exc.on_http_error(exc.GitlabListError)
def list(self, **kwargs):
def list(self, **kwargs: Any) -> Union[List[LDAPGroup], RESTObjectList]:
"""Retrieve a list of objects.
Args:
Expand Down
Loading