Coverage for src/gitlabracadabra/gitlab/deploy_key_cache.py: 84%
24 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-10 17:02 +0100
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-10 17:02 +0100
1#
2# Copyright (C) 2019-2025 Mathieu Parent <math.parent@gmail.com>
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Lesser General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Lesser General Public License for more details.
13#
14# You should have received a copy of the GNU Lesser General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
18from __future__ import annotations
20from typing import TYPE_CHECKING
22if TYPE_CHECKING: 22 ↛ 23line 22 didn't jump to line 23 because the condition on line 22 was never true
23 from gitlabracadabra.gitlab.pygitlab import PyGitlab
26class DeployKeyCache:
27 """Deploy keys mapping cache.
29 indexed by id and slug (tile@project_id).
30 """
32 def __init__(self, connection: PyGitlab) -> None:
33 """Initialize a deploy keys cache.
35 Args:
36 connection: A GitlabConnection/PyGitlab.
37 """
38 self._connection = connection
39 self._slug2id: dict[str, int | None] = {}
40 self._id2slug: dict[int, str | None] = {}
42 def map_deploy_key(self, deploy_key_id: int, project_id: int, deploy_key_title: str) -> None:
43 """Map deploy key id and slug.
45 Args:
46 deploy_key_id: Deploy key id.
47 project_id: GitLab Project id.
48 deploy_key_title: Deploy key title.
49 """
50 slug = f"{deploy_key_title}@{project_id}"
51 self._id2slug[deploy_key_id] = slug
52 self._slug2id[slug] = deploy_key_id
54 def id_from_title(self, project_id: int, deploy_key_title: str) -> int | None:
55 """Get deploy key id from project and deploy key title.
57 Args:
58 project_id: GitLab Project id.
59 deploy_key_title: Deploy key title.
61 Returns:
62 Deploy key id.
63 """
64 slug = f"{deploy_key_title}@{project_id}"
65 if slug not in self._slug2id: 65 ↛ 73line 65 didn't jump to line 73 because the condition on line 65 was always true
66 self._slug2id[slug] = None
67 project = self._connection.pygitlab.projects.get(project_id, lazy=True)
68 for deploy_key in project.keys.list(all=True): 68 ↛ 73line 68 didn't jump to line 73 because the loop on line 68 didn't complete
69 if deploy_key.title == deploy_key_title: 69 ↛ 68line 69 didn't jump to line 68 because the condition on line 69 was always true
70 self._slug2id[slug] = deploy_key.id
71 self.map_deploy_key(deploy_key.id, project_id, deploy_key_title)
72 break
73 return self._slug2id[slug]