debputy.lsp.languages.lsp_debian_control

src/debputy/lsp/languages/lsp_debian_control.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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
import dataclasses
import importlib.resources
import os.path
import textwrap
from functools import lru_cache
from itertools import chain
from typing import (
    Union,
    Tuple,
    Optional,
    List,
    Self,
    TYPE_CHECKING,
)
from collections.abc import Sequence, Mapping, Iterable

import debputy.lsp.data.deb822_data as deb822_ref_data_dir
from debputy.analysis.analysis_util import flatten_ppfs
from debputy.analysis.debian_dir import resolve_debhelper_config_files
from debputy.dh.dh_assistant import extract_dh_compat_level
from debputy.linting.lint_util import (
    LintState,
    te_range_to_lsp,
    te_position_to_lsp,
    with_range_in_continuous_parts,
)
from debputy.lsp.apt_cache import PackageLookup
from debputy.lsp.debputy_ls import DebputyLanguageServer
from debputy.lsp.lsp_debian_control_reference_data import (
    DctrlKnownField,
    DctrlFileMetadata,
    package_name_to_section,
    all_package_relationship_fields,
    extract_first_value_and_position,
    all_source_relationship_fields,
    StanzaMetadata,
    SUBSTVAR_RE,
)
from debputy.lsp.lsp_features import (
    lint_diagnostics,
    lsp_completer,
    lsp_hover,
    lsp_standard_handler,
    lsp_folding_ranges,
    lsp_semantic_tokens_full,
    lsp_will_save_wait_until,
    lsp_format_document,
    lsp_text_doc_inlay_hints,
    LanguageDispatchRule,
    SecondaryLanguage,
    lsp_cli_reformat_document,
)
from debputy.lsp.lsp_generic_deb822 import (
    deb822_completer,
    deb822_hover,
    deb822_folding_ranges,
    deb822_semantic_tokens_full,
    deb822_format_file,
    scan_for_syntax_errors_and_token_level_diagnostics,
)
from debputy.lsp.lsp_reference_keyword import LSP_DATA_DOMAIN
from debputy.lsp.quickfixes import (
    propose_correct_text_quick_fix,
    propose_insert_text_on_line_after_diagnostic_quick_fix,
    propose_remove_range_quick_fix,
)
from debputy.lsp.ref_models.deb822_reference_parse_models import (
    DCTRL_SUBSTVARS_REFERENCE_DATA_PARSER,
    DCtrlSubstvar,
)
from debputy.lsp.text_util import markdown_urlify
from debputy.lsp.vendoring._deb822_repro import (
    Deb822ParagraphElement,
)
from debputy.lsp.vendoring._deb822_repro.parsing import (
    Deb822KeyValuePairElement,
)
from debputy.lsprotocol.types import (
    Position,
    FoldingRange,
    FoldingRangeParams,
    CompletionItem,
    CompletionList,
    CompletionParams,
    HoverParams,
    Hover,
    TEXT_DOCUMENT_CODE_ACTION,
    SemanticTokens,
    SemanticTokensParams,
    WillSaveTextDocumentParams,
    TextEdit,
    DocumentFormattingParams,
    InlayHint,
)
from debputy.manifest_parser.util import AttributePath
from debputy.packager_provided_files import (
    PackagerProvidedFile,
    detect_all_packager_provided_files,
)
from debputy.plugin.api.impl import plugin_metadata_for_debputys_own_plugin
from debputy.util import PKGNAME_REGEX, _info, _trace_log, _is_trace_log_enabled
from debputy.yaml import MANIFEST_YAML

if TYPE_CHECKING:
    import lsprotocol.types as types
else:
    import debputy.lsprotocol.types as types

try:
    from debputy.lsp.vendoring._deb822_repro.locatable import (
        Position as TEPosition,
        Range as TERange,
        START_POSITION,
    )

    from pygls.workspace import TextDocument
except ImportError:
    pass


_DISPATCH_RULE = LanguageDispatchRule.new_rule(
    "debian/control",
    None,
    "debian/control",
    [
        # emacs's name
        SecondaryLanguage("debian-control"),
        # vim's name
        SecondaryLanguage("debcontrol"),
    ],
)


@dataclasses.dataclass(slots=True, frozen=True)
class SubstvarMetadata:
    name: str
    defined_by: str
    dh_sequence: str | None
    doc_uris: Sequence[str]
    synopsis: str
    description: str

    def render_metadata_fields(self) -> str:
        def_by = f"Defined by: {self.defined_by}"
        dh_seq = (
            f"DH Sequence: {self.dh_sequence}" if self.dh_sequence is not None else None
        )
        doc_uris = self.doc_uris
        parts = [def_by, dh_seq]
        if doc_uris:
            if len(doc_uris) == 1:
                parts.append(f"Documentation: {markdown_urlify(doc_uris[0])}")
            else:
                parts.append("Documentation:")
                parts.extend(f" - {markdown_urlify(uri)}" for uri in doc_uris)
        return "\n".join(parts)

    @classmethod
    def from_ref_data(cls, x: DCtrlSubstvar) -> "Self":
        doc = x.get("documentation", {})
        return cls(
            x["name"],
            x["defined_by"],
            x.get("dh_sequence"),
            doc.get("uris", []),
            doc.get("synopsis", ""),
            doc.get("long_description", ""),
        )


def relationship_substvar_for_field(substvar: str) -> str | None:
    relationship_fields = all_package_relationship_fields()
    try:
        col_idx = substvar.rindex(":")
    except ValueError:
        return None
    return relationship_fields.get(substvar[col_idx + 1 : -1].lower())


def _as_substvars_metadata(
    args: list[SubstvarMetadata],
) -> Mapping[str, SubstvarMetadata]:
    r = {s.name: s for s in args}
    assert len(r) == len(args)
    return r


def dctrl_variables_metadata_basename() -> str:
    return "debian_control_variables_data.yaml"


@lru_cache
def dctrl_substvars_metadata() -> Mapping[str, SubstvarMetadata]:
    p = importlib.resources.files(deb822_ref_data_dir.__name__).joinpath(
        dctrl_variables_metadata_basename()
    )

    with p.open("r", encoding="utf-8") as fd:
        raw = MANIFEST_YAML.load(fd)

    attr_path = AttributePath.root_path(p)
    ref = DCTRL_SUBSTVARS_REFERENCE_DATA_PARSER.parse_input(raw, attr_path)
    return _as_substvars_metadata(
        [SubstvarMetadata.from_ref_data(x) for x in ref["variables"]]
    )


_DCTRL_FILE_METADATA = DctrlFileMetadata()


lsp_standard_handler(_DISPATCH_RULE, TEXT_DOCUMENT_CODE_ACTION)


@lsp_hover(_DISPATCH_RULE)
def _debian_control_hover(
    ls: "DebputyLanguageServer",
    params: HoverParams,
) -> Hover | None:
    return deb822_hover(ls, params, _DCTRL_FILE_METADATA, custom_handler=_custom_hover)


def _custom_hover_description(
    _ls: "DebputyLanguageServer",
    _known_field: DctrlKnownField,
    line: str,
    _word_at_position: str,
) -> Hover | str | None:
    if line[0].isspace():
        return None
    try:
        col_idx = line.index(":")
    except ValueError:
        return None

    content = line[col_idx + 1 :].strip()

    # Synopsis
    return textwrap.dedent(
        f"""\
        # Package synopsis

        The synopsis functions as a phrase describing the package, not a
        complete sentence, so sentential punctuation is inappropriate: it
        does not need extra capital letters or a final period (full stop).
        It should also omit any initial indefinite or definite article
        - "a", "an", or "the". Thus for instance:

        ```
        Package: libeg0
        Description: exemplification support library
        ```

        Technically this is a noun phrase minus articles, as opposed to a
        verb phrase. A good heuristic is that it should be possible to
        substitute the package name and synopsis into this formula:

        ```
        # Generic
        The package provides {{a,an,the,some}} synopsis.

        # The current package for comparison
        The package provides {{a,an,the,some}} {content}.
        ```

        Other advice for writing synopsis:
         * Avoid using the package name. Any software would display the
           package name already and it generally does not help the user
           understand what they are looking at.
         * In many situations, the user will only see the package name
           and its synopsis. The synopsis must be able to stand alone.

        **Example renderings in various terminal UIs**:
        ```
        # apt search TERM
        package/stable,now 1.0-1 all:
           {content}

        # apt-get search TERM
        package - {content}
        ```

        ## Reference example

        An reference example for comparison: The Sphinx package
        (python3-sphinx/7.2.6-6) had the following synopsis:

        ```
        Description: documentation generator for Python projects
        ```

        In the test sentence, it would read as:

        ```
        The python3-sphinx package provides a documentation generator for Python projects.
        ```

        **Side-by-side comparison in the terminal UIs**:
        ```
        # apt search TERM
        python3-sphinx/stable,now 7.2.6-6 all:
           documentation generator for Python projects

        package/stable,now 1.0-1 all:
           {content}


        # apt-get search TERM
        package - {content}
        python3-sphinx - documentation generator for Python projects
        ```
    """
    )


def _render_package_lookup(
    package_lookup: PackageLookup,
    known_field: DctrlKnownField,
) -> str:
    name = package_lookup.name
    provider = package_lookup.package
    if package_lookup.package is None and len(package_lookup.provided_by) == 1:
        provider = package_lookup.provided_by[0]

    if provider:
        segments = [
            f"# {name} ({provider.version}, {provider.architecture}) ",
            "",
        ]

        if (
            _is_bd_field(known_field)
            and name.startswith("dh-sequence-")
            and len(name) > 12
        ):
            sequence = name[12:]
            segments.append(
                f"This build-dependency will activate the `dh` sequence called `{sequence}`."
            )
            segments.append("")

        elif (
            known_field.name == "Build-Depends"
            and name.startswith("debputy-plugin-")
            and len(name) > 15
        ):
            plugin_name = name[15:]
            segments.append(
                f"This build-dependency will activate the `debputy` plugin called `{plugin_name}`."
            )
            segments.append("")

        segments.extend(
            [
                f"Synopsis: {provider.synopsis}",
                "",
                f"Multi-Arch: {provider.multi_arch}",
                "",
                f"Section: {provider.section}",
            ]
        )
        if provider.upstream_homepage is not None:
            segments.append("")
            segments.append(f"Upstream homepage: {provider.upstream_homepage}")
        segments.append("")
        segments.append(
            "Data is from the system's APT cache, which may not match the target distribution."
        )
        return "\n".join(segments)

    segments = [
        f"# {name} [virtual]",
        "",
        "The package {name} is a virtual package provided by one of:",
    ]
    segments.extend(f" * {p.name}" for p in package_lookup.provided_by)
    segments.append("")
    segments.append(
        "Data is from the system's APT cache, which may not match the target distribution."
    )
    return "\n".join(segments)


def _disclaimer(is_empty: bool) -> str:
    if is_empty:
        return textwrap.dedent(
            """\
        The system's APT cache is empty, so it was not possible to verify that the
        package exist.
"""
        )
    return textwrap.dedent(
        """\
        The package is not known by the APT cache on this system, so there may be typo
        or the package may not be available in the version of your distribution.
"""
    )


def _render_package_by_name(
    name: str, known_field: DctrlKnownField, is_empty: bool
) -> str | None:
    if _is_bd_field(known_field) and name.startswith("dh-sequence-") and len(name) > 12:
        sequence = name[12:]
        return (
            textwrap.dedent(
                f"""\
        # {name}

        This build-dependency will activate the `dh` sequence called `{sequence}`.

        """
            )
            + _disclaimer(is_empty)
        )
    if (
        known_field.name == "Build-Depends"
        and name.startswith("debputy-plugin-")
        and len(name) > 15
    ):
        plugin_name = name[15:]
        return (
            textwrap.dedent(
                f"""\
        # {name}

        This build-dependency will activate the `debputy` plugin called `{plugin_name}`.

        """
            )
            + _disclaimer(is_empty)
        )
    return (
        textwrap.dedent(
            f"""\
        # {name}

    """
        )
        + _disclaimer(is_empty)
    )


def _is_bd_field(known_field: DctrlKnownField) -> bool:
    return known_field.name in (
        "Build-Depends",
        "Build-Depends-Arch",
        "Build-Depends-Indep",
    )


def _custom_hover_relationship_field(
    ls: "DebputyLanguageServer",
    known_field: DctrlKnownField,
    _line: str,
    word_at_position: str,
) -> Hover | str | None:
    apt_cache = ls.apt_cache
    state = apt_cache.state
    is_empty = False
    _info(f"Rel field: {known_field.name} - {word_at_position} - {state}")
    if "|" in word_at_position:
        return textwrap.dedent(
            f"""\
            Sorry, no hover docs for OR relations at the moment.

            The relation being matched: `{word_at_position}`

            The code is missing logic to determine which side of the OR the lookup is happening.
        """
        )
    match = next(iter(PKGNAME_REGEX.finditer(word_at_position)), None)
    if match is None:
        return
    package = match.group()
    if state == "empty-cache":
        state = "loaded"
        is_empty = True
    if state == "loaded":
        result = apt_cache.lookup(package)
        if result is None:
            return _render_package_by_name(
                package,
                known_field,
                is_empty=is_empty,
            )
        return _render_package_lookup(result, known_field)

    if state in (
        "not-loaded",
        "failed",
        "tooling-not-available",
    ):
        details = apt_cache.load_error if apt_cache.load_error else "N/A"
        return textwrap.dedent(
            f"""\
        Sorry, the APT cache data is not available due to an error or missing tool.

        Details: {details}
        """
        )

    if state == "empty-cache":
        return f"Cannot lookup {package}: APT cache data was empty"

    if state == "loading":
        return f"Cannot lookup {package}: APT cache data is still being indexed. Please try again in a moment."
    return None


_CUSTOM_FIELD_HOVER = {
    field: _custom_hover_relationship_field
    for field in chain(
        all_package_relationship_fields().values(),
        all_source_relationship_fields().values(),
    )
    if field != "Provides"
}

_CUSTOM_FIELD_HOVER["Description"] = _custom_hover_description


def _custom_hover(
    ls: "DebputyLanguageServer",
    server_position: Position,
    _current_field: str | None,
    word_at_position: str,
    known_field: DctrlKnownField | None,
    in_value: bool,
    _doc: "TextDocument",
    lines: list[str],
) -> Hover | str | None:
    if not in_value:
        return None

    line_no = server_position.line
    line = lines[line_no]
    substvar_search_ref = server_position.character
    substvar = ""
    try:
        if line and line[substvar_search_ref] in ("$", "{"):
            substvar_search_ref += 2
        substvar_start = line.rindex("${", 0, substvar_search_ref)
        substvar_end = line.index("}", substvar_start)
        if server_position.character <= substvar_end:
            substvar = line[substvar_start : substvar_end + 1]
    except (ValueError, IndexError):
        pass

    if substvar == "${}" or SUBSTVAR_RE.fullmatch(substvar):
        substvar_md = dctrl_substvars_metadata().get(substvar)

        computed_doc = ""
        for_field = relationship_substvar_for_field(substvar)
        if for_field:
            # Leading empty line is intentional!
            computed_doc = textwrap.dedent(
                f"""
                This substvar is a relationship substvar for the field {for_field}.
                Relationship substvars are automatically added in the field they
                are named after in `debhelper-compat (= 14)` or later, or with
                `debputy` (any integration mode after 0.1.21).
            """
            )

        if substvar_md is None:
            doc = f"No documentation for {substvar}.\n"
            md_fields = ""
        else:
            doc = ls.translation(LSP_DATA_DOMAIN).pgettext(
                f"Variable:{substvar_md.name}",
                substvar_md.description,
            )
            md_fields = "\n" + substvar_md.render_metadata_fields()
        return f"# Substvar `{substvar}`\n\n{doc}{computed_doc}{md_fields}"

    if known_field is None:
        return None
    dispatch = _CUSTOM_FIELD_HOVER.get(known_field.name)
    if dispatch is None:
        return None
    return dispatch(ls, known_field, line, word_at_position)


@lsp_completer(_DISPATCH_RULE)
def _debian_control_completions(
    ls: "DebputyLanguageServer",
    params: CompletionParams,
) -> CompletionList | Sequence[CompletionItem] | None:
    return deb822_completer(ls, params, _DCTRL_FILE_METADATA)


@lsp_folding_ranges(_DISPATCH_RULE)
def _debian_control_folding_ranges(
    ls: "DebputyLanguageServer",
    params: FoldingRangeParams,
) -> Sequence[FoldingRange] | None:
    return deb822_folding_ranges(ls, params, _DCTRL_FILE_METADATA)


@lsp_text_doc_inlay_hints(_DISPATCH_RULE)
async def _doc_inlay_hint(
    ls: "DebputyLanguageServer",
    params: types.InlayHintParams,
) -> list[InlayHint] | None:
    doc = ls.workspace.get_text_document(params.text_document.uri)
    lint_state = ls.lint_state(doc)
    deb822_file = lint_state.parsed_deb822_file_content
    if not deb822_file:
        return None
    inlay_hints = []
    stanzas = list(deb822_file)
    if len(stanzas) < 2:
        return None
    source_stanza = stanzas[0]
    source_stanza_pos = source_stanza.position_in_file()
    inherited_inlay_label_part = {}
    stanza_no = 0

    async for stanza_range, stanza in lint_state.slow_iter(
        with_range_in_continuous_parts(deb822_file.iter_parts())
    ):
        if not isinstance(stanza, Deb822ParagraphElement):
            continue
        stanza_def = _DCTRL_FILE_METADATA.classify_stanza(stanza, stanza_no)
        stanza_no += 1
        pkg_kvpair = stanza.get_kvpair_element(("Package", 0), use_get=True)
        if pkg_kvpair is None:
            continue

        parts = []
        async for known_field in ls.slow_iter(
            stanza_def.stanza_fields.values(), yield_every=25
        ):
            if (
                not known_field.inheritable_from_other_stanza
                or not known_field.show_as_inherited
                or known_field.name in stanza
            ):
                continue

            inherited_value = source_stanza.get(known_field.name)
            if inherited_value is not None:
                inlay_hint_label_part = inherited_inlay_label_part.get(known_field.name)
                if inlay_hint_label_part is None:
                    kvpair = source_stanza.get_kvpair_element(known_field.name)
                    value_range_te = kvpair.range_in_parent().relative_to(
                        source_stanza_pos
                    )
                    value_range = doc.position_codec.range_to_client_units(
                        lint_state.lines,
                        te_range_to_lsp(value_range_te),
                    )
                    inlay_hint_label_part = types.InlayHintLabelPart(
                        f"  ({known_field.name}: {inherited_value})",
                        tooltip="Inherited from Source stanza",
                        location=types.Location(
                            params.text_document.uri,
                            value_range,
                        ),
                    )
                    inherited_inlay_label_part[known_field.name] = inlay_hint_label_part
                parts.append(inlay_hint_label_part)

        if parts:
            known_field = stanza_def["Package"]
            values = known_field.field_value_class.interpreter().interpret(pkg_kvpair)
            assert values is not None
            anchor_value = list(values.iter_value_references())[-1]
            anchor_position = (
                anchor_value.locatable.range_in_parent().end_pos.relative_to(
                    pkg_kvpair.value_element.position_in_parent().relative_to(
                        stanza_range.start_pos
                    )
                )
            )
            anchor_position_client_units = doc.position_codec.position_to_client_units(
                lint_state.lines,
                te_position_to_lsp(anchor_position),
            )
            inlay_hints.append(
                types.InlayHint(
                    anchor_position_client_units,
                    parts,
                    padding_left=True,
                    padding_right=False,
                )
            )
    return inlay_hints


def _source_package_checks(
    stanza: Deb822ParagraphElement,
    stanza_position: "TEPosition",
    stanza_metadata: StanzaMetadata[DctrlKnownField],
    lint_state: LintState,
) -> None:
    vcs_fields = {}
    source_fields = _DCTRL_FILE_METADATA["Source"].stanza_fields
    for kvpair in stanza.iter_parts_of_type(Deb822KeyValuePairElement):
        name = stanza_metadata.normalize_field_name(kvpair.field_name.lower())
        if (
            not name.startswith("vcs-")
            or name == "vcs-browser"
            or name not in source_fields
        ):
            continue
        vcs_fields[name] = kvpair

    if len(vcs_fields) < 2:
        return
    for kvpair in vcs_fields.values():
        lint_state.emit_diagnostic(
            kvpair.range_in_parent().relative_to(stanza_position),
            f'Multiple Version Control fields defined ("{kvpair.field_name}")',
            "warning",
            "Policy 5.6.26",
            quickfixes=[
                propose_remove_range_quick_fix(
                    proposed_title=f'Remove "{kvpair.field_name}"'
                )
            ],
        )


def _binary_package_checks(
    stanza: Deb822ParagraphElement,
    stanza_position: "TEPosition",
    source_stanza: Deb822ParagraphElement,
    representation_field_range: "TERange",
    lint_state: LintState,
) -> None:
    package_name = stanza.get("Package", "")
    source_section = source_stanza.get("Section")
    section_kvpair = stanza.get_kvpair_element(("Section", 0), use_get=True)
    section: str | None = None
    section_range: Optional["TERange"] = None
    if section_kvpair is not None:
        section, section_range = extract_first_value_and_position(
            section_kvpair,
            stanza_position,
        )

    if section_range is None:
        section_range = representation_field_range
    effective_section = section or source_section or "unknown"
    package_type = stanza.get("Package-Type", "")
    component_prefix = ""
    if "/" in effective_section:
        component_prefix, effective_section = effective_section.split("/", maxsplit=1)
        component_prefix += "/"

    if package_name.endswith("-udeb") or package_type == "udeb":
        if package_type != "udeb":
            package_type_kvpair = stanza.get_kvpair_element(
                "Package-Type", use_get=True
            )
            package_type_range: Optional["TERange"] = None
            if package_type_kvpair is not None:
                _, package_type_range = extract_first_value_and_position(
                    package_type_kvpair,
                    stanza_position,
                )
            if package_type_range is None:
                package_type_range = representation_field_range
            lint_state.emit_diagnostic(
                package_type_range,
                'The Package-Type should be "udeb" given the package name',
                "warning",
                "debputy",
            )
        guessed_section = "debian-installer"
        section_diagnostic_rationale = " since it is an udeb"
    else:
        guessed_section = package_name_to_section(package_name)
        section_diagnostic_rationale = " based on the package name"
    if guessed_section is not None and guessed_section != effective_section:
        if section is not None:
            quickfix_data = [
                propose_correct_text_quick_fix(f"{component_prefix}{guessed_section}")
            ]
        else:
            quickfix_data = [
                propose_insert_text_on_line_after_diagnostic_quick_fix(
                    f"Section: {component_prefix}{guessed_section}\n"
                )
            ]
        assert section_range is not None  # mypy hint
        lint_state.emit_diagnostic(
            section_range,
            f'The Section should be "{component_prefix}{guessed_section}"{section_diagnostic_rationale}',
            "warning",
            "debputy",
            quickfixes=quickfix_data,
        )


@lint_diagnostics(_DISPATCH_RULE)
async def _lint_debian_control(lint_state: LintState) -> None:
    deb822_file = lint_state.parsed_deb822_file_content

    if not _DCTRL_FILE_METADATA.file_metadata_applies_to_file(deb822_file):
        return

    first_error = await scan_for_syntax_errors_and_token_level_diagnostics(
        deb822_file,
        lint_state,
    )

    stanzas = list(deb822_file)
    source_stanza = stanzas[0] if stanzas else None
    binary_stanzas_w_pos = []

    source_stanza_metadata, binary_stanza_metadata = _DCTRL_FILE_METADATA.stanza_types()
    stanza_no = 0

    async for stanza_range, stanza in lint_state.slow_iter(
        with_range_in_continuous_parts(deb822_file.iter_parts())
    ):
        if not isinstance(stanza, Deb822ParagraphElement):
            continue
        stanza_position = stanza_range.start_pos
        if stanza_position.line_position >= first_error:
            break
        stanza_no += 1
        is_binary_stanza = stanza_no != 1
        if is_binary_stanza:
            stanza_metadata = binary_stanza_metadata
            other_stanza_metadata = source_stanza_metadata
            other_stanza_name = "Source"
            binary_stanzas_w_pos.append((stanza, stanza_position))
            _, representation_field_range = stanza_metadata.stanza_representation(
                stanza, stanza_position
            )
            _binary_package_checks(
                stanza,
                stanza_position,
                source_stanza,
                representation_field_range,
                lint_state,
            )
        else:
            stanza_metadata = source_stanza_metadata
            other_stanza_metadata = binary_stanza_metadata
            other_stanza_name = "Binary"
            _source_package_checks(
                stanza,
                stanza_position,
                stanza_metadata,
                lint_state,
            )

        await stanza_metadata.stanza_diagnostics(
            deb822_file,
            stanza,
            stanza_position,
            lint_state,
            confusable_with_stanza_metadata=other_stanza_metadata,
            confusable_with_stanza_name=other_stanza_name,
            inherit_from_stanza=source_stanza if is_binary_stanza else None,
        )

    _detect_misspelled_packaging_files(
        lint_state,
        binary_stanzas_w_pos,
    )


def _package_range_of_stanza(
    binary_stanzas: list[tuple[Deb822ParagraphElement, TEPosition]],
) -> Iterable[tuple[str, str | None, "TERange"]]:
    for stanza, stanza_position in binary_stanzas:
        kvpair = stanza.get_kvpair_element(("Package", 0), use_get=True)
        if kvpair is None:
            continue
        representation_field_range = kvpair.range_in_parent().relative_to(
            stanza_position
        )
        yield stanza["Package"], stanza.get("Architecture"), representation_field_range


def _packaging_files(
    lint_state: LintState,
) -> Iterable[PackagerProvidedFile]:
    source_root = lint_state.source_root
    debian_dir = lint_state.debian_dir
    binary_packages = lint_state.binary_packages
    if (
        source_root is None
        or not source_root.has_fs_path
        or debian_dir is None
        or binary_packages is None
    ):
        return

    debputy_integration_mode = lint_state.debputy_metadata.debputy_integration_mode
    dh_sequencer_data = lint_state.dh_sequencer_data
    dh_sequences = dh_sequencer_data.sequences
    is_debputy_package = debputy_integration_mode is not None
    feature_set = lint_state.plugin_feature_set
    known_packaging_files = feature_set.known_packaging_files
    static_packaging_files = {
        kpf.detection_value: kpf
        for kpf in known_packaging_files.values()
        if kpf.detection_method == "path"
    }
    ignored_path = set(static_packaging_files)

    if is_debputy_package:
        all_debputy_ppfs = list(
            flatten_ppfs(
                detect_all_packager_provided_files(
                    feature_set,
                    debian_dir,
                    binary_packages,
                    allow_fuzzy_matches=True,
                    detect_typos=True,
                    ignore_paths=ignored_path,
                )
            )
        )
        for ppf in all_debputy_ppfs:
            if ppf.path.path in ignored_path:
                continue
            ignored_path.add(ppf.path.path)
            yield ppf

    # FIXME: This should read the editor data, but dh_assistant does not support that.
    dh_compat_level, _ = extract_dh_compat_level(cwd=source_root.fs_path)
    if dh_compat_level is not None:
        debputy_plugin_metadata = plugin_metadata_for_debputys_own_plugin()
        (
            all_dh_ppfs,
            _,
            _,
            _,
        ) = resolve_debhelper_config_files(
            debian_dir,
            binary_packages,
            debputy_plugin_metadata,
            feature_set,
            dh_sequences,
            dh_compat_level,
            saw_dh=dh_sequencer_data.uses_dh_sequencer,
            ignore_paths=ignored_path,
            debputy_integration_mode=debputy_integration_mode,
            cwd=source_root.fs_path,
        )
        for ppf in all_dh_ppfs:
            if ppf.path.path in ignored_path:
                continue
            ignored_path.add(ppf.path.path)
            yield ppf


def _detect_misspelled_packaging_files(
    lint_state: LintState,
    binary_stanzas_w_pos: list[tuple[Deb822ParagraphElement, TEPosition]],
) -> None:
    stanza_ranges = {
        p: (a, r) for p, a, r in _package_range_of_stanza(binary_stanzas_w_pos)
    }
    for ppf in _packaging_files(lint_state):
        binary_package = ppf.package_name
        explicit_package = ppf.uses_explicit_package_name
        name_segment = ppf.name_segment is not None
        stem = ppf.definition.stem
        if _is_trace_log_enabled():
            _trace_log(
                f"PPF check: {binary_package} {stem=} {explicit_package=} {name_segment=} {ppf.expected_path=} {ppf.definition.has_active_command=}"
            )
        if binary_package is None or stem is None:
            continue
        res = stanza_ranges.get(binary_package)
        if res is None:
            continue
        declared_arch, diag_range = res
        if diag_range is None:
            continue
        path = ppf.path.path
        likely_typo_of = ppf.expected_path
        arch_restriction = ppf.architecture_restriction
        if likely_typo_of is not None:
            # Handles arch_restriction == 'all' at the same time due to how
            # the `likely-typo-of` is created
            lint_state.emit_diagnostic(
                diag_range,
                f'The file "{path}" is likely a typo of "{likely_typo_of}"',
                "warning",
                "debputy",
                diagnostic_applies_to_another_file=path,
            )
            continue
        if declared_arch == "all" and arch_restriction is not None:
            lint_state.emit_diagnostic(
                diag_range,
                f'The file "{path}" has an architecture restriction but is for an `arch:all` package, so'
                f" the restriction does not make sense.",
                "warning",
                "debputy",
                diagnostic_applies_to_another_file=path,
            )
        elif arch_restriction == "all":
            lint_state.emit_diagnostic(
                diag_range,
                f'The file "{path}" has an architecture restriction of `all` rather than a real architecture',
                "warning",
                "debputy",
                diagnostic_applies_to_another_file=path,
            )

        if not ppf.definition.has_active_command:
            lint_state.emit_diagnostic(
                diag_range,
                f"The file {path} is related to a command that is not active in the dh sequence"
                " with the current addons",
                "warning",
                "debputy",
                diagnostic_applies_to_another_file=path,
            )
            continue

        if not explicit_package and name_segment is not None:
            basename = os.path.basename(path)
            if basename == ppf.definition.stem:
                continue
            alt_name = f"{binary_package}.{stem}"
            if arch_restriction is not None:
                alt_name = f"{alt_name}.{arch_restriction}"
            if ppf.definition.allow_name_segment:
                or_alt_name = f' (or maybe "debian/{binary_package}.{basename}")'
            else:
                or_alt_name = ""

            lint_state.emit_diagnostic(
                diag_range,
                f'Possible typo in "{path}". Consider renaming the file to "debian/{alt_name}"'
                f"{or_alt_name} if it is intended for {binary_package}",
                "warning",
                "debputy",
                diagnostic_applies_to_another_file=path,
            )


@lsp_will_save_wait_until(_DISPATCH_RULE)
def _debian_control_on_save_formatting(
    ls: "DebputyLanguageServer",
    params: WillSaveTextDocumentParams,
) -> Sequence[TextEdit] | None:
    doc = ls.workspace.get_text_document(params.text_document.uri)
    lint_state = ls.lint_state(doc)
    return _reformat_debian_control(lint_state)


@lsp_cli_reformat_document(_DISPATCH_RULE)
def _reformat_debian_control(
    lint_state: LintState,
) -> Sequence[TextEdit] | None:
    return deb822_format_file(lint_state, _DCTRL_FILE_METADATA)


@lsp_format_document(_DISPATCH_RULE)
def _debian_control_format_file(
    ls: "DebputyLanguageServer",
    params: DocumentFormattingParams,
) -> Sequence[TextEdit] | None:
    doc = ls.workspace.get_text_document(params.text_document.uri)
    lint_state = ls.lint_state(doc)
    return _reformat_debian_control(lint_state)


@lsp_semantic_tokens_full(_DISPATCH_RULE)
async def _debian_control_semantic_tokens_full(
    ls: "DebputyLanguageServer",
    request: SemanticTokensParams,
) -> SemanticTokens | None:
    return await deb822_semantic_tokens_full(
        ls,
        request,
        _DCTRL_FILE_METADATA,
    )