Debian Codegraph @

debian/lib/python/debian_linux/utils.py

raw
1 import io
2 import os
3 import re
4 import textwrap
5 import typing
6
7 import jinja2
8
9 from .dataclasses_deb822 import read_deb822
10 from .debian import SourcePackage, BinaryPackage, TestsControl
11
12
13 class Templates(object):
14 dirs: list[str]
15 _cache: dict[str, str]
16 _jinja2: jinja2.Environment
17
18 def __init__(self, dirs: list[str] = ["debian/templates"]) -> None:
19 self.dirs = dirs
20
21 self._cache = {}
22 self._jinja2 = jinja2.Environment(
23 # autoescape uses HTML safe escaping, which does not help us
24 autoescape=False,
25 keep_trailing_newline=True,
26 trim_blocks=True,
27 undefined=jinja2.StrictUndefined,
28 )
29
30 def _read(self, name: str) -> typing.Any:
31 pkgid, name = name.rsplit('.', 1)
32
33 for suffix in ['.j2', '.in', '']:
34 for dir in self.dirs:
35 filename = "%s/%s.%s%s" % (dir, pkgid, name, suffix)
36 if os.path.exists(filename):
37 with open(filename, 'r', encoding='utf-8') as f:
38 return (f.read(), suffix)
39
40 raise KeyError(name)
41
42 def _get(self, key: str) -> typing.Any:
43 try:
44 return self._cache[key]
45 except KeyError:
46 self._cache[key] = value = self._read(key)
47 return value
48
49 def get(self, key: str, context: dict[str, str] = {}) -> str:
50 value = self._get(key)
51 suffix = value[1]
52
53 if context:
54 if suffix == '.in':
55 try:
56 def subst(match):
57 return context[match.group(1)]
58 return re.sub(r'@([-_a-z0-9]+)@', subst, str(value[0]))
59 except KeyError as e:
60 raise RuntimeError(f'templates/{key}.in: {e} is undefined') from None
61
62 elif suffix == '.j2':
63 try:
64 return self._jinja2.from_string(value[0]).render(context)
65 except jinja2.exceptions.UndefinedError as e:
66 raise RuntimeError(f'templates/{key}.j2: {e}') from None
67
68 return value[0]
69
70 def get_control(
71 self, key: str, context: dict[str, str] = {},
72 ) -> typing.Iterable[BinaryPackage]:
73 return read_deb822(BinaryPackage, io.StringIO(self.get(key, context)))
74
75 def get_source_control(
76 self, key: str, context: dict[str, str] = {},
77 ) -> typing.Iterable[SourcePackage]:
78 return read_deb822(SourcePackage, io.StringIO(self.get(key, context)))
79
80 def get_tests_control(
81 self, key: str, context: dict[str, str] = {},
82 ) -> typing.Iterable[TestsControl]:
83 return read_deb822(TestsControl, io.StringIO(self.get(key, context)))
84
85
86 class TextWrapper(textwrap.TextWrapper):
87 wordsep_re = re.compile(
88 r'(\s+|' # any whitespace
89 r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash