File: simple_template.py

package info (click to toggle)
mautrix-python 0.20.7-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,812 kB
  • sloc: python: 19,103; makefile: 16
file content (48 lines) | stat: -rw-r--r-- 1,584 bytes parent folder | download
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
47
48
# Copyright (c) 2022 Tulir Asokan
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import annotations

from typing import Generic, TypeVar

T = TypeVar("T")


class SimpleTemplate(Generic[T]):
    _template: str
    _keyword: str
    _prefix: str
    _suffix: str
    _type: type[T]

    def __init__(
        self, template: str, keyword: str, prefix: str = "", suffix: str = "", type: type[T] = str
    ) -> None:
        self._template = template
        self._keyword = keyword
        index = self._template.find("{%s}" % keyword)
        length = len(keyword) + 2
        self._prefix = prefix + self._template[:index]
        self._suffix = self._template[index + length :] + suffix
        self._type = type

    def format(self, arg: T) -> str:
        return self._template.format(**{self._keyword: arg})

    def format_full(self, arg: T) -> str:
        return f"{self._prefix}{arg}{self._suffix}"

    def parse(self, val: str) -> T | None:
        prefix_ok = val[: len(self._prefix)] == self._prefix
        has_suffix = len(self._suffix) > 0
        suffix_ok = not has_suffix or val[-len(self._suffix) :] == self._suffix
        if prefix_ok and suffix_ok:
            start = len(self._prefix)
            end = -len(self._suffix) if has_suffix else len(val)
            try:
                return self._type(val[start:end])
            except ValueError:
                pass
        return None