File: labels.py

package info (click to toggle)
hcloud-python 2.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,396 kB
  • sloc: python: 15,311; makefile: 43; javascript: 3
file content (46 lines) | stat: -rw-r--r-- 1,622 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from __future__ import annotations

import re


class LabelValidator:
    KEY_REGEX = re.compile(
        r"^([a-z0-9A-Z]((?:[\-_.]|[a-z0-9A-Z]){0,253}[a-z0-9A-Z])?/)?[a-z0-9A-Z]((?:[\-_.]|[a-z0-9A-Z]|){0,61}[a-z0-9A-Z])?$"
    )
    VALUE_REGEX = re.compile(
        r"^(([a-z0-9A-Z](?:[\-_.]|[a-z0-9A-Z]){0,61})?[a-z0-9A-Z]$|$)"
    )

    @staticmethod
    def validate(labels: dict[str, str]) -> bool:
        """Validates Labels. If you want to know which key/value pair of the dict is not correctly formatted
        use :func:`~hcloud.helpers.labels.validate_verbose`.

        :return:  bool
        """
        for key, value in labels.items():
            if LabelValidator.KEY_REGEX.match(key) is None:
                return False
            if LabelValidator.VALUE_REGEX.match(value) is None:
                return False
        return True

    @staticmethod
    def validate_verbose(labels: dict[str, str]) -> tuple[bool, str]:
        """Validates Labels and returns the corresponding error message if something is wrong. Returns True, <empty string>
        if everything is fine.

        :return:  bool, str
        """
        for key, value in labels.items():
            if LabelValidator.KEY_REGEX.match(key) is None:
                return (
                    False,
                    f"label key {key} is not correctly formatted",
                )
            if LabelValidator.VALUE_REGEX.match(value) is None:
                return (
                    False,
                    f"label value {value} (key: {key}) is not correctly formatted",
                )
        return True, ""