debputy.dh.debhelper_emulation

src/debputy/dh/debhelper_emulation.py
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
import dataclasses
import os.path
import re
import shutil
from re import Match
from typing import (
    Optional,
    Union,
    Tuple,
    cast,
    Any,
    List,
)
from collections.abc import Callable, Iterable, Sequence, Mapping

from debputy.packages import BinaryPackage
from debputy.plugin.api import VirtualPath
from debputy.substitution import Substitution
from debputy.util import ensure_dir, print_command, _error

SnippetReplacement = Union[str, Callable[[str], str]]
MAINTSCRIPT_TOKEN_NAME_PATTERN = r"[A-Za-z0-9_.+]+"
MAINTSCRIPT_TOKEN_NAME_REGEX = re.compile(MAINTSCRIPT_TOKEN_NAME_PATTERN)
MAINTSCRIPT_TOKEN_REGEX = re.compile(f"#({MAINTSCRIPT_TOKEN_NAME_PATTERN})#")
_ARCH_FILTER_START = re.compile(r"^\s*(\[([^]]*)])[ \t]+")
_ARCH_FILTER_END = re.compile(r"\s+(\[([^]]*)])\s*$")
_BUILD_PROFILE_FILTER = re.compile(r"(<([^>]*)>(?:\s+<([^>]*)>)*)")


class CannotEmulateExecutableDHConfigFile(Exception):
    def message(self) -> str:
        return cast("str", self.args[0])

    def config_file(self) -> VirtualPath:
        return cast("VirtualPath", self.args[1])


@dataclasses.dataclass(slots=True, frozen=True)
class DHConfigFileLine:
    config_file: VirtualPath
    line_no: int
    executable_config: bool
    original_line: str
    tokens: Sequence[str]
    arch_filter: str | None
    build_profile_filter: str | None

    def conditional_key(self) -> tuple[str, ...]:
        k = []
        if self.arch_filter is not None:
            k.append("arch")
            k.append(self.arch_filter)
        if self.build_profile_filter is not None:
            k.append("build-profiles")
            k.append(self.build_profile_filter)
        return tuple(k)

    def conditional(self) -> Mapping[str, Any] | None:
        filters = []
        if self.arch_filter is not None:
            filters.append({"arch-matches": self.arch_filter})
        if self.build_profile_filter is not None:
            filters.append({"build-profiles-matches": self.build_profile_filter})
        if not filters:
            return None
        if len(filters) == 1:
            return filters[0]
        return {"all-of": filters}


def dhe_dbgsym_root_dir(binary_package: BinaryPackage) -> str:
    return os.path.join("debian", ".debhelper", binary_package.name, "dbgsym-root")


def read_dbgsym_file(binary_package: BinaryPackage) -> list[str]:
    dbgsym_id_file = os.path.join(
        "debian", ".debhelper", binary_package.name, "dbgsym-build-ids"
    )
    try:
        with open(dbgsym_id_file, encoding="utf-8") as fd:
            return fd.read().split()
    except FileNotFoundError:
        return []


def assert_no_dbgsym_migration(binary_package: BinaryPackage) -> None:
    dbgsym_migration_file = os.path.join(
        "debian", ".debhelper", binary_package.name, "dbgsym-migration"
    )
    if os.path.lexists(dbgsym_migration_file):
        _error(
            "Sorry, debputy does not support dh_strip --dbgsym-migration feature. Please either finish the"
            " migration first or migrate to debputy later"
        )


def _prune_match(
    line: str,
    match: Match[str] | None,
    match_mapper: Callable[[Match[str]], str] | None = None,
) -> tuple[str, str | None]:
    if match is None:
        return line, None
    s, e = match.span()
    if match_mapper:
        matched_part = match_mapper(match)
    else:
        matched_part = line[s:e]
    # We prune exactly the matched part and assume the regexes leaves behind spaces if they were important.
    line = line[:s] + line[e:]
    # One special-case, if the match is at the beginning or end, then we can safely discard left
    # over whitespace.
    return line.strip(), matched_part


def dhe_filedoublearray(
    config_file: VirtualPath,
    substitution: Substitution,
    *,
    allow_dh_exec_rename: bool = False,
) -> Iterable[DHConfigFileLine]:
    with config_file.open() as fd:
        is_executable = config_file.is_executable
        for line_no, orig_line in enumerate(fd, start=1):
            arch_filter = None
            build_profile_filter = None
            if (
                line_no == 1
                and is_executable
                and not orig_line.startswith(
                    ("#!/usr/bin/dh-exec", "#! /usr/bin/dh-exec")
                )
            ):
                raise CannotEmulateExecutableDHConfigFile(
                    "Only #!/usr/bin/dh-exec based executables can be emulated",
                    config_file,
                )
            orig_line = orig_line.rstrip("\n")
            line = orig_line.strip()
            if not line or line.startswith("#"):
                continue
            if is_executable:
                if "=>" in line and not allow_dh_exec_rename:
                    raise CannotEmulateExecutableDHConfigFile(
                        'Cannot emulate dh-exec\'s "=>" feature to rename files for the concrete file',
                        config_file,
                    )
                line, build_profile_filter = _prune_match(
                    line,
                    _BUILD_PROFILE_FILTER.search(line),
                )
                line, arch_filter = _prune_match(
                    line,
                    _ARCH_FILTER_START.search(line) or _ARCH_FILTER_END.search(line),
                    # Remove the enclosing []
                    lambda m: m.group(1)[1:-1].strip(),
                )

            parts = tuple(
                substitution.substitute(
                    w, f'{config_file.path} line {line_no} token "{w}"'
                )
                for w in line.split()
            )
            yield DHConfigFileLine(
                config_file,
                line_no,
                is_executable,
                orig_line,
                parts,
                arch_filter,
                build_profile_filter,
            )


def dhe_pkgfile(
    debian_dir: VirtualPath,
    binary_package: BinaryPackage,
    basename: str,
    always_fallback_to_packageless_variant: bool = False,
    bug_950723_prefix_matching: bool = False,
) -> VirtualPath | None:
    # TODO: Architecture specific files
    maybe_at_suffix = "@" if bug_950723_prefix_matching else ""
    possible_names = [f"{binary_package.name}{maybe_at_suffix}.{basename}"]
    if binary_package.is_main_package or always_fallback_to_packageless_variant:
        possible_names.append(
            f"{basename}@" if bug_950723_prefix_matching else basename
        )

    for name in possible_names:
        match = debian_dir.get(name)
        if match is not None and not match.is_dir:
            return match
    return None


def dhe_pkgdir(
    debian_dir: VirtualPath,
    binary_package: BinaryPackage,
    basename: str,
) -> VirtualPath | None:
    possible_names = [f"{binary_package.name}.{basename}"]
    if binary_package.is_main_package:
        possible_names.append(basename)

    for name in possible_names:
        match = debian_dir.get(name)
        if match is not None and match.is_dir:
            return match
    return None