Debian Codegraph @

python/tests/testsigs/parse/debsigs.py

raw
1 # SPDX-FileCopyrightText: Peter Pentchev <[email protected]>
2 # SPDX-License-Identifier: GPL-2.0-or-later
3 """Parse the human-readable output of `debsigs --list`."""
4
5 from __future__ import annotations
6
7 import typing
8
9 import pyparsing as pyp
10
11 from testsigs import defs
12
13
14 if typing.TYPE_CHECKING:
15 from typing import Final
16
17
18 _p_first = pyp.Literal("GPG signatures in ") + pyp.CharsNotIn("\n") + pyp.Char("\n")
19
20 _p_sig_type = pyp.Regex("[A-Za-z0-9_]+")
21
22 _p_hex = pyp.Word("0123456789ABCDEF")
23
24 _p_sig = (
25 _p_sig_type
26 + pyp.Literal(": signed by ").suppress()
27 + _p_hex
28 + pyp.Literal(" on ").suppress()
29 + pyp.CharsNotIn("\n").suppress()
30 + pyp.Char("\n").suppress()
31 )
32
33
34 @_p_sig.set_parse_action
35 def _parse_sig(tokens: pyp.ParseResults) -> defs.DebSig:
36 """Parse a signature line."""
37 match tokens.as_list():
38 case [sig_type, key_id] if isinstance(sig_type, str) and isinstance(key_id, str):
39 return defs.DebSig(sig_type=sig_type, key_id=key_id)
40
41 case _:
42 raise RuntimeError(repr(tokens))
43
44
45 _p_last = pyp.Literal(" *** NO ATTEMPT HAS BEEN MADE") + pyp.CharsNotIn("\n") + pyp.Char("\n")
46
47 _p_list = _p_first.suppress() + pyp.ZeroOrMore(_p_sig) + _p_last.suppress()
48
49 _p_list_complete = _p_list.leave_whitespace().parse_with_tabs()
50
51
52 def parse_list(output: str) -> list[defs.DebSig]:
53 """Parse the output of `debsigs --list`, extract the info we care about."""
54 res: Final = _p_list_complete.parse_string(output, parse_all=True).as_list()
55 if not all(isinstance(sig, defs.DebSig) for sig in res):
56 raise RuntimeError(repr(res))
57 return res