debputy.packager_provided_files

src/debputy/packager_provided_files.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
import collections
import dataclasses
from typing import (
    Dict,
    List,
    Optional,
    Tuple,
    TYPE_CHECKING,
    FrozenSet,
)
from collections.abc import Mapping, Iterable, Sequence, Container

from debputy.packages import BinaryPackage
from debputy.plugin.api import VirtualPath
from debputy.plugin.api.impl_types import (
    PackagerProvidedFileClassSpec,
    PluginProvidedKnownPackagingFile,
)
from debputy.util import _error, CAN_DETECT_TYPOS, detect_possible_typo

if TYPE_CHECKING:
    from debputy.plugin.api.feature_set import PluginProvidedFeatureSet


_KNOWN_NON_TYPO_EXTENSIONS = frozenset(
    {
        "conf",
        "config",
        "sh",
        "yml",
        "yaml",
        "json",
        "bash",
        "pl",
        "py",
        "md",
        "rst",
        # Fairly common image format in older packages
        "xpm",
        # Cruft of various kind (for unclean work directories). Just to avoid stupid false-positives.
        "bak",
        "tmp",
        "temp",
        "orig",
        "rej",
    }
)


@dataclasses.dataclass(frozen=True, slots=True)
class PackagerProvidedFile:
    path: VirtualPath
    package_name: str
    installed_as_basename: str
    provided_key: str
    definition: PackagerProvidedFileClassSpec
    match_priority: int = 0
    fuzzy_match: bool = False
    uses_explicit_package_name: bool = False
    name_segment: str | None = None
    architecture_restriction: str | None = None
    expected_path: str | None = None

    def compute_dest(self) -> tuple[str, str]:
        return self.definition.compute_dest(
            self.installed_as_basename,
            owning_package=self.package_name,
            path=self.path,
        )


@dataclasses.dataclass(slots=True)
class PerPackagePackagerProvidedResult:
    auto_installable: list[PackagerProvidedFile]
    reserved_only: dict[str, list[PackagerProvidedFile]]


def _find_package_name_prefix(
    binary_packages: Mapping[str, BinaryPackage],
    main_binary_package: str,
    max_periods_in_package_name: int,
    path: VirtualPath,
    *,
    allow_fuzzy_matches: bool = False,
) -> Iterable[tuple[str, str, bool, bool]]:
    if max_periods_in_package_name < 1:
        prefix, remaining = path.name.split(".", 1)
        package_name = prefix
        bug_950723 = False
        if allow_fuzzy_matches and package_name.endswith("@"):
            package_name = package_name[:-1]
            bug_950723 = True
        if package_name in binary_packages:
            yield package_name, remaining, True, bug_950723
        else:
            yield main_binary_package, path.name, False, False
        return

    parts = path.name.split(".", max_periods_in_package_name + 1)
    for p in range(len(parts) - 1, 0, -1):
        name = ".".join(parts[0:p])
        bug_950723 = False
        if allow_fuzzy_matches and name.endswith("@"):
            name = name[:-1]
            bug_950723 = True

        if name in binary_packages:
            remaining = ".".join(parts[p:])
            yield name, remaining, True, bug_950723
    # main package case
    yield main_binary_package, path.name, False, False


def _iterate_stem_splits(basename: str) -> tuple[str, str, int]:
    stem = basename
    period_count = stem.count(".")
    yield stem, None, period_count
    install_as_name = ""
    while period_count > 0:
        period_count -= 1
        install_as_name_part, stem = stem.split(".", 1)
        install_as_name = (
            install_as_name + "." + install_as_name_part
            if install_as_name != ""
            else install_as_name_part
        )
        yield stem, install_as_name, period_count


def _find_definition(
    packager_provided_files: Mapping[str, PackagerProvidedFileClassSpec],
    basename: str,
    *,
    period2stems: Mapping[int, Sequence[str]] | None = None,
    had_arch: bool = False,
) -> tuple[str | None, PackagerProvidedFileClassSpec | None, str | None]:
    for stem, install_as_name, period_count in _iterate_stem_splits(basename):
        definition = packager_provided_files.get(stem)
        if definition is not None:
            return install_as_name, definition, None
        if not period2stems:
            continue
        stems = period2stems.get(period_count)

        if not stems:
            continue
        # If the stem is also the extension and a known one at that, then
        # we do not consider it a typo match (to avoid false positives).
        #
        # We also ignore "foo.1" since manpages are kind of common.
        if not had_arch and (stem in _KNOWN_NON_TYPO_EXTENSIONS or stem.isdigit()):
            continue
        max_edit_distance = 2 if len(stem) > 3 else 1
        matches = detect_possible_typo(stem, stems, max_edit_distance=max_edit_distance)
        if matches is not None and len(matches) == 1:
            definition = packager_provided_files[matches[0]]
            return install_as_name, definition, stem
    return None, None, None


def _check_mismatches(
    path: VirtualPath,
    definition: PackagerProvidedFileClassSpec,
    owning_package: BinaryPackage,
    install_as_name: str | None,
    had_arch: bool,
) -> None:
    if install_as_name is not None and not definition.allow_name_segment:
        _error(
            f'The file "{path.fs_path}" looks like a packager provided file for'
            f' {owning_package.name} of type {definition.stem} with the custom name "{install_as_name}".'
            " However, this file type does not allow custom naming. The file type was registered"
            f" by {definition.debputy_plugin_metadata.plugin_name} in case you disagree and want"
            " to file a bug/feature request."
        )
    if had_arch:
        if owning_package.is_arch_all:
            _error(
                f'The file "{path.fs_path}" looks like an architecture specific packager provided file for'
                f" {owning_package.name} of type {definition.stem}."
                " However, the package in question is arch:all. The use of architecture specific files"
                " for arch:all packages does not make sense."
            )
        if not definition.allow_architecture_segment:
            _error(
                f'The file "{path.fs_path}" looks like an architecture specific packager provided file for'
                f" {owning_package.name} of type {definition.stem}."
                " However, this file type does not allow architecture specific variants. The file type was registered"
                f" by {definition.debputy_plugin_metadata.plugin_name} in case you disagree and want"
                " to file a bug/feature request."
            )


def _split_basename(
    basename: str,
    owning_package: BinaryPackage,
    *,
    has_explicit_package: bool = False,
    allow_fuzzy_matches: bool = False,
) -> tuple[str, int, str | None, bool]:
    match_priority = 1 if has_explicit_package else 0
    fuzzy_match = False
    arch_restriction: str | None = None
    if allow_fuzzy_matches and basename.endswith(".in") and len(basename) > 3:
        basename = basename[:-3]
        fuzzy_match = True

    if "." in basename:
        remaining, last_word = basename.rsplit(".", 1)
        # We cannot use "resolved_architecture" as it would return "all".
        if last_word == owning_package.package_deb_architecture_variable("ARCH"):
            match_priority = 3
            basename = remaining
            arch_restriction = last_word
        elif last_word == owning_package.package_deb_architecture_variable("ARCH_OS"):
            match_priority = 2
            basename = remaining
            arch_restriction = last_word
        elif last_word == "all" and owning_package.is_arch_all:
            # This case does not make sense, but we detect it, so we can report an error
            # via _check_mismatches.
            match_priority = -1
            basename = remaining
            arch_restriction = last_word

    return basename, match_priority, arch_restriction, fuzzy_match


def _split_path(
    packager_provided_files: Mapping[str, PackagerProvidedFileClassSpec],
    binary_packages: Mapping[str, BinaryPackage],
    main_binary_package: str,
    max_periods_in_package_name: int,
    path: VirtualPath,
    *,
    allow_fuzzy_matches: bool = False,
    period2stems: Mapping[int, Sequence[str]] | None = None,
    known_static_non_ppf_names=frozenset(),
) -> Iterable[PackagerProvidedFile]:
    owning_package_name = main_binary_package
    basename = path.name
    match_priority = 0
    had_arch = False
    if "." not in basename:
        definition = packager_provided_files.get(basename)
        if definition is None:
            return
        if definition.packageless_is_fallback_for_all_packages:
            yield from (
                PackagerProvidedFile(
                    path=path,
                    package_name=n,
                    installed_as_basename=n,
                    provided_key=".UNNAMED.",
                    definition=definition,
                    match_priority=match_priority,
                    fuzzy_match=False,
                    uses_explicit_package_name=False,
                    name_segment=None,
                    architecture_restriction=None,
                )
                for n in binary_packages
            )
        else:
            yield PackagerProvidedFile(
                path=path,
                package_name=owning_package_name,
                installed_as_basename=owning_package_name,
                provided_key=".UNNAMED.",
                definition=definition,
                match_priority=match_priority,
                fuzzy_match=False,
                uses_explicit_package_name=False,
                name_segment=None,
                architecture_restriction=None,
            )
        return
    if f"debian/{path.name}" in known_static_non_ppf_names:
        return

    for (
        owning_package_name,
        basename,
        explicit_package,
        bug_950723,
    ) in _find_package_name_prefix(
        binary_packages,
        main_binary_package,
        max_periods_in_package_name,
        path,
        allow_fuzzy_matches=allow_fuzzy_matches,
    ):
        owning_package = binary_packages[owning_package_name]

        basename, match_priority, arch_restriction, fuzzy_match = _split_basename(
            basename,
            owning_package,
            has_explicit_package=explicit_package,
            allow_fuzzy_matches=allow_fuzzy_matches,
        )

        install_as_name, definition, typoed_stem = _find_definition(
            packager_provided_files,
            basename,
            period2stems=period2stems,
            had_arch=bool(arch_restriction),
        )
        if definition is None:
            continue

        # Note: bug_950723 implies allow_fuzzy_matches
        if bug_950723 and not definition.bug_950723:
            continue

        if not allow_fuzzy_matches:
            # LSP/Lint checks here but should not use `_check_mismatches` as
            # the hard error disrupts them.
            _check_mismatches(
                path,
                definition,
                owning_package,
                install_as_name,
                arch_restriction is not None,
            )

        expected_path: str | None = None
        if (
            definition.packageless_is_fallback_for_all_packages
            and install_as_name is None
            and not had_arch
            and not explicit_package
            and arch_restriction is None
        ):
            if typoed_stem is not None:
                parent_path = (
                    path.parent_dir.path + "/" if path.parent_dir is not None else ""
                )
                expected_path = f"{parent_path}{definition.stem}"
                if fuzzy_match and path.name.endswith(".in"):
                    expected_path += ".in"
            yield from (
                PackagerProvidedFile(
                    path=path,
                    package_name=n,
                    installed_as_basename=f"{n}@" if bug_950723 else n,
                    provided_key=".UNNAMED." if bug_950723 else ".UNNAMED@.",
                    definition=definition,
                    match_priority=match_priority,
                    fuzzy_match=fuzzy_match,
                    uses_explicit_package_name=False,
                    name_segment=None,
                    architecture_restriction=None,
                    expected_path=expected_path,
                )
                for n in binary_packages
            )
        else:
            provided_key = (
                install_as_name if install_as_name is not None else ".UNNAMED."
            )
            basename = (
                install_as_name if install_as_name is not None else owning_package_name
            )
            if bug_950723:
                provided_key = f"{provided_key}@"
                basename = f"{basename}@"
                package_prefix = f"{owning_package_name}@"
            else:
                package_prefix = owning_package_name
            if typoed_stem:
                parent_path = (
                    path.parent_dir.path + "/" if path.parent_dir is not None else ""
                )
                basename = definition.stem
                if install_as_name is not None:
                    basename = f"{install_as_name}.{basename}"
                if explicit_package:
                    basename = f"{package_prefix}.{basename}"
                if arch_restriction is not None and arch_restriction != "all":
                    basename = f"{basename}.{arch_restriction}"
                expected_path = f"{parent_path}{basename}"
                if fuzzy_match and path.name.endswith(".in"):
                    expected_path += ".in"
            yield PackagerProvidedFile(
                path=path,
                package_name=owning_package_name,
                installed_as_basename=basename,
                provided_key=provided_key,
                definition=definition,
                match_priority=match_priority,
                fuzzy_match=fuzzy_match,
                uses_explicit_package_name=bool(explicit_package),
                name_segment=install_as_name,
                architecture_restriction=arch_restriction,
                expected_path=expected_path,
            )
        return


def _period_stem(stems: Iterable[str]) -> Mapping[int, Sequence[str]]:
    result: dict[int, list[str]] = {}
    for stem in stems:
        period_count = stem.count(".")
        matched_stems = result.get(period_count)
        if not matched_stems:
            matched_stems = [stem]
            result[period_count] = matched_stems
        else:
            matched_stems.append(stem)
    return result


def _find_main_package_name(
    binary_packages: Mapping[str, BinaryPackage],
    *,
    allow_fuzzy_matches: bool = False,
) -> str | None:
    main_packages = [p.name for p in binary_packages.values() if p.is_main_package]
    if not main_packages:
        assert allow_fuzzy_matches
        return next(
            iter(p.name for p in binary_packages.values() if "Package" in p.fields),
            None,
        )
    return main_packages[0]


@dataclasses.dataclass(slots=True, frozen=True)
class PackagingFileClassification:
    path: VirtualPath
    packager_provided_files_per_package: None | (
        Mapping[str, Sequence[PackagerProvidedFile]]
    )


def classify_debian_packaging_files(
    plugin_feature_set: "PluginProvidedFeatureSet",
    debian_dir: VirtualPath,
    binary_packages: Mapping[str, BinaryPackage],
    *,
    allow_fuzzy_matches: bool = False,
    detect_typos: bool = False,
    ignore_paths: Container[str] = frozenset(),
) -> Iterable[PackagingFileClassification]:
    packager_provided_files = plugin_feature_set.packager_provided_files
    known_static_non_ppf_names: frozenset[str] = frozenset(
        {
            p.detection_value
            for p in plugin_feature_set.known_packaging_files.values()
            if p.detection_method == "path"
        }
    )
    main_binary_package = _find_main_package_name(
        binary_packages,
        allow_fuzzy_matches=allow_fuzzy_matches,
    )
    if main_binary_package is None:
        return {}
    provided_files_by_key: dict[tuple[str, str, str], PackagerProvidedFile] = {}
    max_periods_in_package_name = max(name.count(".") for name in binary_packages)
    if detect_typos and CAN_DETECT_TYPOS:
        period2stems = _period_stem(packager_provided_files.keys())
    else:
        period2stems = {}

    paths = []

    for entry in debian_dir.iterdir:
        if entry.is_dir or entry.name.startswith("."):
            continue
        if entry.path in ignore_paths:
            continue
        paths.append(entry)
        matching_ppfs = _split_path(
            packager_provided_files,
            binary_packages,
            main_binary_package,
            max_periods_in_package_name,
            entry,
            allow_fuzzy_matches=allow_fuzzy_matches,
            period2stems=period2stems,
            known_static_non_ppf_names=known_static_non_ppf_names,
        )
        for packager_provided_file in matching_ppfs:
            match_key = (
                packager_provided_file.package_name,
                packager_provided_file.definition.stem,
                packager_provided_file.provided_key,
            )
            existing = provided_files_by_key.get(match_key)
            if (
                existing is not None
                and existing.match_priority > packager_provided_file.match_priority
            ):
                continue
            provided_files_by_key[match_key] = packager_provided_file

    paths2ppfs_per_package = {}
    for packager_provided_file in provided_files_by_key.values():
        package_name = packager_provided_file.package_name
        path_name = packager_provided_file.path.path
        ppfs_per_package = paths2ppfs_per_package.get(path_name)
        if ppfs_per_package is None:
            ppfs_per_package = collections.defaultdict(list)
            paths2ppfs_per_package[path_name] = ppfs_per_package
        ppfs_per_package[package_name].append(packager_provided_file)

    for entry in paths:
        yield PackagingFileClassification(
            entry,
            paths2ppfs_per_package.get(entry.path),
        )


def detect_all_packager_provided_files(
    plugin_feature_set: "PluginProvidedFeatureSet",
    debian_dir: VirtualPath,
    binary_packages: Mapping[str, BinaryPackage],
    *,
    allow_fuzzy_matches: bool = False,
    detect_typos: bool = False,
    ignore_paths: Container[str] = frozenset(),
) -> dict[str, PerPackagePackagerProvidedResult]:
    result = {
        n: PerPackagePackagerProvidedResult([], collections.defaultdict(list))
        for n in binary_packages
    }
    for classified_path in classify_debian_packaging_files(
        plugin_feature_set,
        debian_dir,
        binary_packages,
        allow_fuzzy_matches=allow_fuzzy_matches,
        detect_typos=detect_typos,
        ignore_paths=ignore_paths,
    ):
        provided_files = classified_path.packager_provided_files_per_package
        if not provided_files:
            continue
        for package_name, provided_file_data in provided_files.items():
            per_package_result = result[package_name]
            per_package_result.auto_installable.extend(
                x for x in provided_file_data if not x.definition.reservation_only
            )
            reservation_only = per_package_result.reserved_only
            for packager_provided_file in provided_file_data:
                if not packager_provided_file.definition.reservation_only:
                    continue
                reservation_only[packager_provided_file.definition.stem].append(
                    packager_provided_file
                )

    return result