summaryrefslogtreecommitdiffstats
path: root/debian/lib/python/debian_linux/dataclasses_deb822.py
blob: aa8774939d6bb7f85447e3c37c287c22b5b7d9f9 (plain)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
from __future__ import annotations

import dataclasses
import re
from typing import (
    Any,
    Callable,
    Generic,
    IO,
    Iterable,
    Optional,
    overload,
    TypeVar,
    TYPE_CHECKING,
)

_T = TypeVar('_T')

if TYPE_CHECKING:
    from dataclasses import _DataclassT
else:
    # We can only get to _DataclassT during type checking, use a generic type during runtime
    _DataclassT = _T

__all__ = [
    'field_deb822',
    'read_deb822',
    'write_deb822',
    'Deb822DecodeError',
]


class Deb822Field(Generic[_T]):
    key: str
    load: Optional[Callable[[str], _T]]
    dump: Optional[Callable[[_T], str]]

    def __init__(
        self, *,
        key: str,
        load: Optional[Callable[[str], _T]],
        dump: Optional[Callable[[_T], str]],
    ) -> None:
        self.key = key
        self.load = load
        self.dump = dump


# The return type _T is technically wrong, but it allows checking if during
# runtime we get the correct type.
@overload
def field_deb822(
    deb822_key: str,
    /, *,
    deb822_load: Optional[Callable[[str], _T]] = None,
    deb822_dump: Optional[Callable[[_T], str]] = str,
    default: _T,
) -> _T:
    ...


@overload
def field_deb822(
    deb822_key: str,
    /, *,
    deb822_load: Optional[Callable[[str], _T]] = None,
    deb822_dump: Optional[Callable[[_T], str]] = str,
    default_factory: Callable[[], _T],
) -> _T:
    ...


@overload
def field_deb822(
    deb822_key: str,
    /, *,
    deb822_load: Optional[Callable[[str], _T]] = None,
    deb822_dump: Optional[Callable[[_T], str]] = str,
) -> _T:
    ...


def field_deb822(
    deb822_key: str,
    /, *,
    deb822_load: Optional[Callable[[str], _T]] = None,
    deb822_dump: Optional[Callable[[_T], str]] = str,
    default: Any = dataclasses.MISSING,
    default_factory: Any = dataclasses.MISSING,
) -> Any:
    metadata: dict[str, Any] = {
        'deb822': Deb822Field(
            key=deb822_key,
            load=deb822_load,
            dump=deb822_dump,
        ),
    }

    if default is not dataclasses.MISSING:
        return dataclasses.field(
            default=default,
            metadata=metadata,
        )
    else:
        return dataclasses.field(
            default_factory=default_factory,
            metadata=metadata,
        )


class Deb822DecodeError(ValueError):
    pass


class Deb822DecodeState(Generic[_DataclassT]):
    cls: type[_DataclassT]
    fields: dict[str, dataclasses.Field]
    ignore_unknown: bool

    data: dict[Optional[dataclasses.Field], str]
    current: Optional[dataclasses.Field]

    _line_re = re.compile(r'''
        ^
        (
            [ \t](?P<cont>.*)
            |
            (?P<key>[^: \t\n\r\f\v]+)\s*:\s*(?P<value>.*)
        )
        $
    ''', re.VERBOSE)

    def __init__(
        self,
        cls: type[_DataclassT],
        ignore_unknown: bool,
    ) -> None:
        self.reset()

        self.cls = cls
        self.fields = {}
        self.ignore_unknown = True

        for i in dataclasses.fields(cls):
            if i.init and (deb822_field := i.metadata.get('deb822')):
                self.fields[deb822_field.key] = i

    def reset(self) -> None:
        self.data = {}
        self.current = None

    def line(self, linenr: int, line: str) -> None:
        m = self._line_re.match(line)
        if not m:
            raise Deb822DecodeError(
                f'Not a header, not a continuation at line {linenr + 1}')
        elif cont := m.group('cont'):
            self.data[self.current] += '\n' + cont
        elif deb822_key := m.group('key'):
            field = self.fields.get(deb822_key)
            if not field and not self.ignore_unknown:
                raise Deb822DecodeError(
                    f'Unknown field "{deb822_key}" at line {linenr + 1}')

            self.current = field
            self.data[field] = m.group('value')
        else:
            raise NotImplementedError

    def generate(self) -> _DataclassT | None:
        if not self.data:
            return None

        r: dict[str, Any] = {}
        for field, value in self.data.items():
            field_factory: Optional[Callable[[str], Any]] = None
            if field is None:
                continue
            elif (deb822_field := field.metadata.get('deb822')) and (load := deb822_field.load):
                field_factory = load
            elif isinstance(field.default_factory, type):
                field_factory = field.default_factory
            elif field.type in ('str', 'Optional[str]'):
                field_factory = str
            else:
                raise RuntimeError(f'Unable to parse type {field.type}')

            if field_factory is not None:
                r[field.name] = field_factory(value)

        self.reset()
        return self.cls(**r)


def read_deb822(
    cls: type[_DataclassT],
    file: IO[str],
    /,
    ignore_unknown: bool = False,
) -> Iterable[_DataclassT]:
    state = Deb822DecodeState(cls, ignore_unknown)

    for linenr, line in enumerate(file):
        line = line.rstrip('\n')

        # Empty line, end of record
        if line == '':
            if (obj := state.generate()):
                yield obj
        # Strip comments rather than trying to preserve them
        elif line[0] == '#':
            continue
        else:
            state.line(linenr, line)

    if (obj := state.generate()):
        yield obj


def write_deb822(
    objs: Iterable[_DataclassT],
    file: IO[str],
    /,
) -> None:
    for obj in objs:
        for field in dataclasses.fields(obj):
            if (
                (value := getattr(obj, field.name, None))
                and (deb822_field := field.metadata.get('deb822'))
                and (dump := deb822_field.dump) is not None
            ):
                folded = '\n '.join(dump(value).strip().split('\n'))
                file.write(f'{deb822_field.key}: {folded}\n')
        file.write('\n')