hcloud-python icon indicating copy to clipboard operation
hcloud-python copied to clipboard

Implement validation on labels as per spec

Open gc-ss opened this issue 3 years ago • 2 comments

Feature Request

What whould you like to see? The labels have a spec: https://docs.hetzner.cloud/#labels

There's currently no validation of labels as per spec, that results in runtime errors

gc-ss avatar Apr 15 '22 00:04 gc-ss

Code for validation:

    class SnapshotLabels:
        # Valid label values must be a string of 63 characters or less and must be empty
        # or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between
        # Otherwise TF will throw: Error: invalid input in field 'labels' (invalid_input): [labels => [invalid label value]]
        regex = r"[a-z0-9A-Z](?:(?:[\-_\.]|[a-z0-9A-Z])*[a-z0-9A-Z])*"
        pattern = re.compile(regex, re.UNICODE | re.DOTALL)

        @classmethod
        def validate(cls, label):

            if label:
                if len(label) > 63:
                    raise ValueError(f"label {label} must be 63 characters or less")
                if not cls.pattern.fullmatch(label):
                    raise ValueError(f"label {label} is not compliant")
                return True
                
        def __init__(self, labels):
            for label in labels:
                if SnapshotLabels.validate(label):
                    SnapshotLabels.validate(labels[label])
            else:
                # all labels passed validation
                self._labels = labels

        def get_mapping(self):
            return self._labels

    # not compliant
    labels = SnapshotLabels({"foo": "bar", "created": "2022-04-14 16:09"})
    # compliant
    labels = SnapshotLabels({"zing": "bang", "created": "2022-04-14_16.09"})    

gc-ss avatar Apr 15 '22 00:04 gc-ss

This issue has been marked as stale because it has not had recent activity. The bot will close the issue if no further action occurs.

github-actions[bot] avatar Jul 14 '22 13:07 github-actions[bot]