Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_image_name.py

raw
1 # Copyright (c) 2025 Felix Fontein
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import re
11 import typing as t
12 from dataclasses import dataclass
13
14 _PATH_RE = re.compile(
15 r"^[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*(\/[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*)*$"
16 )
17 _TAG_RE = re.compile(r"^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$")
18 _DIGEST_RE = re.compile(r"^sha256:[0-9a-fA-F]{64}$")
19
20
21 def is_digest(name: str, allow_empty: bool = False) -> bool:
22 """Check whether the given name is in fact an image ID (hash)."""
23 if not name:
24 return allow_empty
25 return _DIGEST_RE.match(name) is not None
26
27
28 def is_tag(name: str, allow_empty: bool = False) -> bool:
29 """Check whether the given name can be an image tag."""
30 if not name:
31 return allow_empty
32 return _TAG_RE.match(name) is not None
33
34
35 @dataclass
36 class ImageName:
37 registry: str | None
38 path: str
39 tag: str | None
40 digest: str | None
41
42 @classmethod
43 def parse(cls, name: str) -> t.Self:
44 registry: str | None = None
45 tag: str | None = None
46 digest: str | None = None
47 parts = name.rsplit("@", 1)
48 if len(parts) == 2:
49 name, digest = parts
50 parts = name.rsplit(":", 1)
51 if len(parts) == 2 and "/" not in parts[1]:
52 name, tag = parts
53 parts = name.split("/", 1)
54 if len(parts) == 2 and (
55 "." in parts[0] or ":" in parts[0] or parts[0] == "localhost"
56 ):
57 registry, name = parts
58 return cls(registry, name, tag, digest)
59
60 def validate(self) -> t.Self:
61 if self.registry:
62 if self.registry[0] == "-" or self.registry[-1] == "-":
63 raise ValueError(
64 f'Invalid registry name ({self.registry}): must not begin or end with a "-".'
65 )
66 if self.registry[-1] == ":":
67 raise ValueError(
68 f'Invalid registry name ({self.registry}): must not end with ":".'
69 )
70 if not _PATH_RE.match(self.path):
71 raise ValueError(f"Invalid path ({self.path}).")
72 if self.tag and not is_tag(self.tag):
73 raise ValueError(f"Invalid tag ({self.tag}).")
74 if self.digest and not is_digest(self.digest):
75 raise ValueError(f"Invalid digest ({self.digest}).")
76 return self
77
78 def combine(self) -> str:
79 parts = []
80 if self.registry:
81 parts.append(self.registry)
82 if self.path:
83 parts.append("/")
84 parts.append(self.path)
85 if self.tag:
86 parts.append(":")
87 parts.append(self.tag)
88 if self.digest:
89 parts.append("@")
90 parts.append(self.digest)
91 return "".join(parts)
92
93 def normalize(self) -> ImageName:
94 registry = self.registry
95 path = self.path
96 if registry in ("", None, "index.docker.io", "registry.hub.docker.com"):
97 registry = "docker.io"
98 if registry == "docker.io" and "/" not in path and path:
99 path = f"library/{path}"
100 return ImageName(registry, path, self.tag, self.digest)
101
102 def get_hostname_and_port(self) -> tuple[str, int]:
103 if self.registry is None:
104 raise ValueError(
105 "Cannot get hostname when there is no registry. Normalize first!"
106 )
107 if self.registry == "docker.io":
108 return "index.docker.io", 443
109 parts = self.registry.split(":", 1)
110 if len(parts) == 2:
111 try:
112 port = int(parts[1])
113 except (TypeError, ValueError) as exc:
114 raise ValueError(f"Cannot parse port {parts[1]!r}") from exc
115 return parts[0], port
116 return self.registry, 443