diff --git a/scripts/snippets/diagnostics.py b/scripts/snippets/diagnostics.py index a5bd8d529..bcefb26e4 100644 --- a/scripts/snippets/diagnostics.py +++ b/scripts/snippets/diagnostics.py @@ -7,6 +7,8 @@ LocalSourcePolicyIssue, SnippetSourceAttributeIssue, SnippetSourceAttributeRule, + SnippetSourceSafetyIssue, + SnippetSourceSafetyRule, ) LOCAL_SOURCE_REMEDIATION = ( @@ -20,6 +22,10 @@ SnippetSourceAttributeRule.LOCAL_PATH_FORBIDDEN: "SNIP006", SnippetSourceAttributeRule.UNSUPPORTED_SOURCE: "SNIP008", } +SOURCE_SAFETY_CODES = { + SnippetSourceSafetyRule.UNREGISTERED_REPOSITORY: "SNIP009", + SnippetSourceSafetyRule.UNSAFE_PATH: "SNIP010", +} def local_source_policy_diagnostic( @@ -50,3 +56,19 @@ def snippet_source_attribute_diagnostics( ) for issue in issues ) + + +def snippet_source_safety_diagnostics( + path: Path, issues: tuple[SnippetSourceSafetyIssue, ...] +) -> tuple[Diagnostic, ...]: + """Assign stable diagnostic codes to source-safety failures.""" + + return tuple( + Diagnostic( + path=path, + span=issue.span, + code=SOURCE_SAFETY_CODES[issue.rule], + message=issue.message, + ) + for issue in issues + ) diff --git a/tests/test_snippet_source_safety_diagnostics.py b/tests/test_snippet_source_safety_diagnostics.py new file mode 100644 index 000000000..2340e6d55 --- /dev/null +++ b/tests/test_snippet_source_safety_diagnostics.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + +from scripts.snippets.diagnostics import snippet_source_safety_diagnostics +from scripts.snippets.model import ( + SnippetSourceSafetyIssue, + SnippetSourceSafetyRule, + Span, +) + +PATH = Path("docs-main/validator.source.mdx") +SPAN = Span(start=20, end=30, line=7, column=3) + + +@pytest.mark.parametrize( + ("rule", "code"), + [ + (SnippetSourceSafetyRule.UNREGISTERED_REPOSITORY, "SNIP009"), + (SnippetSourceSafetyRule.UNSAFE_PATH, "SNIP010"), + ], +) +def test_maps_source_safety_rule_to_stable_code( + rule: SnippetSourceSafetyRule, code: str +) -> None: + diagnostics = snippet_source_safety_diagnostics( + PATH, + ( + SnippetSourceSafetyIssue( + rule=rule, span=SPAN, message="failure" + ), + ), + ) + + assert diagnostics[0].code == code + assert diagnostics[0].span == SPAN