File: update-message-registry.py

package info (click to toggle)
libxkbcommon 1.13.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 8,344 kB
  • sloc: ansic: 57,807; xml: 8,905; python: 7,451; yacc: 913; sh: 253; makefile: 23
file content (322 lines) | stat: -rwxr-xr-x 9,381 bytes parent folder | download | duplicates (2)
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#!/usr/bin/env python3

from __future__ import annotations

import argparse
import random
import re
from dataclasses import astuple, dataclass
from pathlib import Path
from typing import Any, Callable, ClassVar, Generic, Sequence, TypeAlias, TypeVar

import jinja2
import yaml


@dataclass(order=True)
class Version:
    """A semantic version number: MAJOR.MINOR.PATCH."""

    UNKNOWN_VERSION: ClassVar[str] = "ALWAYS"
    DEFAULT_VERSION: ClassVar[str] = "1.0.0"

    major: int
    minor: int
    patch: int = 0

    def __str__(self) -> str:
        return ".".join(map(str, astuple(self)))

    @classmethod
    def parse(cls, raw_version: str) -> Version:
        if raw_version == cls.UNKNOWN_VERSION:
            raw_version = cls.DEFAULT_VERSION
        version = raw_version.split(".")
        assert 2 <= len(version) <= 3 and all(n.isdecimal() for n in version), (
            raw_version
        )
        return Version(*map(int, version))


@dataclass
class Example:
    """An example in a message entry."""

    name: str
    description: str
    before: str | None
    after: str | None

    @classmethod
    def parse(cls, entry: dict[str, Any]) -> Example:
        name = entry.get("name")
        assert name, entry

        description = entry.get("description")
        assert description

        before = entry.get("before")
        after = entry.get("after")
        # Either none or both of them
        assert not (bool(before) ^ bool(after))

        return Example(name=name, description=description, before=before, after=after)


@dataclass
class Entry:
    """An xkbcommon message entry in the message registry"""

    VALID_TYPES = ("warning", "error")

    code: int
    """A unique strictly positive integer identifier"""
    id: str
    """A unique short human-readable string identifier"""
    type: str
    """Log level of the message"""
    description: str
    """A short description of the meaning of the message"""
    details: str
    """A long description of the meaning of the message"""
    added: Version
    """Version of xkbcommon the message has been added"""
    removed: Version | None
    """Version of xkbcommon the message has been removed"""
    examples: tuple[Example, ...]
    """
    Optional examples of situations in which the message occurs.
    If the message is an error or a warning, also provide hints on how to fix it.
    """

    @classmethod
    def parse(cls, entry: dict[str, Any]) -> Entry:
        code = entry.get("code")
        assert code is not None and isinstance(code, int) and code > 0, entry

        id = entry.get("id")
        assert id is not None, entry

        type_ = entry.get("type")
        assert type_ in cls.VALID_TYPES, entry

        description = entry.get("description")
        assert description is not None, entry

        details = entry.get("details", "")

        raw_added = entry.get("added", "")
        assert raw_added, entry

        added = Version.parse(raw_added)
        assert added, entry

        if removed := entry.get("removed"):
            removed = Version.parse(removed)
            assert added < removed, entry

        if examples := entry.get("examples", ()):
            examples = tuple(map(Example.parse, examples))

        return Entry(
            code=code,
            id=id,
            type=type_,
            description=description,
            added=added,
            removed=removed,
            details=details,
            examples=examples,
        )

    @property
    def message_code(self) -> str:
        """Format the message code for display"""
        return f"XKB-{self.code:0>3}"

    @property
    def message_code_constant(self: Entry) -> str:
        """Returns the C enumeration member denoting the message code"""
        id = self.id.replace("-", "_").upper()
        return f"XKB_{self.type.upper()}_{id}"

    @property
    def message_name(self: Entry) -> str:
        """Format the message string identifier for display"""
        return self.id.replace("-", " ").capitalize()


Registry: TypeAlias = Sequence[Entry]


def prepend_todo(text: str) -> str:
    if text.startswith("TODO"):
        return f"""<span class="todo">{text[:5]}</span>{text[5:]}"""
    else:
        return text


def load_message_registry(
    env: jinja2.Environment, constants: dict[str, int], path: Path
) -> Registry:
    # Load the message registry YAML file as a Jinja2 template
    registry_template = env.get_template(str(path))

    # Load message registry
    message_registry = sorted(
        map(Entry.parse, yaml.safe_load(registry_template.render(constants))),
        key=lambda e: e.code,
    )

    # Check message codes and identifiers are unique
    codes: set[int] = set()
    identifiers: set[str] = set()
    for n, entry in enumerate(message_registry):
        if entry.code in codes:
            raise ValueError(f"Duplicated code in entry #{n}: {entry.code}")
        if entry.id in identifiers:
            raise ValueError(f"Duplicated identifier in entry #{n}: {entry.id}")
        codes.add(entry.code)
        identifiers.add(entry.id)

    return message_registry


def generate_file(
    registry: Registry,
    env: jinja2.Environment,
    root: Path,
    file: Path,
    skip_removed: bool = False,
) -> None:
    """Generate a file from its Jinja2 template and the message registry"""
    template_path = file.with_suffix(f"{file.suffix}.jinja")
    template = env.get_template(str(template_path))
    path = root / file
    script = Path(__file__).name
    with path.open("wt", encoding="utf-8") as fd:
        entries = (
            tuple(filter(lambda e: e.removed is None, registry))
            if skip_removed
            else registry
        )
        fd.writelines(template.generate(entries=entries, script=script))


T = TypeVar("T")


@dataclass
class Constant(Generic[T]):
    name: str
    pattern: re.Pattern[str]
    conversion: Callable[[str], T]


def read_constants(path: Path, patterns: Sequence[Constant[T]]) -> dict[str, T]:
    constants: dict[str, T] = {}
    patternsʹ = list(patterns)
    with path.open("rt", encoding="utf-8") as fd:
        for line in fd:
            for k, constant in enumerate(patternsʹ):
                if m := constant.pattern.match(line):
                    constants[constant.name] = constant.conversion(m.group(1))
                    del patternsʹ[k]
                    continue  # Expect only one match per line
            if not patternsʹ:
                # No more pattern to match
                break
    for constant in patternsʹ:
        print(f"ERROR: could not find constant: {constant.name}.")
    if patternsʹ:
        raise ValueError("Some constants were not found.")
    return constants


def generate(
    args: argparse.Namespace, registry: Registry, jinja_env: jinja2.Environment
):
    """
    Generate the files
    """
    generate_file(
        registry,
        jinja_env,
        args.root,
        Path("src/messages-codes.h"),
        skip_removed=True,
    )
    generate_file(
        registry, jinja_env, args.root, Path("tools/messages.c"), skip_removed=True
    )
    generate_file(registry, jinja_env, args.root, Path("doc/message-registry.md"))


def get_new_code(
    args: argparse.Namespace, registry: Registry, jinja_env: jinja2.Environment
):
    """
    Get a free code
    """
    # Get all codes
    codes = frozenset(entry.code for entry in registry)
    # Filter free ones
    free = tuple(code for code in range(args.min, args.max + 1) if code not in codes)
    print(*random.sample(free, k=args.count))


# Root of the project
ROOT = Path(__file__).parent.parent

# Parse commands
parser = argparse.ArgumentParser(description="Generate files from the message registry")
parser.add_argument(
    "--root",
    type=Path,
    default=ROOT,
    help="Path to the root of the project (default: %(default)s)",
)
parser.set_defaults(func=generate)
subparsers = parser.add_subparsers()
new_id_parser = subparsers.add_parser("get-new-code", help="Get a new message codes")
new_id_parser.set_defaults(func=get_new_code)
new_id_parser.add_argument("--min", type=int, default=1, help="default: %(default)s")
new_id_parser.add_argument("--max", type=int, default=999, help="default: %(default)s")
new_id_parser.add_argument("--count", type=int, default=10, help="default: %(default)s")
generate_parser = subparsers.add_parser("generate", help="Generate files")

args = parser.parse_args()

# Read some constants from libxkbcommon that we need
constants = read_constants(
    Path(__file__).parent.parent / "src" / "keymap.h",
    (
        Constant(
            "XKB_MAX_GROUPS",
            re.compile(r"^#define\s+XKB_MAX_GROUPS\s+(\d+)"),
            int,
        ),
        Constant(
            "XKB_MAX_GROUPS_X11",
            re.compile(r"^#define\s+XKB_MAX_GROUPS_X11\s+(\d+)"),
            int,
        ),
    ),
)

# Configure Jinja
template_loader = jinja2.FileSystemLoader(args.root, encoding="utf-8")
jinja_env = jinja2.Environment(
    loader=template_loader,
    keep_trailing_newline=True,
    trim_blocks=True,
    lstrip_blocks=True,
)
jinja_env.filters["prepend_todo"] = prepend_todo

# Load message registry
message_registry = load_message_registry(
    jinja_env, constants, Path("doc/message-registry.yaml")
)

args.func(args=args, registry=message_registry, jinja_env=jinja_env)