Coverage for src/debputy/lsp/languages/lsp_debian_control.py: 62%
420 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-28 20:14 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-28 20:14 +0000
1import dataclasses
2import importlib.resources
3import os.path
4import textwrap
5from functools import lru_cache
6from itertools import chain
7from typing import (
8 Optional,
9 Self,
10 TYPE_CHECKING,
11)
12from collections.abc import Sequence, Mapping, Iterable
14import debputy.lsp.data.deb822_data as deb822_ref_data_dir
15from debputy.analysis.analysis_util import flatten_ppfs
16from debputy.analysis.debian_dir import resolve_debhelper_config_files
17from debputy.dh.dh_assistant import extract_dh_compat_level
18from debputy.linting.lint_util import (
19 LintState,
20 te_range_to_lsp,
21 te_position_to_lsp,
22 with_range_in_continuous_parts,
23)
24from debputy.lsp.apt_cache import PackageLookup
25from debputy.lsp.debputy_ls import DebputyLanguageServer
26from debputy.lsp.lsp_debian_control_reference_data import (
27 DctrlKnownField,
28 DctrlFileMetadata,
29 package_name_to_section,
30 all_package_relationship_fields,
31 extract_first_value_and_position,
32 all_source_relationship_fields,
33 StanzaMetadata,
34 SUBSTVAR_RE,
35 dpkg_architecture_values,
36)
37from debputy.lsp.lsp_features import (
38 lint_diagnostics,
39 lsp_completer,
40 lsp_hover,
41 lsp_standard_handler,
42 lsp_folding_ranges,
43 lsp_semantic_tokens_full,
44 lsp_will_save_wait_until,
45 lsp_format_document,
46 lsp_text_doc_inlay_hints,
47 LanguageDispatchRule,
48 SecondaryLanguage,
49 lsp_cli_reformat_document,
50)
51from debputy.lsp.lsp_generic_deb822 import (
52 deb822_completer,
53 deb822_hover,
54 deb822_folding_ranges,
55 deb822_semantic_tokens_full,
56 deb822_format_file,
57 scan_for_syntax_errors_and_token_level_diagnostics,
58)
59from debputy.lsp.lsp_reference_keyword import LSP_DATA_DOMAIN
60from debputy.lsp.quickfixes import (
61 propose_correct_text_quick_fix,
62 propose_insert_text_on_line_after_diagnostic_quick_fix,
63 propose_remove_range_quick_fix,
64)
65from debputy.lsp.ref_models.deb822_reference_parse_models import (
66 DCTRL_SUBSTVARS_REFERENCE_DATA_PARSER,
67 DCtrlSubstvar,
68)
69from debputy.lsp.text_util import markdown_urlify
70from debian._deb822_repro import (
71 Deb822ParagraphElement,
72)
73from debian._deb822_repro.parsing import (
74 Deb822KeyValuePairElement,
75)
76from debputy.lsprotocol.types import (
77 Position,
78 FoldingRange,
79 FoldingRangeParams,
80 CompletionItem,
81 CompletionList,
82 CompletionParams,
83 HoverParams,
84 Hover,
85 TEXT_DOCUMENT_CODE_ACTION,
86 SemanticTokens,
87 SemanticTokensParams,
88 WillSaveTextDocumentParams,
89 TextEdit,
90 DocumentFormattingParams,
91 InlayHint,
92)
93from debputy.manifest_parser.util import AttributePath
94from debputy.packager_provided_files import (
95 PackagerProvidedFile,
96 detect_all_packager_provided_files,
97)
98from debputy.plugin.api.impl import plugin_metadata_for_debputys_own_plugin
99from debputy.util import PKGNAME_REGEX, _info, _trace_log, _is_trace_log_enabled
100from debputy.yaml import MANIFEST_YAML
102if TYPE_CHECKING:
103 import lsprotocol.types as types
104else:
105 import debputy.lsprotocol.types as types
107try:
108 from debian._deb822_repro.locatable import (
109 Position as TEPosition,
110 Range as TERange,
111 START_POSITION,
112 )
114 from pygls.workspace import TextDocument
115except ImportError:
116 pass
119_DISPATCH_RULE = LanguageDispatchRule.new_rule(
120 "debian/control",
121 None,
122 "debian/control",
123 [
124 # emacs's name
125 SecondaryLanguage("debian-control"),
126 # vim's name
127 SecondaryLanguage("debcontrol"),
128 ],
129)
132@dataclasses.dataclass(slots=True, frozen=True)
133class SubstvarMetadata:
134 name: str
135 defined_by: str
136 dh_sequence: str | None
137 doc_uris: Sequence[str]
138 synopsis: str
139 description: str
141 def render_metadata_fields(self) -> str:
142 def_by = f"Defined by: {self.defined_by}"
143 doc_uris = self.doc_uris
144 parts = [def_by]
145 if self.dh_sequence is not None: 145 ↛ 147line 145 didn't jump to line 147 because the condition on line 145 was always true
146 parts.append(f"DH Sequence: {self.dh_sequence}")
147 if doc_uris: 147 ↛ 153line 147 didn't jump to line 153 because the condition on line 147 was always true
148 if len(doc_uris) == 1: 148 ↛ 151line 148 didn't jump to line 151 because the condition on line 148 was always true
149 parts.append(f"Documentation: {markdown_urlify(doc_uris[0])}")
150 else:
151 parts.append("Documentation:")
152 parts.extend(f" - {markdown_urlify(uri)}" for uri in doc_uris)
153 return "\n".join(parts)
155 @classmethod
156 def from_ref_data(cls, x: DCtrlSubstvar) -> "Self":
157 doc = x.get("documentation", {})
158 return cls(
159 x["name"],
160 x["defined_by"],
161 x.get("dh_sequence"),
162 doc.get("uris", []),
163 doc.get("synopsis", ""),
164 doc.get("long_description", ""),
165 )
168def relationship_substvar_for_field(substvar: str) -> str | None:
169 relationship_fields = all_package_relationship_fields()
170 try:
171 col_idx = substvar.rindex(":")
172 except ValueError:
173 return None
174 return relationship_fields.get(substvar[col_idx + 1 : -1].lower())
177def _as_substvars_metadata(
178 args: list[SubstvarMetadata],
179) -> Mapping[str, SubstvarMetadata]:
180 r = {s.name: s for s in args}
181 assert len(r) == len(args)
182 return r
185def dctrl_variables_metadata_basename() -> str:
186 return "debian_control_variables_data.yaml"
189@lru_cache
190def dctrl_substvars_metadata() -> Mapping[str, SubstvarMetadata]:
191 p = importlib.resources.files(deb822_ref_data_dir.__name__).joinpath(
192 dctrl_variables_metadata_basename()
193 )
195 with p.open("r", encoding="utf-8") as fd:
196 raw = MANIFEST_YAML.load(fd)
198 attr_path = AttributePath.root_path(p)
199 ref = DCTRL_SUBSTVARS_REFERENCE_DATA_PARSER.parse_input(raw, attr_path)
200 return _as_substvars_metadata(
201 [SubstvarMetadata.from_ref_data(x) for x in ref["variables"]]
202 )
205_DCTRL_FILE_METADATA = DctrlFileMetadata()
208lsp_standard_handler(_DISPATCH_RULE, TEXT_DOCUMENT_CODE_ACTION)
211@lsp_hover(_DISPATCH_RULE)
212def _debian_control_hover(
213 ls: "DebputyLanguageServer",
214 params: HoverParams,
215) -> Hover | None:
216 return deb822_hover(ls, params, _DCTRL_FILE_METADATA, custom_handler=_custom_hover)
219def _custom_hover_description(
220 _ls: "DebputyLanguageServer",
221 _known_field: DctrlKnownField,
222 line: str,
223 _word_at_position: str,
224) -> Hover | str | None:
225 if line[0].isspace(): 225 ↛ 226line 225 didn't jump to line 226 because the condition on line 225 was never true
226 return None
227 try:
228 col_idx = line.index(":")
229 except ValueError:
230 return None
232 content = line[col_idx + 1 :].strip()
234 # Synopsis
235 return textwrap.dedent(f"""\
236 # Package synopsis
238 The synopsis functions as a phrase describing the package, not a
239 complete sentence, so sentential punctuation is inappropriate: it
240 does not need extra capital letters or a final period (full stop).
241 It should also omit any initial indefinite or definite article
242 - "a", "an", or "the". Thus for instance:
244 ```
245 Package: libeg0
246 Description: exemplification support library
247 ```
249 Technically this is a noun phrase minus articles, as opposed to a
250 verb phrase. A good heuristic is that it should be possible to
251 substitute the package name and synopsis into this formula:
253 ```
254 # Generic
255 The package provides {{a,an,the,some}} synopsis.
257 # The current package for comparison
258 The package provides {{a,an,the,some}} {content}.
259 ```
261 Other advice for writing synopsis:
262 * Avoid using the package name. Any software would display the
263 package name already and it generally does not help the user
264 understand what they are looking at.
265 * In many situations, the user will only see the package name
266 and its synopsis. The synopsis must be able to stand alone.
268 **Example renderings in various terminal UIs**:
269 ```
270 # apt search TERM
271 package/stable,now 1.0-1 all:
272 {content}
274 # apt-get search TERM
275 package - {content}
276 ```
278 ## Reference example
280 An reference example for comparison: The Sphinx package
281 (python3-sphinx/7.2.6-6) had the following synopsis:
283 ```
284 Description: documentation generator for Python projects
285 ```
287 In the test sentence, it would read as:
289 ```
290 The python3-sphinx package provides a documentation generator for Python projects.
291 ```
293 **Side-by-side comparison in the terminal UIs**:
294 ```
295 # apt search TERM
296 python3-sphinx/stable,now 7.2.6-6 all:
297 documentation generator for Python projects
299 package/stable,now 1.0-1 all:
300 {content}
303 # apt-get search TERM
304 package - {content}
305 python3-sphinx - documentation generator for Python projects
306 ```
307 """)
310def _render_package_lookup(
311 package_lookup: PackageLookup,
312 known_field: DctrlKnownField,
313) -> str:
314 name = package_lookup.name
315 provider = package_lookup.package
316 if package_lookup.package is None and len(package_lookup.provided_by) == 1:
317 provider = package_lookup.provided_by[0]
319 if provider:
320 segments = [
321 f"# {name} ({provider.version}, {provider.architecture}) ",
322 "",
323 ]
325 if (
326 _is_bd_field(known_field)
327 and name.startswith("dh-sequence-")
328 and len(name) > 12
329 ):
330 sequence = name[12:]
331 segments.append(
332 f"This build-dependency will activate the `dh` sequence called `{sequence}`."
333 )
334 segments.append("")
336 elif (
337 known_field.name == "Build-Depends"
338 and name.startswith("debputy-plugin-")
339 and len(name) > 15
340 ):
341 plugin_name = name[15:]
342 segments.append(
343 f"This build-dependency will activate the `debputy` plugin called `{plugin_name}`."
344 )
345 segments.append("")
347 segments.extend(
348 [
349 f"Synopsis: {provider.synopsis}",
350 "",
351 f"Multi-Arch: {provider.multi_arch}",
352 "",
353 f"Section: {provider.section}",
354 ]
355 )
356 if provider.upstream_homepage is not None:
357 segments.append("")
358 segments.append(f"Upstream homepage: {provider.upstream_homepage}")
359 segments.append("")
360 segments.append(
361 "Data is from the system's APT cache, which may not match the target distribution."
362 )
363 return "\n".join(segments)
365 segments = [
366 f"# {name} [virtual]",
367 "",
368 "The package {name} is a virtual package provided by one of:",
369 ]
370 segments.extend(f" * {p.name}" for p in package_lookup.provided_by)
371 segments.append("")
372 segments.append(
373 "Data is from the system's APT cache, which may not match the target distribution."
374 )
375 return "\n".join(segments)
378def _disclaimer(is_empty: bool) -> str:
379 if is_empty:
380 return textwrap.dedent("""\
381 The system's APT cache is empty, so it was not possible to verify that the
382 package exist.
383""")
384 return textwrap.dedent("""\
385 The package is not known by the APT cache on this system, so there may be typo
386 or the package may not be available in the version of your distribution.
387""")
390def _render_package_by_name(
391 name: str, known_field: DctrlKnownField, is_empty: bool
392) -> str | None:
393 if _is_bd_field(known_field) and name.startswith("dh-sequence-") and len(name) > 12:
394 sequence = name[12:]
395 return textwrap.dedent(f"""\
396 # {name}
398 This build-dependency will activate the `dh` sequence called `{sequence}`.
400 """) + _disclaimer(is_empty)
401 if (
402 known_field.name == "Build-Depends"
403 and name.startswith("debputy-plugin-")
404 and len(name) > 15
405 ):
406 plugin_name = name[15:]
407 return textwrap.dedent(f"""\
408 # {name}
410 This build-dependency will activate the `debputy` plugin called `{plugin_name}`.
412 """) + _disclaimer(is_empty)
413 return textwrap.dedent(f"""\
414 # {name}
416 """) + _disclaimer(is_empty)
419def _is_bd_field(known_field: DctrlKnownField) -> bool:
420 return known_field.name in (
421 "Build-Depends",
422 "Build-Depends-Arch",
423 "Build-Depends-Indep",
424 )
427def _custom_hover_relationship_field(
428 ls: "DebputyLanguageServer",
429 known_field: DctrlKnownField,
430 _line: str,
431 word_at_position: str,
432) -> Hover | str | None:
433 apt_cache = ls.apt_cache
434 state = apt_cache.state
435 is_empty = False
436 _info(f"Rel field: {known_field.name} - {word_at_position} - {state}")
437 if "|" in word_at_position: 437 ↛ 438line 437 didn't jump to line 438 because the condition on line 437 was never true
438 return textwrap.dedent(f"""\
439 Sorry, no hover docs for OR relations at the moment.
441 The relation being matched: `{word_at_position}`
443 The code is missing logic to determine which side of the OR the lookup is happening.
444 """)
445 match = next(iter(PKGNAME_REGEX.finditer(word_at_position)), None)
446 if match is None: 446 ↛ 447line 446 didn't jump to line 447 because the condition on line 446 was never true
447 return None
448 package = match.group()
449 if state == "empty-cache": 449 ↛ 450line 449 didn't jump to line 450 because the condition on line 449 was never true
450 state = "loaded"
451 is_empty = True
452 if state == "loaded": 452 ↛ 453line 452 didn't jump to line 453 because the condition on line 452 was never true
453 result = apt_cache.lookup(package)
454 if result is None:
455 return _render_package_by_name(
456 package,
457 known_field,
458 is_empty=is_empty,
459 )
460 return _render_package_lookup(result, known_field)
462 if state in ( 462 ↛ 474line 462 didn't jump to line 474 because the condition on line 462 was always true
463 "not-loaded",
464 "failed",
465 "tooling-not-available",
466 ):
467 details = apt_cache.load_error if apt_cache.load_error else "N/A"
468 return textwrap.dedent(f"""\
469 Sorry, the APT cache data is not available due to an error or missing tool.
471 Details: {details}
472 """)
474 if state == "empty-cache":
475 return f"Cannot lookup {package}: APT cache data was empty"
477 if state == "loading":
478 return f"Cannot lookup {package}: APT cache data is still being indexed. Please try again in a moment."
479 return None
482_CUSTOM_FIELD_HOVER = dict(
483 (
484 (field, _custom_hover_relationship_field)
485 for field in chain(
486 all_package_relationship_fields().values(),
487 all_source_relationship_fields().values(),
488 )
489 if field != "Provides"
490 ),
491 Description=_custom_hover_description,
492)
495def _custom_hover(
496 ls: "DebputyLanguageServer",
497 server_position: Position,
498 _current_field: str | None,
499 word_at_position: str,
500 known_field: DctrlKnownField | None,
501 in_value: bool,
502 _doc: "TextDocument",
503 lines: list[str],
504) -> Hover | str | None:
505 if not in_value:
506 return None
508 line_no = server_position.line
509 line = lines[line_no]
510 substvar_search_ref = server_position.character
511 substvar = ""
512 try:
513 if line and line[substvar_search_ref] in ("$", "{"):
514 substvar_search_ref += 2
515 substvar_start = line.rindex("${", 0, substvar_search_ref)
516 substvar_end = line.index("}", substvar_start)
517 if server_position.character <= substvar_end:
518 substvar = line[substvar_start : substvar_end + 1]
519 except (ValueError, IndexError):
520 pass
522 if substvar == "${}" or SUBSTVAR_RE.fullmatch(substvar):
523 substvar_md = dctrl_substvars_metadata().get(substvar)
525 computed_doc = ""
526 for_field = relationship_substvar_for_field(substvar)
527 if for_field: 527 ↛ 529line 527 didn't jump to line 529 because the condition on line 527 was never true
528 # Leading empty line is intentional!
529 computed_doc = textwrap.dedent(f"""
530 This substvar is a relationship substvar for the field {for_field}.
531 Relationship substvars are automatically added in the field they
532 are named after in `debhelper-compat (= 14)` or later, or with
533 `debputy` (any integration mode after 0.1.21).
534 """)
536 if substvar_md is None: 536 ↛ 537line 536 didn't jump to line 537 because the condition on line 536 was never true
537 doc = f"No documentation for {substvar}.\n"
538 md_fields = ""
539 else:
540 doc = ls.translation(LSP_DATA_DOMAIN).pgettext(
541 f"Variable:{substvar_md.name}",
542 substvar_md.description,
543 )
544 md_fields = "\n" + substvar_md.render_metadata_fields()
545 return f"# Substvar `{substvar}`\n\n{doc}{computed_doc}{md_fields}"
547 if known_field is None: 547 ↛ 548line 547 didn't jump to line 548 because the condition on line 547 was never true
548 return None
549 dispatch = _CUSTOM_FIELD_HOVER.get(known_field.name)
550 if dispatch is None: 550 ↛ 551line 550 didn't jump to line 551 because the condition on line 550 was never true
551 return None
552 return dispatch(ls, known_field, line, word_at_position)
555@lsp_completer(_DISPATCH_RULE)
556def _debian_control_completions(
557 ls: "DebputyLanguageServer",
558 params: CompletionParams,
559) -> CompletionList | Sequence[CompletionItem] | None:
560 return deb822_completer(ls, params, _DCTRL_FILE_METADATA)
563@lsp_folding_ranges(_DISPATCH_RULE)
564def _debian_control_folding_ranges(
565 ls: "DebputyLanguageServer",
566 params: FoldingRangeParams,
567) -> Sequence[FoldingRange] | None:
568 return deb822_folding_ranges(ls, params, _DCTRL_FILE_METADATA)
571@lsp_text_doc_inlay_hints(_DISPATCH_RULE)
572async def _doc_inlay_hint(
573 ls: "DebputyLanguageServer",
574 params: types.InlayHintParams,
575) -> list[InlayHint] | None:
576 doc = ls.workspace.get_text_document(params.text_document.uri)
577 lint_state = ls.lint_state(doc)
578 deb822_file = lint_state.parsed_deb822_file_content
579 if not deb822_file:
580 return None
581 inlay_hints = []
582 stanzas = list(deb822_file)
583 if len(stanzas) < 2:
584 return None
585 source_stanza = stanzas[0]
586 source_stanza_pos = source_stanza.position_in_file()
587 inherited_inlay_label_part = {}
588 stanza_no = 0
590 async for stanza_range, stanza in lint_state.slow_iter(
591 with_range_in_continuous_parts(deb822_file.iter_parts())
592 ):
593 if not isinstance(stanza, Deb822ParagraphElement):
594 continue
595 stanza_def = _DCTRL_FILE_METADATA.classify_stanza(stanza, stanza_no)
596 stanza_no += 1
597 pkg_kvpair = stanza.get_kvpair_element(("Package", 0), use_get=True)
598 if pkg_kvpair is None:
599 continue
601 parts = []
602 async for known_field in ls.slow_iter(
603 stanza_def.stanza_fields.values(), yield_every=25
604 ):
605 if (
606 not known_field.inheritable_from_other_stanza
607 or not known_field.show_as_inherited
608 or known_field.name in stanza
609 ):
610 continue
612 inherited_value = source_stanza.get(known_field.name)
613 if inherited_value is not None:
614 inlay_hint_label_part = inherited_inlay_label_part.get(known_field.name)
615 if inlay_hint_label_part is None:
616 kvpair = source_stanza.get_kvpair_element(known_field.name)
617 value_range_te = kvpair.range_in_parent().relative_to(
618 source_stanza_pos
619 )
620 value_range = doc.position_codec.range_to_client_units(
621 lint_state.lines,
622 te_range_to_lsp(value_range_te),
623 )
624 inlay_hint_label_part = types.InlayHintLabelPart(
625 f" ({known_field.name}: {inherited_value})",
626 tooltip="Inherited from Source stanza",
627 location=types.Location(
628 params.text_document.uri,
629 value_range,
630 ),
631 )
632 inherited_inlay_label_part[known_field.name] = inlay_hint_label_part
633 parts.append(inlay_hint_label_part)
635 if parts:
636 known_field = stanza_def["Package"]
637 values = known_field.field_value_class.interpreter().interpret(pkg_kvpair)
638 assert values is not None
639 anchor_value = list(values.iter_value_references())[-1]
640 anchor_position = (
641 anchor_value.locatable.range_in_parent().end_pos.relative_to(
642 pkg_kvpair.value_element.position_in_parent().relative_to(
643 stanza_range.start_pos
644 )
645 )
646 )
647 anchor_position_client_units = doc.position_codec.position_to_client_units(
648 lint_state.lines,
649 te_position_to_lsp(anchor_position),
650 )
651 inlay_hints.append(
652 types.InlayHint(
653 anchor_position_client_units,
654 parts,
655 padding_left=True,
656 padding_right=False,
657 )
658 )
659 return inlay_hints
662def _source_package_checks(
663 stanza: Deb822ParagraphElement,
664 stanza_position: "TEPosition",
665 stanza_metadata: StanzaMetadata[DctrlKnownField],
666 lint_state: LintState,
667) -> None:
668 vcs_fields = {}
669 source_fields = _DCTRL_FILE_METADATA["Source"].stanza_fields
670 for kvpair in stanza.iter_parts_of_type(Deb822KeyValuePairElement):
671 name = stanza_metadata.normalize_field_name(kvpair.field_name.lower())
672 if (
673 not name.startswith("vcs-")
674 or name == "vcs-browser"
675 or name not in source_fields
676 ):
677 continue
678 vcs_fields[name] = kvpair
680 if len(vcs_fields) < 2:
681 return
682 for kvpair in vcs_fields.values():
683 lint_state.emit_diagnostic(
684 kvpair.range_in_parent().relative_to(stanza_position),
685 f'Multiple Version Control fields defined ("{kvpair.field_name}")',
686 "warning",
687 "Policy 5.6.26",
688 quickfixes=[
689 propose_remove_range_quick_fix(
690 proposed_title=f'Remove "{kvpair.field_name}"'
691 )
692 ],
693 )
696def _binary_package_checks(
697 stanza: Deb822ParagraphElement,
698 stanza_position: "TEPosition",
699 source_stanza: Deb822ParagraphElement,
700 representation_field_range: "TERange",
701 lint_state: LintState,
702) -> None:
703 package_name = stanza.get("Package", "")
704 source_section = source_stanza.get("Section")
705 section_kvpair = stanza.get_kvpair_element(("Section", 0), use_get=True)
706 section: str | None = None
707 section_range: Optional["TERange"] = None
708 if section_kvpair is not None:
709 section, section_range = extract_first_value_and_position(
710 section_kvpair,
711 stanza_position,
712 )
714 if section_range is None:
715 section_range = representation_field_range
716 effective_section = section or source_section or "unknown"
717 package_type = stanza.get("Package-Type", "")
718 component_prefix = ""
719 if "/" in effective_section:
720 component_prefix, effective_section = effective_section.split("/", maxsplit=1)
721 component_prefix += "/"
723 if package_name.endswith("-udeb") or package_type == "udeb":
724 if package_type != "udeb": 724 ↛ 725line 724 didn't jump to line 725 because the condition on line 724 was never true
725 package_type_kvpair = stanza.get_kvpair_element(
726 "Package-Type", use_get=True
727 )
728 package_type_range: Optional["TERange"] = None
729 if package_type_kvpair is not None:
730 _, package_type_range = extract_first_value_and_position(
731 package_type_kvpair,
732 stanza_position,
733 )
734 if package_type_range is None:
735 package_type_range = representation_field_range
736 lint_state.emit_diagnostic(
737 package_type_range,
738 'The Package-Type should be "udeb" given the package name',
739 "warning",
740 "debputy",
741 )
742 guessed_section = "debian-installer"
743 section_diagnostic_rationale = " since it is an udeb"
744 else:
745 guessed_section = package_name_to_section(package_name)
746 section_diagnostic_rationale = " based on the package name"
747 if guessed_section is not None and guessed_section != effective_section: 747 ↛ 748line 747 didn't jump to line 748 because the condition on line 747 was never true
748 if section is not None:
749 quickfix_data = [
750 propose_correct_text_quick_fix(f"{component_prefix}{guessed_section}")
751 ]
752 else:
753 quickfix_data = [
754 propose_insert_text_on_line_after_diagnostic_quick_fix(
755 f"Section: {component_prefix}{guessed_section}\n"
756 )
757 ]
758 assert section_range is not None # mypy hint
759 lint_state.emit_diagnostic(
760 section_range,
761 f'The Section should be "{component_prefix}{guessed_section}"{section_diagnostic_rationale}',
762 "warning",
763 "debputy",
764 quickfixes=quickfix_data,
765 )
768@lint_diagnostics(_DISPATCH_RULE)
769async def _lint_debian_control(lint_state: LintState) -> None:
770 deb822_file = lint_state.parsed_deb822_file_content
772 if not _DCTRL_FILE_METADATA.file_metadata_applies_to_file(deb822_file): 772 ↛ 773line 772 didn't jump to line 773 because the condition on line 772 was never true
773 return
775 first_error = await scan_for_syntax_errors_and_token_level_diagnostics(
776 deb822_file,
777 lint_state,
778 )
780 stanzas = list(deb822_file)
781 source_stanza = stanzas[0] if stanzas else None
782 binary_stanzas_w_pos = []
784 source_stanza_metadata, binary_stanza_metadata = _DCTRL_FILE_METADATA.stanza_types()
785 stanza_no = 0
787 async for stanza_range, stanza in lint_state.slow_iter(
788 with_range_in_continuous_parts(deb822_file.iter_parts())
789 ):
790 if not isinstance(stanza, Deb822ParagraphElement):
791 continue
792 stanza_position = stanza_range.start_pos
793 if stanza_position.line_position >= first_error: 793 ↛ 794line 793 didn't jump to line 794 because the condition on line 793 was never true
794 break
795 stanza_no += 1
796 is_binary_stanza = stanza_no != 1
797 if is_binary_stanza:
798 stanza_metadata = binary_stanza_metadata
799 other_stanza_metadata = source_stanza_metadata
800 other_stanza_name = "Source"
801 binary_stanzas_w_pos.append((stanza, stanza_position))
802 _, representation_field_range = stanza_metadata.stanza_representation(
803 stanza, stanza_position
804 )
805 _binary_package_checks(
806 stanza,
807 stanza_position,
808 source_stanza,
809 representation_field_range,
810 lint_state,
811 )
812 else:
813 stanza_metadata = source_stanza_metadata
814 other_stanza_metadata = binary_stanza_metadata
815 other_stanza_name = "Binary"
816 _source_package_checks(
817 stanza,
818 stanza_position,
819 stanza_metadata,
820 lint_state,
821 )
823 await stanza_metadata.stanza_diagnostics(
824 deb822_file,
825 stanza,
826 stanza_position,
827 lint_state,
828 confusable_with_stanza_metadata=other_stanza_metadata,
829 confusable_with_stanza_name=other_stanza_name,
830 inherit_from_stanza=source_stanza if is_binary_stanza else None,
831 )
833 _detect_misspelled_packaging_files(
834 lint_state,
835 binary_stanzas_w_pos,
836 )
839def _package_range_of_stanza(
840 binary_stanzas: list[tuple[Deb822ParagraphElement, TEPosition]],
841) -> Iterable[tuple[str, str | None, "TERange"]]:
842 for stanza, stanza_position in binary_stanzas:
843 kvpair = stanza.get_kvpair_element(("Package", 0), use_get=True)
844 if kvpair is None: 844 ↛ 845line 844 didn't jump to line 845 because the condition on line 844 was never true
845 continue
846 representation_field_range = kvpair.range_in_parent().relative_to(
847 stanza_position
848 )
849 yield stanza["Package"], stanza.get("Architecture"), representation_field_range
852def _packaging_files(
853 lint_state: LintState,
854) -> Iterable[PackagerProvidedFile]:
855 source_root = lint_state.source_root
856 debian_dir = lint_state.debian_dir
857 binary_packages = lint_state.binary_packages
858 if (
859 source_root is None
860 or not source_root.has_fs_path
861 or debian_dir is None
862 or binary_packages is None
863 ):
864 return
866 debputy_integration_mode = lint_state.debputy_metadata.debputy_integration_mode
867 dh_sequencer_data = lint_state.dh_sequencer_data
868 dh_sequences = dh_sequencer_data.sequences
869 is_debputy_package = debputy_integration_mode is not None
870 feature_set = lint_state.plugin_feature_set
871 known_packaging_files = feature_set.known_packaging_files
872 static_packaging_files = {
873 kpf.detection_value: kpf
874 for kpf in known_packaging_files.values()
875 if kpf.detection_method == "path"
876 }
877 ignored_path = set(static_packaging_files)
878 arch_names = dpkg_architecture_values("ARCH")
879 arch_os_names = dpkg_architecture_values("ARCH_OS")
881 if is_debputy_package:
882 all_debputy_ppfs = list(
883 flatten_ppfs(
884 detect_all_packager_provided_files(
885 feature_set,
886 debian_dir,
887 binary_packages,
888 allow_fuzzy_matches=True,
889 detect_typos=True,
890 ignore_paths=ignored_path,
891 match_arch=arch_names,
892 match_arch_os=arch_os_names,
893 multi_match=True,
894 )
895 )
896 )
897 for ppf in all_debputy_ppfs:
898 if ppf.path.path in ignored_path: 898 ↛ 899line 898 didn't jump to line 899 because the condition on line 898 was never true
899 continue
900 ignored_path.add(ppf.path.path)
901 yield ppf
903 # FIXME: This should read the editor data, but dh_assistant does not support that.
904 dh_compat_level, _ = extract_dh_compat_level(cwd=source_root.fs_path)
905 if dh_compat_level is not None: 905 ↛ exitline 905 didn't return from function '_packaging_files' because the condition on line 905 was always true
906 debputy_plugin_metadata = plugin_metadata_for_debputys_own_plugin()
907 (
908 all_dh_ppfs,
909 _,
910 _,
911 _,
912 ) = resolve_debhelper_config_files(
913 debian_dir,
914 binary_packages,
915 debputy_plugin_metadata,
916 feature_set,
917 dh_sequences,
918 dh_compat_level,
919 saw_dh=dh_sequencer_data.uses_dh_sequencer,
920 ignore_paths=ignored_path,
921 debputy_integration_mode=debputy_integration_mode,
922 cwd=source_root.fs_path,
923 match_arch=arch_names,
924 match_arch_os=arch_os_names,
925 multi_match=True,
926 )
927 for ppf in all_dh_ppfs:
929 if ppf.path.path in ignored_path: 929 ↛ 930line 929 didn't jump to line 930 because the condition on line 929 was never true
930 continue
931 ignored_path.add(ppf.path.path)
932 yield ppf
935def _detect_misspelled_packaging_files(
936 lint_state: LintState,
937 binary_stanzas_w_pos: list[tuple[Deb822ParagraphElement, TEPosition]],
938) -> None:
939 stanza_ranges = {
940 p: (a, r) for p, a, r in _package_range_of_stanza(binary_stanzas_w_pos)
941 }
942 for ppf in _packaging_files(lint_state):
943 binary_package = ppf.package_name
944 explicit_package = ppf.uses_explicit_package_name
945 name_segment = ppf.name_segment is not None
946 stem = ppf.definition.stem
947 if _is_trace_log_enabled(): 947 ↛ 948line 947 didn't jump to line 948 because the condition on line 947 was never true
948 _trace_log(
949 f"PPF check: {binary_package} {stem=} {explicit_package=} {name_segment=} {ppf.expected_path=} {ppf.definition.has_active_command=}"
950 )
951 if binary_package is None or stem is None: 951 ↛ 952line 951 didn't jump to line 952 because the condition on line 951 was never true
952 continue
953 res = stanza_ranges.get(binary_package)
954 if res is None: 954 ↛ 955line 954 didn't jump to line 955 because the condition on line 954 was never true
955 continue
956 declared_arch, diag_range = res
957 if diag_range is None: 957 ↛ 958line 957 didn't jump to line 958 because the condition on line 957 was never true
958 continue
959 path = ppf.path.path
960 likely_typo_of = ppf.expected_path
961 arch_restriction = ppf.architecture_restriction
962 if likely_typo_of is not None:
963 # Handles arch_restriction == 'all' at the same time due to how
964 # the `likely-typo-of` is created
965 lint_state.emit_diagnostic(
966 diag_range,
967 f'The file "{path}" is likely a typo of "{likely_typo_of}"',
968 "warning",
969 "debputy",
970 diagnostic_applies_to_another_file=path,
971 )
972 continue
973 if declared_arch == "all" and arch_restriction is not None: 973 ↛ 974line 973 didn't jump to line 974 because the condition on line 973 was never true
974 lint_state.emit_diagnostic(
975 diag_range,
976 f'The file "{path}" has an architecture restriction but is for an `arch:all` package, so'
977 f" the restriction does not make sense.",
978 "warning",
979 "debputy",
980 diagnostic_applies_to_another_file=path,
981 )
982 elif arch_restriction == "all": 982 ↛ 983line 982 didn't jump to line 983 because the condition on line 982 was never true
983 lint_state.emit_diagnostic(
984 diag_range,
985 f'The file "{path}" has an architecture restriction of `all` rather than a real architecture',
986 "warning",
987 "debputy",
988 diagnostic_applies_to_another_file=path,
989 )
991 if not ppf.definition.has_active_command: 991 ↛ 992line 991 didn't jump to line 992 because the condition on line 991 was never true
992 lint_state.emit_diagnostic(
993 diag_range,
994 f"The file {path} is related to a command that is not active in the dh sequence"
995 " with the current addons",
996 "warning",
997 "debputy",
998 diagnostic_applies_to_another_file=path,
999 )
1000 continue
1002 if not explicit_package and name_segment is not None:
1003 basename = os.path.basename(path)
1004 if basename == ppf.definition.stem:
1005 continue
1006 alt_name = f"{binary_package}.{stem}"
1007 if arch_restriction is not None: 1007 ↛ 1008line 1007 didn't jump to line 1008 because the condition on line 1007 was never true
1008 alt_name = f"{alt_name}.{arch_restriction}"
1009 if ppf.definition.allow_name_segment:
1010 or_alt_name = f' (or maybe "debian/{binary_package}.{basename}")'
1011 else:
1012 or_alt_name = ""
1014 lint_state.emit_diagnostic(
1015 diag_range,
1016 f'Possible typo in "{path}". Consider renaming the file to "debian/{alt_name}"'
1017 f"{or_alt_name} if it is intended for {binary_package}",
1018 "warning",
1019 "debputy",
1020 diagnostic_applies_to_another_file=path,
1021 )
1024@lsp_will_save_wait_until(_DISPATCH_RULE)
1025def _debian_control_on_save_formatting(
1026 ls: "DebputyLanguageServer",
1027 params: WillSaveTextDocumentParams,
1028) -> Sequence[TextEdit] | None:
1029 doc = ls.workspace.get_text_document(params.text_document.uri)
1030 lint_state = ls.lint_state(doc)
1031 return _reformat_debian_control(lint_state)
1034@lsp_cli_reformat_document(_DISPATCH_RULE)
1035def _reformat_debian_control(
1036 lint_state: LintState,
1037) -> Sequence[TextEdit] | None:
1038 return deb822_format_file(lint_state, _DCTRL_FILE_METADATA)
1041@lsp_format_document(_DISPATCH_RULE)
1042def _debian_control_format_file(
1043 ls: "DebputyLanguageServer",
1044 params: DocumentFormattingParams,
1045) -> Sequence[TextEdit] | None:
1046 doc = ls.workspace.get_text_document(params.text_document.uri)
1047 lint_state = ls.lint_state(doc)
1048 return _reformat_debian_control(lint_state)
1051@lsp_semantic_tokens_full(_DISPATCH_RULE)
1052async def _debian_control_semantic_tokens_full(
1053 ls: "DebputyLanguageServer",
1054 request: SemanticTokensParams,
1055) -> SemanticTokens | None:
1056 return await deb822_semantic_tokens_full(
1057 ls,
1058 request,
1059 _DCTRL_FILE_METADATA,
1060 )