| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import argparse |
| 6 |
import gzip |
| 7 |
import itertools |
| 8 |
import json |
| 9 |
import multiprocessing |
| 10 |
import os |
| 11 |
import shlex |
| 12 |
import subprocess |
| 13 |
import sys |
| 14 |
import xml.etree.ElementTree as ET |
| 15 |
from abc import ABCMeta, abstractmethod |
| 16 |
from dataclasses import dataclass |
| 17 |
from functools import partial |
| 18 |
from pathlib import Path |
| 19 |
from typing import ( |
| 20 |
TYPE_CHECKING, |
| 21 |
BinaryIO, |
| 22 |
ClassVar, |
| 23 |
Iterable, |
| 24 |
Iterator, |
| 25 |
NoReturn, |
| 26 |
Protocol, |
| 27 |
Sequence, |
| 28 |
TextIO, |
| 29 |
TypeVar, |
| 30 |
cast, |
| 31 |
) |
| 32 |
|
| 33 |
# TODO: import unconditionally Self from typing once we raise Python requirement to 3.11+ |
| 34 |
if TYPE_CHECKING: |
| 35 |
from typing_extensions import Self |
| 36 |
|
| 37 |
WILDCARD = "*" |
| 38 |
|
| 39 |
DEFAULT_XKB_ROOT = Path("@XKB_CONFIG_ROOT@") |
| 40 |
|
| 41 |
# Meson needs to fill this in so we can call the tool in the buildir. |
| 42 |
EXTRA_PATH = "@MESON_BUILD_ROOT@" |
| 43 |
os.environ["PATH"] = ":".join(filter(bool, (EXTRA_PATH, os.getenv("PATH")))) |
| 44 |
|
| 45 |
# Environment variable to get the right level of log |
| 46 |
os.environ["XKB_LOG_LEVEL"] = "warning" |
| 47 |
os.environ["XKB_LOG_VERBOSITY"] = "10" |
| 48 |
|
| 49 |
|
| 50 |
@dataclass |
| 51 |
class RMLVO: |
| 52 |
DEFAULT_RULES: ClassVar[str] = "evdev" |
| 53 |
DEFAULT_MODEL: ClassVar[str] = "pc105" |
| 54 |
DEFAULT_LAYOUT: ClassVar[str] = "us" |
| 55 |
rules: str |
| 56 |
model: str |
| 57 |
layout: str |
| 58 |
variant: str | None |
| 59 |
option: str | None |
| 60 |
|
| 61 |
def __iter__(self) -> Iterator[str | None]: |
| 62 |
yield self.rules |
| 63 |
yield self.model |
| 64 |
yield self.layout |
| 65 |
yield self.variant |
| 66 |
yield self.option |
| 67 |
|
| 68 |
@property |
| 69 |
def rmlvo(self) -> Iterator[tuple[str, str]]: |
| 70 |
yield ("rules", self.rules) |
| 71 |
yield ("model", self.model) |
| 72 |
yield ("layout", self.layout) |
| 73 |
# Keep only defined and non-empty values |
| 74 |
if self.variant is not None: |
| 75 |
yield ("variant", self.variant) |
| 76 |
if self.option is not None: |
| 77 |
yield ("option", self.option) |
| 78 |
|
| 79 |
@classmethod |
| 80 |
def from_rmlvo( |
| 81 |
cls, |
| 82 |
rules: str | None = None, |
| 83 |
model: str | None = None, |
| 84 |
layout: str | None = None, |
| 85 |
variant: str | None = None, |
| 86 |
option: str | None = None, |
| 87 |
) -> Self: |
| 88 |
return cls( |
| 89 |
# We need to force a value for RML components |
| 90 |
rules or cls.DEFAULT_RULES, |
| 91 |
model or cls.DEFAULT_MODEL, |
| 92 |
layout or cls.DEFAULT_LAYOUT, |
| 93 |
variant, |
| 94 |
option, |
| 95 |
) |
| 96 |
|
| 97 |
|
| 98 |
@dataclass |
| 99 |
class Invocation(RMLVO, metaclass=ABCMeta): |
| 100 |
exitstatus: int = 77 # default to “skipped” |
| 101 |
error: str | None = None |
| 102 |
keymap: bytes = b"" |
| 103 |
command: str = "" # The fully compiled keymap |
| 104 |
|
| 105 |
def __str_iter(self) -> Iterator[str]: |
| 106 |
yield f"- rmlvo: {self.to_yaml(self.rmlvo)}" |
| 107 |
yield f" cmd: {json.dumps(self.command)}" |
| 108 |
yield f" status: {self.exitstatus}" |
| 109 |
if self.error: |
| 110 |
yield f" error: {json.dumps(self.error.strip())}" |
| 111 |
|
| 112 |
def __str__(self) -> str: |
| 113 |
return "\n".join(self.__str_iter()) |
| 114 |
|
| 115 |
@property |
| 116 |
def short(self) -> Iterator[tuple[str, str | int]]: |
| 117 |
yield from self.rmlvo |
| 118 |
yield ("status", self.exitstatus) |
| 119 |
if self.error is not None: |
| 120 |
yield ("error", self.error) |
| 121 |
|
| 122 |
@staticmethod |
| 123 |
def to_yaml(xs: Iterable[tuple[str, str | int]]) -> str: |
| 124 |
fields = ", ".join(f"{k}: {json.dumps(v)}" for k, v in xs) |
| 125 |
return f"{{ {fields} }}" |
| 126 |
|
| 127 |
def _write(self, fd: BinaryIO) -> None: |
| 128 |
fd.write(f"// {self.to_yaml(self.rmlvo)}\n".encode("utf-8")) |
| 129 |
fd.write(self.keymap) |
| 130 |
|
| 131 |
def _write_keymap(self, output_dir: Path, compress: int) -> None: |
| 132 |
layout = self.layout |
| 133 |
if self.variant: |
| 134 |
layout += f"({self.variant})" |
| 135 |
if self.option: |
| 136 |
layout += f"+{self.option}" |
| 137 |
(output_dir / self.model).mkdir(exist_ok=True) |
| 138 |
keymap_file = output_dir / self.model / layout |
| 139 |
if compress: |
| 140 |
keymap_file = keymap_file.with_suffix(".gz") |
| 141 |
with gzip.open(keymap_file, "wb", compresslevel=compress) as fd: |
| 142 |
self._write(fd) |
| 143 |
fd.close() |
| 144 |
else: |
| 145 |
with keymap_file.open("wb") as fd: |
| 146 |
self._write(fd) |
| 147 |
|
| 148 |
def _print_result(self, short: bool, verbose: bool) -> None: |
| 149 |
if self.exitstatus != 0: |
| 150 |
target = sys.stderr |
| 151 |
else: |
| 152 |
target = sys.stdout if verbose else None |
| 153 |
|
| 154 |
if target: |
| 155 |
if short: |
| 156 |
print("-", self.to_yaml(self.short), file=target) |
| 157 |
else: |
| 158 |
print(self, file=target) |
| 159 |
|
| 160 |
@classmethod |
| 161 |
@abstractmethod |
| 162 |
def run( |
| 163 |
cls, |
| 164 |
i: Self, |
| 165 |
xkb_root: Path, |
| 166 |
output_dir: Path | None, |
| 167 |
compress: int, |
| 168 |
*args, |
| 169 |
**kwargs, |
| 170 |
) -> Self: ... |
| 171 |
|
| 172 |
@classmethod |
| 173 |
def run_all( |
| 174 |
cls, |
| 175 |
xkb_root: Path, |
| 176 |
combos: Iterable[Self], |
| 177 |
combos_count: int, |
| 178 |
njobs: int, |
| 179 |
keymap_output_dir: Path | None, |
| 180 |
verbose: bool, |
| 181 |
short: bool, |
| 182 |
progress_bar: ProgressBar[Iterable[Self]], |
| 183 |
chunksize: int, |
| 184 |
compress: int, |
| 185 |
**kwargs, |
| 186 |
) -> bool: |
| 187 |
if keymap_output_dir: |
| 188 |
try: |
| 189 |
keymap_output_dir.mkdir(parents=True) |
| 190 |
except FileExistsError as e: |
| 191 |
print(e, file=sys.stderr) |
| 192 |
return False |
| 193 |
|
| 194 |
failed = False |
| 195 |
with multiprocessing.Pool(njobs) as p: |
| 196 |
f = partial( |
| 197 |
cls.run, |
| 198 |
xkb_root=xkb_root, |
| 199 |
output_dir=keymap_output_dir, |
| 200 |
compress=compress, |
| 201 |
) |
| 202 |
results = p.imap_unordered(f, combos, chunksize=chunksize) |
| 203 |
for invocation in progress_bar( |
| 204 |
results, total=combos_count, file=sys.stdout |
| 205 |
): |
| 206 |
if invocation.exitstatus != 0: |
| 207 |
failed = True |
| 208 |
|
| 209 |
invocation._print_result(short, verbose) |
| 210 |
|
| 211 |
return failed |
| 212 |
|
| 213 |
|
| 214 |
@dataclass |
| 215 |
class XkbCompInvocation(Invocation): |
| 216 |
@classmethod |
| 217 |
def run( |
| 218 |
cls, |
| 219 |
i: Self, |
| 220 |
xkb_root: Path, |
| 221 |
output_dir: Path | None, |
| 222 |
compress: int, |
| 223 |
*args, |
| 224 |
**kwargs, |
| 225 |
) -> Self: |
| 226 |
i._run(xkb_root, not output_dir) |
| 227 |
if output_dir: |
| 228 |
i._write_keymap(output_dir, compress) |
| 229 |
return i |
| 230 |
|
| 231 |
def _run(self, xkb_root: Path, test: bool) -> None: |
| 232 |
setxkbmap_args = ( |
| 233 |
"setxkbmap", |
| 234 |
"-print", |
| 235 |
# Informative only; we set CWD to ensure proper rules are loaded |
| 236 |
"-I", |
| 237 |
str(xkb_root), |
| 238 |
*itertools.chain.from_iterable((f"-{k}", v) for k, v in self.rmlvo), |
| 239 |
) |
| 240 |
xkbcomp_args = ("xkbcomp", "-I", f"-I{xkb_root}", "-xkb", "-", "-") |
| 241 |
|
| 242 |
self.command = shlex.join(itertools.chain(setxkbmap_args, "|", xkbcomp_args)) |
| 243 |
|
| 244 |
setxkbmap = subprocess.Popen( |
| 245 |
setxkbmap_args, |
| 246 |
stdout=subprocess.PIPE, |
| 247 |
stderr=subprocess.PIPE, |
| 248 |
universal_newlines=True, |
| 249 |
cwd=xkb_root, |
| 250 |
) |
| 251 |
stdout, stderr = setxkbmap.communicate() |
| 252 |
if "Cannot open display" in stderr: |
| 253 |
self.error = stderr |
| 254 |
self.exitstatus = 90 |
| 255 |
else: |
| 256 |
xkbcomp = subprocess.Popen( |
| 257 |
xkbcomp_args, |
| 258 |
stdin=subprocess.PIPE, |
| 259 |
stdout=subprocess.PIPE, |
| 260 |
stderr=subprocess.PIPE, |
| 261 |
universal_newlines=True, |
| 262 |
) |
| 263 |
stdout, stderr = xkbcomp.communicate(stdout) |
| 264 |
if xkbcomp.returncode != 0: |
| 265 |
self.error = ( |
| 266 |
"failed to compile keymap:\n" |
| 267 |
f"------\nstderr:\n{stderr}\n" |
| 268 |
f"------\nstdout:\n{stdout}\n" |
| 269 |
) |
| 270 |
self.exitstatus = xkbcomp.returncode |
| 271 |
else: |
| 272 |
self.keymap = stdout.encode("utf-8") |
| 273 |
self.exitstatus = 0 |
| 274 |
|
| 275 |
|
| 276 |
@dataclass |
| 277 |
class XkbCompToXkbcommonInvocation(XkbCompInvocation): |
| 278 |
""" |
| 279 |
Use setxkbcomp & xkbcomp, then pipe the result to xkbcli in order to enable |
| 280 |
comparison with direct xkbcli compilation with the same format. |
| 281 |
""" |
| 282 |
|
| 283 |
def _run(self, xkb_root: Path, test: bool) -> None: |
| 284 |
super()._run(xkb_root, test) |
| 285 |
|
| 286 |
if self.exitstatus: |
| 287 |
return |
| 288 |
|
| 289 |
if test: |
| 290 |
return |
| 291 |
|
| 292 |
args = ( |
| 293 |
"xkbcli-compile-keymap", # this is run in the builddir |
| 294 |
# Not used: keymap is already compiled |
| 295 |
# "--include", xkb_root, |
| 296 |
# Not needed, because we set XKB_LOG_LEVEL and XKB_LOG_VERBOSITY in env |
| 297 |
# "--verbose", |
| 298 |
"--keymap", |
| 299 |
) |
| 300 |
|
| 301 |
try: |
| 302 |
completed = subprocess.run( |
| 303 |
args, |
| 304 |
check=True, |
| 305 |
capture_output=True, |
| 306 |
input=self.keymap, |
| 307 |
) |
| 308 |
except subprocess.CalledProcessError as err: |
| 309 |
self.error = ( |
| 310 |
"failed to compile keymap:\n" |
| 311 |
f"------\nstderr:\n{err.stderr}\n" |
| 312 |
f"------\nstdout:\n{err.stdout}\n" |
| 313 |
f"------\nstdin:\n{self.keymap.decode('utf-8')}\n" |
| 314 |
) |
| 315 |
self.exitstatus = err.returncode |
| 316 |
else: |
| 317 |
self.keymap = completed.stdout |
| 318 |
|
| 319 |
|
| 320 |
@dataclass |
| 321 |
class XkbcommonInvocation(Invocation): |
| 322 |
UNRECOGNIZED_KEYSYM_ERROR: ClassVar[str] = "XKB-107" |
| 323 |
|
| 324 |
def _check_stderr(self, stderr: str) -> bool: |
| 325 |
if self.UNRECOGNIZED_KEYSYM_ERROR in stderr: |
| 326 |
for line in stderr.splitlines(): |
| 327 |
if self.UNRECOGNIZED_KEYSYM_ERROR in line: |
| 328 |
self.error = line |
| 329 |
break |
| 330 |
self.exitstatus = 99 # tool doesn't generate this one |
| 331 |
return False |
| 332 |
else: |
| 333 |
self.exitstatus = 0 |
| 334 |
return True |
| 335 |
|
| 336 |
@classmethod |
| 337 |
def run( |
| 338 |
cls, |
| 339 |
i: Self, |
| 340 |
xkb_root: Path, |
| 341 |
output_dir: Path | None, |
| 342 |
compress: int, |
| 343 |
*args, |
| 344 |
**kwargs, |
| 345 |
) -> Self: |
| 346 |
i._run(xkb_root, output_dir, not output_dir, compress) |
| 347 |
return i |
| 348 |
|
| 349 |
def _run( |
| 350 |
self, xkb_root: Path, output_dir: Path | None, test: bool, compress: int |
| 351 |
) -> None: |
| 352 |
args = ( |
| 353 |
"xkbcli-compile-keymap", # this is run in the builddir |
| 354 |
"--include", |
| 355 |
str(xkb_root), |
| 356 |
# Not needed, because we set XKB_LOG_LEVEL and XKB_LOG_VERBOSITY in env |
| 357 |
# "--verbose", |
| 358 |
*itertools.chain.from_iterable((f"--{k}", v) for k, v in self.rmlvo), |
| 359 |
) |
| 360 |
if test: |
| 361 |
args += ("--test",) |
| 362 |
self.command = shlex.join(args) |
| 363 |
try: |
| 364 |
completed = subprocess.run(args, text=True, check=True, capture_output=True) |
| 365 |
except subprocess.CalledProcessError as err: |
| 366 |
self.error = ( |
| 367 |
"failed to compile keymap:\n" |
| 368 |
f"------\nstderr:\n{err.stderr}\n" |
| 369 |
f"------\nstdout:\n{err.stdout}\n" |
| 370 |
) |
| 371 |
self.exitstatus = err.returncode |
| 372 |
else: |
| 373 |
if self._check_stderr(completed.stderr): |
| 374 |
self.keymap = completed.stdout.encode("utf-8") |
| 375 |
if output_dir: |
| 376 |
self._write_keymap(output_dir, compress) |
| 377 |
|
| 378 |
|
| 379 |
@dataclass |
| 380 |
class XkbcommonToXkbcompInvocation(XkbcommonInvocation): |
| 381 |
""" |
| 382 |
Use xkbcli, then pipe the result to xkbcomp in order to check |
| 383 |
that xkbcomp can parse xkbcommon output. |
| 384 |
""" |
| 385 |
|
| 386 |
def _run( |
| 387 |
self, xkb_root: Path, output_dir: Path | None, test: bool, compress: int |
| 388 |
) -> None: |
| 389 |
super()._run(xkb_root, output_dir, False, compress) |
| 390 |
|
| 391 |
if self.exitstatus: |
| 392 |
return |
| 393 |
|
| 394 |
args = ("xkbcomp", "-xkb", "-opt", "g", "-", "-") |
| 395 |
|
| 396 |
try: |
| 397 |
completed = subprocess.run( |
| 398 |
args, |
| 399 |
check=True, |
| 400 |
capture_output=True, |
| 401 |
input=self.keymap, |
| 402 |
) |
| 403 |
except subprocess.CalledProcessError as err: |
| 404 |
self.error = ( |
| 405 |
"failed to compile keymap:\n" |
| 406 |
f"------\nstderr:\n{err.stderr}\n" |
| 407 |
f"------\nstdout:\n{err.stdout}\n" |
| 408 |
f"------\nstdin:\n{self.keymap.decode('utf-8')}\n" |
| 409 |
) |
| 410 |
self.exitstatus = err.returncode |
| 411 |
else: |
| 412 |
self.keymap = completed.stdout |
| 413 |
if output_dir: |
| 414 |
self._write_keymap(output_dir, compress) |
| 415 |
|
| 416 |
|
| 417 |
@dataclass |
| 418 |
class Layout: |
| 419 |
name: str |
| 420 |
variants: list[str | None] |
| 421 |
|
| 422 |
@classmethod |
| 423 |
def parse(cls, e: ET.Element, variant: list[str] | None = None) -> Self: |
| 424 |
if (name_elem := e.find("configItem/name")) is None or name_elem is None: |
| 425 |
raise ValueError("Layout name not found") |
| 426 |
if not variant: |
| 427 |
variants = [None] + [ |
| 428 |
cls.parse_text(v) |
| 429 |
for v in e.findall("variantList/variant/configItem/name") |
| 430 |
] |
| 431 |
else: |
| 432 |
variants = cast(list[str | None], variant) |
| 433 |
return cls(cls.parse_text(e.find("configItem/name")), variants) |
| 434 |
|
| 435 |
@staticmethod |
| 436 |
def parse_text(e: ET.Element | None) -> str: |
| 437 |
if e is None or not e.text: |
| 438 |
raise ValueError("Name not found") |
| 439 |
return e.text |
| 440 |
|
| 441 |
|
| 442 |
class Registry: |
| 443 |
@classmethod |
| 444 |
def parse_path(cls, xkb_root: Path, path: Path) -> Path: |
| 445 |
if path.is_file(): |
| 446 |
# File exists: return unchanged |
| 447 |
return path |
| 448 |
elif len(path.parts) == 1: |
| 449 |
# Lookup XML file in XKB root |
| 450 |
_path = ( |
| 451 |
path |
| 452 |
if path.suffix == ".xml" |
| 453 |
# NOTE: If we got evdev.extras, we want to keep the current suffix |
| 454 |
else path.with_suffix(f"{path.suffix}.xml") |
| 455 |
) |
| 456 |
_path = xkb_root / "rules" / _path |
| 457 |
if _path.is_file(): |
| 458 |
return _path |
| 459 |
raise ValueError(f"Cannot resolve registry file: {path}") |
| 460 |
|
| 461 |
@classmethod |
| 462 |
def parse( |
| 463 |
cls, |
| 464 |
paths: Sequence[Path], |
| 465 |
tool: type[Invocation], |
| 466 |
rules: str | None, |
| 467 |
model: str | None, |
| 468 |
layout: str | None, |
| 469 |
variant: str | None, |
| 470 |
option: str | None, |
| 471 |
) -> tuple[int, Iterator[Invocation]]: |
| 472 |
models: tuple[str, ...] = () |
| 473 |
layouts: tuple[Layout, ...] = () |
| 474 |
options: tuple[str, ...] = () |
| 475 |
|
| 476 |
if variant and not layout: |
| 477 |
raise ValueError("Variant must be set together with layout") |
| 478 |
|
| 479 |
for path in paths: |
| 480 |
root = ET.fromstring(path.read_text(encoding="utf-8")) |
| 481 |
|
| 482 |
# Models |
| 483 |
if model is None: |
| 484 |
models += tuple( |
| 485 |
e.text |
| 486 |
for e in root.findall("modelList/model/configItem/name") |
| 487 |
if e.text |
| 488 |
) |
| 489 |
elif not models: |
| 490 |
models += (model,) |
| 491 |
|
| 492 |
# Layouts/variants |
| 493 |
if layout: |
| 494 |
if variant is None: |
| 495 |
layouts += tuple( |
| 496 |
map( |
| 497 |
Layout.parse, |
| 498 |
( |
| 499 |
e |
| 500 |
for e in root.findall("layoutList/layout") |
| 501 |
if e.find(f"configItem/name[.='{layout}']") is not None |
| 502 |
), |
| 503 |
) |
| 504 |
) |
| 505 |
elif not layouts: |
| 506 |
layouts += ( |
| 507 |
Layout(layout, cast(list[str | None], variant.split(":"))), |
| 508 |
) |
| 509 |
else: |
| 510 |
layouts += tuple(map(Layout.parse, root.findall("layoutList/layout"))) |
| 511 |
|
| 512 |
# Options |
| 513 |
if option is None: |
| 514 |
options += tuple( |
| 515 |
e.text |
| 516 |
for e in root.findall("optionList/group/option/configItem/name") |
| 517 |
if e.text |
| 518 |
) |
| 519 |
elif not options and option: |
| 520 |
options += (option,) |
| 521 |
|
| 522 |
# Some registry may be only partial, e.g.: *.extras.xml |
| 523 |
if not models: |
| 524 |
models = (RMLVO.DEFAULT_MODEL,) |
| 525 |
if not layouts: |
| 526 |
layouts = (Layout(RMLVO.DEFAULT_LAYOUT, [None]),) |
| 527 |
|
| 528 |
count = len(models) * sum(len(l.variants) for l in layouts) * (1 + len(options)) |
| 529 |
|
| 530 |
# The list of combos can be huge, so better to use a generator instead |
| 531 |
def iter_combos() -> Iterator[Invocation]: |
| 532 |
for m in models: |
| 533 |
for l in layouts: |
| 534 |
for v in l.variants: |
| 535 |
yield tool.from_rmlvo( |
| 536 |
rules=rules, model=m, layout=l.name, variant=v, option=None |
| 537 |
) |
| 538 |
for opt in options: |
| 539 |
yield tool.from_rmlvo( |
| 540 |
rules=rules, |
| 541 |
model=m, |
| 542 |
layout=l.name, |
| 543 |
variant=v, |
| 544 |
option=opt, |
| 545 |
) |
| 546 |
|
| 547 |
return count, iter_combos() |
| 548 |
|
| 549 |
|
| 550 |
T = TypeVar("T") |
| 551 |
|
| 552 |
|
| 553 |
# Needed because Callable does not handle keywords args |
| 554 |
class ProgressBar(Protocol[T]): |
| 555 |
def __call__(self, x: T, total: int, file: TextIO | None) -> T: ... |
| 556 |
|
| 557 |
|
| 558 |
# The function generating the progress bar (if any). |
| 559 |
def create_progress_bar(verbose: bool) -> ProgressBar[T]: |
| 560 |
def noop_progress_bar(x: T, total: int, file: TextIO | None = None) -> T: |
| 561 |
return x |
| 562 |
|
| 563 |
progress_bar: ProgressBar[T] = noop_progress_bar |
| 564 |
if not verbose and os.isatty(sys.stdout.fileno()): |
| 565 |
try: |
| 566 |
from tqdm import tqdm |
| 567 |
|
| 568 |
progress_bar = cast(ProgressBar[T], tqdm) |
| 569 |
except ImportError: |
| 570 |
pass |
| 571 |
|
| 572 |
return progress_bar |
| 573 |
|
| 574 |
|
| 575 |
def main() -> NoReturn: |
| 576 |
parser = argparse.ArgumentParser( |
| 577 |
description=""" |
| 578 |
This tool compiles a keymap for each layout, variant and |
| 579 |
options combination in the given rules XML file. The output |
| 580 |
of this tool is YAML, use your favorite YAML parser to |
| 581 |
extract error messages. Errors are printed to stderr. |
| 582 |
""" |
| 583 |
) |
| 584 |
parser.add_argument( |
| 585 |
"paths", |
| 586 |
metavar="/path/to/rules.xml", |
| 587 |
nargs="*", |
| 588 |
type=Path, |
| 589 |
default=(), |
| 590 |
help="Path to xkeyboard-config's XML registry file", |
| 591 |
) |
| 592 |
parser.add_argument( |
| 593 |
"--xkb-root", |
| 594 |
default=DEFAULT_XKB_ROOT, |
| 595 |
type=Path, |
| 596 |
help="XKB root directory", |
| 597 |
) |
| 598 |
DEFAULT_TOOL = "xkbcommon" |
| 599 |
tools: dict[str, type[Invocation]] = { |
| 600 |
DEFAULT_TOOL: XkbcommonInvocation, |
| 601 |
"xkbcommon-xkbcomp": XkbcommonToXkbcompInvocation, |
| 602 |
"xkbcomp": XkbCompInvocation, |
| 603 |
"xkbcomp-xkbcommon": XkbCompToXkbcommonInvocation, |
| 604 |
} |
| 605 |
parser.add_argument( |
| 606 |
"--tool", |
| 607 |
choices=tools.keys(), |
| 608 |
type=str, |
| 609 |
default=DEFAULT_TOOL, |
| 610 |
help="parsing tool to use", |
| 611 |
) |
| 612 |
parser.add_argument( |
| 613 |
"--jobs", |
| 614 |
"-j", |
| 615 |
type=int, |
| 616 |
default=4 * (os.cpu_count() or 1), |
| 617 |
help="number of processes to use", |
| 618 |
) |
| 619 |
parser.add_argument("--chunksize", default=1, type=int) |
| 620 |
parser.add_argument("--verbose", "-v", default=False, action="store_true") |
| 621 |
parser.add_argument( |
| 622 |
"--short", default=False, action="store_true", help="Concise output" |
| 623 |
) |
| 624 |
parser.add_argument( |
| 625 |
"--keymap-output-dir", |
| 626 |
default=None, |
| 627 |
type=Path, |
| 628 |
help="Directory to print compiled keymaps to", |
| 629 |
) |
| 630 |
parser.add_argument( |
| 631 |
"--compress", type=int, default=0, help="Compression level of keymaps files" |
| 632 |
) |
| 633 |
parser.add_argument( |
| 634 |
"--rules", default=RMLVO.DEFAULT_RULES, type=str, help="Rule set to use" |
| 635 |
) |
| 636 |
parser.add_argument( |
| 637 |
"--model", default="", type=str, help="Only test the given model" |
| 638 |
) |
| 639 |
parser.add_argument( |
| 640 |
"--layout", default=WILDCARD, type=str, help="Only test the given layout" |
| 641 |
) |
| 642 |
parser.add_argument( |
| 643 |
"--variant", |
| 644 |
default=WILDCARD, |
| 645 |
type=str, |
| 646 |
help="Only test the given variants (colon-separated list)", |
| 647 |
) |
| 648 |
parser.add_argument( |
| 649 |
"--option", default=WILDCARD, type=str, help="Only test the given option" |
| 650 |
) |
| 651 |
parser.add_argument( |
| 652 |
"--no-iterations", "-1", action="store_true", help="Only test one combo" |
| 653 |
) |
| 654 |
|
| 655 |
args = parser.parse_args() |
| 656 |
|
| 657 |
xkb_root: Path = args.xkb_root |
| 658 |
verbose: bool = args.verbose |
| 659 |
short = args.short |
| 660 |
keymapdir = args.keymap_output_dir |
| 661 |
progress_bar: ProgressBar[Iterable[Invocation]] = create_progress_bar(verbose) |
| 662 |
|
| 663 |
tool = tools[args.tool] |
| 664 |
|
| 665 |
# NOTE: We test only one set of rules; handle wild card only for consistency |
| 666 |
# with other components. |
| 667 |
rules: str | None = None if args.rules == WILDCARD else args.rules |
| 668 |
model: str | None = None if args.model == WILDCARD else args.model |
| 669 |
layout: str | None = None if args.layout == WILDCARD else args.layout |
| 670 |
variant: str | None = None if args.variant == WILDCARD else args.variant |
| 671 |
option: str | None = None if args.option == WILDCARD else args.option |
| 672 |
|
| 673 |
if not args.paths: |
| 674 |
# If there is no given registry, fallback to the given rules, |
| 675 |
# else fallback to the default rules. |
| 676 |
path = xkb_root / "rules" / (rules or RMLVO.DEFAULT_RULES) |
| 677 |
paths = (path.with_suffix(f"{path.suffix}.xml"),) |
| 678 |
else: |
| 679 |
paths = tuple(Registry.parse_path(xkb_root, p) for p in args.paths) |
| 680 |
|
| 681 |
# This need to be valid YAML. Currently unused, so left as comments |
| 682 |
print("# xkb root:", json.dumps(str(xkb_root)), file=sys.stderr) |
| 683 |
print("# paths:", json.dumps(tuple(map(str, paths))), file=sys.stderr) |
| 684 |
|
| 685 |
if args.no_iterations: |
| 686 |
combos = ( |
| 687 |
tool.from_rmlvo( |
| 688 |
rules=rules, model=model, layout=layout, variant=variant, option=option |
| 689 |
), |
| 690 |
) |
| 691 |
count = len(combos) |
| 692 |
iter_combos = iter(combos) |
| 693 |
else: |
| 694 |
count, iter_combos = Registry.parse( |
| 695 |
paths, tool, rules, model, layout, variant, option |
| 696 |
) |
| 697 |
|
| 698 |
failed = tool.run_all( |
| 699 |
xkb_root=xkb_root, |
| 700 |
combos=iter_combos, |
| 701 |
combos_count=count, |
| 702 |
njobs=args.jobs, |
| 703 |
keymap_output_dir=keymapdir, |
| 704 |
verbose=verbose, |
| 705 |
short=short, |
| 706 |
progress_bar=progress_bar, |
| 707 |
chunksize=args.chunksize, |
| 708 |
compress=args.compress, |
| 709 |
) |
| 710 |
sys.exit(failed) |
| 711 |
|
| 712 |
|
| 713 |
if __name__ == "__main__": |
| 714 |
try: |
| 715 |
main() |
| 716 |
except KeyboardInterrupt: |
| 717 |
print("# Exiting after Ctrl+C") |