| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import argparse |
| 6 |
import random |
| 7 |
import re |
| 8 |
from dataclasses import astuple, dataclass |
| 9 |
from pathlib import Path |
| 10 |
from typing import Any, Callable, ClassVar, Generic, Sequence, TypeAlias, TypeVar |
| 11 |
|
| 12 |
import jinja2 |
| 13 |
import yaml |
| 14 |
|
| 15 |
|
| 16 |
@dataclass(order=True) |
| 17 |
class Version: |
| 18 |
"""A semantic version number: MAJOR.MINOR.PATCH.""" |
| 19 |
|
| 20 |
UNKNOWN_VERSION: ClassVar[str] = "ALWAYS" |
| 21 |
DEFAULT_VERSION: ClassVar[str] = "1.0.0" |
| 22 |
|
| 23 |
major: int |
| 24 |
minor: int |
| 25 |
patch: int = 0 |
| 26 |
|
| 27 |
def __str__(self) -> str: |
| 28 |
return ".".join(map(str, astuple(self))) |
| 29 |
|
| 30 |
@classmethod |
| 31 |
def parse(cls, raw_version: str) -> Version: |
| 32 |
if raw_version == cls.UNKNOWN_VERSION: |
| 33 |
raw_version = cls.DEFAULT_VERSION |
| 34 |
version = raw_version.split(".") |
| 35 |
assert 2 <= len(version) <= 3 and all(n.isdecimal() for n in version), ( |
| 36 |
raw_version |
| 37 |
) |
| 38 |
return Version(*map(int, version)) |
| 39 |
|
| 40 |
|
| 41 |
@dataclass |
| 42 |
class Example: |
| 43 |
"""An example in a message entry.""" |
| 44 |
|
| 45 |
name: str |
| 46 |
description: str |
| 47 |
before: str | None |
| 48 |
after: str | None |
| 49 |
|
| 50 |
@classmethod |
| 51 |
def parse(cls, entry: dict[str, Any]) -> Example: |
| 52 |
name = entry.get("name") |
| 53 |
assert name, entry |
| 54 |
|
| 55 |
description = entry.get("description") |
| 56 |
assert description |
| 57 |
|
| 58 |
before = entry.get("before") |
| 59 |
after = entry.get("after") |
| 60 |
# Either none or both of them |
| 61 |
assert not (bool(before) ^ bool(after)) |
| 62 |
|
| 63 |
return Example(name=name, description=description, before=before, after=after) |
| 64 |
|
| 65 |
|
| 66 |
@dataclass |
| 67 |
class Entry: |
| 68 |
"""An xkbcommon message entry in the message registry""" |
| 69 |
|
| 70 |
VALID_TYPES = ("warning", "error") |
| 71 |
|
| 72 |
code: int |
| 73 |
"""A unique strictly positive integer identifier""" |
| 74 |
id: str |
| 75 |
"""A unique short human-readable string identifier""" |
| 76 |
type: str |
| 77 |
"""Log level of the message""" |
| 78 |
description: str |
| 79 |
"""A short description of the meaning of the message""" |
| 80 |
details: str |
| 81 |
"""A long description of the meaning of the message""" |
| 82 |
added: Version |
| 83 |
"""Version of xkbcommon the message has been added""" |
| 84 |
removed: Version | None |
| 85 |
"""Version of xkbcommon the message has been removed""" |
| 86 |
examples: tuple[Example, ...] |
| 87 |
""" |
| 88 |
Optional examples of situations in which the message occurs. |
| 89 |
If the message is an error or a warning, also provide hints on how to fix it. |
| 90 |
""" |
| 91 |
|
| 92 |
@classmethod |
| 93 |
def parse(cls, entry: dict[str, Any]) -> Entry: |
| 94 |
code = entry.get("code") |
| 95 |
assert code is not None and isinstance(code, int) and code > 0, entry |
| 96 |
|
| 97 |
id = entry.get("id") |
| 98 |
assert id is not None, entry |
| 99 |
|
| 100 |
type_ = entry.get("type") |
| 101 |
assert type_ in cls.VALID_TYPES, entry |
| 102 |
|
| 103 |
description = entry.get("description") |
| 104 |
assert description is not None, entry |
| 105 |
|
| 106 |
details = entry.get("details", "") |
| 107 |
|
| 108 |
raw_added = entry.get("added", "") |
| 109 |
assert raw_added, entry |
| 110 |
|
| 111 |
added = Version.parse(raw_added) |
| 112 |
assert added, entry |
| 113 |
|
| 114 |
if removed := entry.get("removed"): |
| 115 |
removed = Version.parse(removed) |
| 116 |
assert added < removed, entry |
| 117 |
|
| 118 |
if examples := entry.get("examples", ()): |
| 119 |
examples = tuple(map(Example.parse, examples)) |
| 120 |
|
| 121 |
return Entry( |
| 122 |
code=code, |
| 123 |
id=id, |
| 124 |
type=type_, |
| 125 |
description=description, |
| 126 |
added=added, |
| 127 |
removed=removed, |
| 128 |
details=details, |
| 129 |
examples=examples, |
| 130 |
) |
| 131 |
|
| 132 |
@property |
| 133 |
def message_code(self) -> str: |
| 134 |
"""Format the message code for display""" |
| 135 |
return f"XKB-{self.code:0>3}" |
| 136 |
|
| 137 |
@property |
| 138 |
def message_code_constant(self: Entry) -> str: |
| 139 |
"""Returns the C enumeration member denoting the message code""" |
| 140 |
id = self.id.replace("-", "_").upper() |
| 141 |
return f"XKB_{self.type.upper()}_{id}" |
| 142 |
|
| 143 |
@property |
| 144 |
def message_name(self: Entry) -> str: |
| 145 |
"""Format the message string identifier for display""" |
| 146 |
return self.id.replace("-", " ").capitalize() |
| 147 |
|
| 148 |
|
| 149 |
Registry: TypeAlias = Sequence[Entry] |
| 150 |
|
| 151 |
|
| 152 |
def prepend_todo(text: str) -> str: |
| 153 |
if text.startswith("TODO"): |
| 154 |
return f"""<span class="todo">{text[:5]}</span>{text[5:]}""" |
| 155 |
else: |
| 156 |
return text |
| 157 |
|
| 158 |
|
| 159 |
def load_message_registry( |
| 160 |
env: jinja2.Environment, constants: dict[str, int], path: Path |
| 161 |
) -> Registry: |
| 162 |
# Load the message registry YAML file as a Jinja2 template |
| 163 |
registry_template = env.get_template(str(path)) |
| 164 |
|
| 165 |
# Load message registry |
| 166 |
message_registry = sorted( |
| 167 |
map(Entry.parse, yaml.safe_load(registry_template.render(constants))), |
| 168 |
key=lambda e: e.code, |
| 169 |
) |
| 170 |
|
| 171 |
# Check message codes and identifiers are unique |
| 172 |
codes: set[int] = set() |
| 173 |
identifiers: set[str] = set() |
| 174 |
for n, entry in enumerate(message_registry): |
| 175 |
if entry.code in codes: |
| 176 |
raise ValueError(f"Duplicated code in entry #{n}: {entry.code}") |
| 177 |
if entry.id in identifiers: |
| 178 |
raise ValueError(f"Duplicated identifier in entry #{n}: {entry.id}") |
| 179 |
codes.add(entry.code) |
| 180 |
identifiers.add(entry.id) |
| 181 |
|
| 182 |
return message_registry |
| 183 |
|
| 184 |
|
| 185 |
def generate_file( |
| 186 |
registry: Registry, |
| 187 |
env: jinja2.Environment, |
| 188 |
root: Path, |
| 189 |
file: Path, |
| 190 |
skip_removed: bool = False, |
| 191 |
) -> None: |
| 192 |
"""Generate a file from its Jinja2 template and the message registry""" |
| 193 |
template_path = file.with_suffix(f"{file.suffix}.jinja") |
| 194 |
template = env.get_template(str(template_path)) |
| 195 |
path = root / file |
| 196 |
script = Path(__file__).name |
| 197 |
with path.open("wt", encoding="utf-8") as fd: |
| 198 |
entries = ( |
| 199 |
tuple(filter(lambda e: e.removed is None, registry)) |
| 200 |
if skip_removed |
| 201 |
else registry |
| 202 |
) |
| 203 |
fd.writelines(template.generate(entries=entries, script=script)) |
| 204 |
|
| 205 |
|
| 206 |
T = TypeVar("T") |
| 207 |
|
| 208 |
|
| 209 |
@dataclass |
| 210 |
class Constant(Generic[T]): |
| 211 |
name: str |
| 212 |
pattern: re.Pattern[str] |
| 213 |
conversion: Callable[[str], T] |
| 214 |
|
| 215 |
|
| 216 |
def read_constants(path: Path, patterns: Sequence[Constant[T]]) -> dict[str, T]: |
| 217 |
constants: dict[str, T] = {} |
| 218 |
patternsʹ = list(patterns) |
| 219 |
with path.open("rt", encoding="utf-8") as fd: |
| 220 |
for line in fd: |
| 221 |
for k, constant in enumerate(patternsʹ): |
| 222 |
if m := constant.pattern.match(line): |
| 223 |
constants[constant.name] = constant.conversion(m.group(1)) |
| 224 |
del patternsʹ[k] |
| 225 |
continue # Expect only one match per line |
| 226 |
if not patternsʹ: |
| 227 |
# No more pattern to match |
| 228 |
break |
| 229 |
for constant in patternsʹ: |
| 230 |
print(f"ERROR: could not find constant: {constant.name}.") |
| 231 |
if patternsʹ: |
| 232 |
raise ValueError("Some constants were not found.") |
| 233 |
return constants |
| 234 |
|
| 235 |
|
| 236 |
def generate( |
| 237 |
args: argparse.Namespace, registry: Registry, jinja_env: jinja2.Environment |
| 238 |
): |
| 239 |
""" |
| 240 |
Generate the files |
| 241 |
""" |
| 242 |
generate_file( |
| 243 |
registry, |
| 244 |
jinja_env, |
| 245 |
args.root, |
| 246 |
Path("src/messages-codes.h"), |
| 247 |
skip_removed=True, |
| 248 |
) |
| 249 |
generate_file( |
| 250 |
registry, jinja_env, args.root, Path("tools/messages.c"), skip_removed=True |
| 251 |
) |
| 252 |
generate_file(registry, jinja_env, args.root, Path("doc/message-registry.md")) |
| 253 |
|
| 254 |
|
| 255 |
def get_new_code( |
| 256 |
args: argparse.Namespace, registry: Registry, jinja_env: jinja2.Environment |
| 257 |
): |
| 258 |
""" |
| 259 |
Get a free code |
| 260 |
""" |
| 261 |
# Get all codes |
| 262 |
codes = frozenset(entry.code for entry in registry) |
| 263 |
# Filter free ones |
| 264 |
free = tuple(code for code in range(args.min, args.max + 1) if code not in codes) |
| 265 |
print(*random.sample(free, k=args.count)) |
| 266 |
|
| 267 |
|
| 268 |
# Root of the project |
| 269 |
ROOT = Path(__file__).parent.parent |
| 270 |
|
| 271 |
# Parse commands |
| 272 |
parser = argparse.ArgumentParser(description="Generate files from the message registry") |
| 273 |
parser.add_argument( |
| 274 |
"--root", |
| 275 |
type=Path, |
| 276 |
default=ROOT, |
| 277 |
help="Path to the root of the project (default: %(default)s)", |
| 278 |
) |
| 279 |
parser.set_defaults(func=generate) |
| 280 |
subparsers = parser.add_subparsers() |
| 281 |
new_id_parser = subparsers.add_parser("get-new-code", help="Get a new message codes") |
| 282 |
new_id_parser.set_defaults(func=get_new_code) |
| 283 |
new_id_parser.add_argument("--min", type=int, default=1, help="default: %(default)s") |
| 284 |
new_id_parser.add_argument("--max", type=int, default=999, help="default: %(default)s") |
| 285 |
new_id_parser.add_argument("--count", type=int, default=10, help="default: %(default)s") |
| 286 |
generate_parser = subparsers.add_parser("generate", help="Generate files") |
| 287 |
|
| 288 |
args = parser.parse_args() |
| 289 |
|
| 290 |
# Read some constants from libxkbcommon that we need |
| 291 |
constants = read_constants( |
| 292 |
Path(__file__).parent.parent / "src" / "keymap.h", |
| 293 |
( |
| 294 |
Constant( |
| 295 |
"XKB_MAX_GROUPS", |
| 296 |
re.compile(r"^#define\s+XKB_MAX_GROUPS\s+(\d+)"), |
| 297 |
int, |
| 298 |
), |
| 299 |
Constant( |
| 300 |
"XKB_MAX_GROUPS_X11", |
| 301 |
re.compile(r"^#define\s+XKB_MAX_GROUPS_X11\s+(\d+)"), |
| 302 |
int, |
| 303 |
), |
| 304 |
), |
| 305 |
) |
| 306 |
|
| 307 |
# Configure Jinja |
| 308 |
template_loader = jinja2.FileSystemLoader(args.root, encoding="utf-8") |
| 309 |
jinja_env = jinja2.Environment( |
| 310 |
loader=template_loader, |
| 311 |
keep_trailing_newline=True, |
| 312 |
trim_blocks=True, |
| 313 |
lstrip_blocks=True, |
| 314 |
) |
| 315 |
jinja_env.filters["prepend_todo"] = prepend_todo |
| 316 |
|
| 317 |
# Load message registry |
| 318 |
message_registry = load_message_registry( |
| 319 |
jinja_env, constants, Path("doc/message-registry.yaml") |
| 320 |
) |
| 321 |
|
| 322 |
args.func(args=args, registry=message_registry, jinja_env=jinja_env) |