From 70599644e973d67cf2cb466433845bc58e92b46c Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Tue, 10 Nov 2026 16:01:53 +0100 Subject: [PATCH 01/15] feat(docs): add gldq documentation quality checker Signed-off-by: Eike Waldt On-behalf-of: SAP Assisted-by: Kilo:claude-sonnet-4-6 --- .github/workflows/docs-checks.yml | 26 + Makefile | 12 +- src/gldq.py | 1274 +++++++++++++++++++++++++++++ tests/unit/test_gldq.py | 748 +++++++++++++++++ 4 files changed, 2059 insertions(+), 1 deletion(-) create mode 100755 src/gldq.py create mode 100644 tests/unit/test_gldq.py diff --git a/.github/workflows/docs-checks.yml b/.github/workflows/docs-checks.yml index 754abc0..e02a369 100644 --- a/.github/workflows/docs-checks.yml +++ b/.github/workflows/docs-checks.yml @@ -193,3 +193,29 @@ jobs: run: | export PATH=$PATH:$HOME/go/bin make woke + + documentation-quality: + needs: aggregate + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + repository: gardenlinux/docs + + - name: Download aggregated docs + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: aggregated-docs + path: docs/ + + - name: Set up Python + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # pin@v6.2.0 + with: + python-version: "3.13" + + - name: Install PyYAML + run: pip install pyyaml + + - name: Run Garden Linux Docs Quality + continue-on-error: true + run: python3 src/gldq.py docs/ --format github diff --git a/Makefile b/Makefile index 57c2d91..40372cf 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: help run build preview publish transform aggregate aggregate-repo aggregate-update-repo aggregate-repo-single aggregate-update-repo-single test-aggregate-local clean clean-projects clean-aggregated-git test test-unit test-integration check spelling linkcheck woke glossary glossary-check format check-system-deps +.PHONY: help run build preview publish transform aggregate aggregate-repo aggregate-update-repo aggregate-repo-single aggregate-update-repo-single test-aggregate-local clean clean-projects clean-aggregated-git test test-unit test-integration check spelling linkcheck woke glossary glossary-check docs-check docs-check-strict format check-system-deps help: @echo "Garden Linux Documentation Hub - Available targets:" @@ -20,6 +20,8 @@ help: @echo " spelling - Check spelling with codespell" @echo " linkcheck - Check links with lychee" @echo " woke - Check inclusive language with woke" + @echo " docs-check - Run Garden Linux Docs Quality" + @echo " docs-check-strict - Run Garden Linux Docs Quality with warnings as errors" @echo " glossary - Process glossary links in documentation" @echo " glossary-check - Validate glossary structure" @echo "" @@ -150,6 +152,14 @@ woke: @echo "Running inclusive language checks..." @pnpm run docs:woke +docs-check: + @echo "Running Garden Linux Docs Quality..." + @python3 src/gldq.py docs/ + +docs-check-strict: + @echo "Running Garden Linux Docs Quality (strict)..." + @python3 src/gldq.py docs/ --strict + glossary: @echo "Processing glossary links..." @python3 src/aggregation/auto_glossary.py docs/ diff --git a/src/gldq.py b/src/gldq.py new file mode 100755 index 0000000..fc60a5a --- /dev/null +++ b/src/gldq.py @@ -0,0 +1,1274 @@ +#!/usr/bin/env python3 +"""gldq - Garden Linux Docs Quality Tool. + +Checks documentation for structural quality markers documented in +docs/contributing/documentation/writing_good_docs.md. +""" + +from __future__ import annotations + +import argparse +import fnmatch +import json +import re +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, Iterator, Sequence + +import yaml + +__version__ = "0.1.0" + +ERROR = "error" +WARNING = "warning" + +SKIP_DIRS = { + ".git", + ".mypy_cache", + ".pytest_cache", + ".ruff_cache", + ".venv", + ".vitepress", + "__pycache__", + "_build", + "dist", + "node_modules", + "public", +} +TOP_LEVEL_SECTIONS = {"tutorials", "how-to", "explanation", "reference", "contributing"} +GENERIC_LINK_TEXTS = { + "", + "here", + "click here", + "this link", + "read more", + "learn more", + "see here", +} + +HEADING_RE = re.compile(r"^(#{1,6})[ \t]+(.*)$") +FENCE_OPEN_RE = re.compile(r"^\s*(`{3,}|~{3,})(.*)$") +FENCE_CLOSE_RE = re.compile(r"^\s*(`{3,}|~{3,})[ \t]*$") +MD_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\(([^)]*)\)") +MD_LINK_RE = re.compile(r"(?]*>", re.IGNORECASE) +ALT_ATTR_RE = re.compile( + r"(?]+))", + re.IGNORECASE, +) +EMOJI_RE = re.compile("[\U0001f000-\U0001faff\u2300-\u23ff\u2600-\u27bf\u2b00-\u2bff]") +SUPPRESSION_RE = re.compile( + r"", + re.IGNORECASE, +) +DEFAULT_EXCLUDE_FILE = Path(".gldq-exclude.yml") + + +@dataclass(frozen=True) +class RuleInfo: + """Metadata for a single lint rule.""" + + rule_id: str + severity: str + description: str + + +RULES: dict[str, RuleInfo] = { + "FM-YAML": RuleInfo("FM-YAML", ERROR, "Front matter must be valid YAML"), + "FM-TITLE": RuleInfo( + "FM-TITLE", WARNING, "Front matter must include a non-empty title" + ), + "FM-DESC": RuleInfo( + "FM-DESC", WARNING, "Front matter must include a non-empty description" + ), + "FM-ORDER": RuleInfo( + "FM-ORDER", WARNING, "Front matter order must be an integer when present" + ), + "FM-RELATED": RuleInfo( + "FM-RELATED", ERROR, "related_topics must be a list of existing documents" + ), + "H1-ONE": RuleInfo( + "H1-ONE", WARNING, "Document must have exactly one level-1 heading" + ), + "H1-EMPTY": RuleInfo("H1-EMPTY", ERROR, "Headings must not be empty"), + "HEAD-SKIP": RuleInfo("HEAD-SKIP", WARNING, "Heading levels must not be skipped"), + "CODE-LANG": RuleInfo( + "CODE-LANG", WARNING, "Fenced code blocks must declare a language" + ), + "CODE-BALANCE": RuleInfo( + "CODE-BALANCE", ERROR, "Fenced code blocks must be closed" + ), + "IMG-ALT": RuleInfo("IMG-ALT", ERROR, "Images must have non-empty alt text"), + "LINK-TEXT": RuleInfo("LINK-TEXT", ERROR, "Links must use descriptive link text"), + "EMOJI": RuleInfo("EMOJI", WARNING, "Emoji are not allowed outside code fences"), + "SECTION-INDEX": RuleInfo( + "SECTION-INDEX", + ERROR, + "Section index pages must include ", + ), + "RELATED-TOPICS-END": RuleInfo( + "RELATED-TOPICS-END", + ERROR, + " must be the last content block", + ), + "RELATED-TOPICS-FM": RuleInfo( + "RELATED-TOPICS-FM", + ERROR, + " requires related_topics in front matter", + ), + "RELATED-TOPICS-PRESENT": RuleInfo( + "RELATED-TOPICS-PRESENT", + WARNING, + "Non-index pages should include ", + ), +} + +CHECKS: list[Callable[["Document"], Iterator["Finding"]]] = [] + + +@dataclass(frozen=True) +class Finding: + """A single lint finding.""" + + rule_id: str + severity: str + path: Path + line: int | None + column: int | None + message: str + + @property + def sort_key(self) -> tuple[str, int, int, str]: + return ( + str(self.path), + self.line if self.line is not None else 0, + self.column if self.column is not None else 0, + self.rule_id, + ) + + +@dataclass +class Suppressions: + """Inline suppression directives for one document.""" + + file_rules: set[str] = field(default_factory=set) + from_line: list[tuple[int, set[str]]] = field(default_factory=list) + next_line: dict[int, set[str]] = field(default_factory=dict) + + def suppresses(self, rule_id: str, line: int | None) -> bool: + """Return whether a finding is suppressed.""" + if rule_id in self.file_rules or "*" in self.file_rules: + return True + if line is None: + return False + for start, rules in self.from_line: + if line >= start and (rule_id in rules or "*" in rules): + return True + rules = self.next_line.get(line, set()) + return rule_id in rules or "*" in rules + + +@dataclass(frozen=True) +class ExclusionRule: + """A rule and path pattern pair from an exclude file.""" + + rule_patterns: tuple[str, ...] + path_patterns: tuple[str, ...] + entry: int + + +@dataclass +class ExcludeConfig: + """Rule-aware exclusions loaded from a YAML file.""" + + rules: list[ExclusionRule] = field(default_factory=list) + path: Path | None = None + + def matches(self, rule_id: str, path: Path, root: Path) -> bool: + """Return whether a finding matches any exclusion rule.""" + rule_id = rule_id.upper() + try: + relative = path.relative_to(root).as_posix() + except ValueError: + relative = path.as_posix() + root_relative = f"{root.name}/{relative}" if root.name else relative + full = path.as_posix() + candidates = (relative, root_relative, full) + + for exclusion in self.rules: + if not any( + fnmatch.fnmatchcase(rule_id, pattern.upper()) + for pattern in exclusion.rule_patterns + ): + continue + if any( + _path_matches(candidate, pattern) + for pattern in exclusion.path_patterns + for candidate in candidates + ): + return True + return False + + +@dataclass +class Fence: + """A fenced code block opening.""" + + line: int + info: str + closed: bool = False + + +@dataclass +class Heading: + """An ATX heading.""" + + line: int + level: int + text: str + + +@dataclass +class Document: + """A parsed markdown document.""" + + path: Path + root: Path + relative: Path + lines: list[str] + frontmatter: dict | None + frontmatter_error: str | None + has_frontmatter: bool + body_start: int + no_fence_lines: list[str] + prose_lines: list[str] + headings: list[Heading] + fences: list[Fence] + suppressions: Suppressions + + @property + def is_home(self) -> bool: + return bool(self.frontmatter and self.frontmatter.get("layout") == "home") + + @property + def is_index(self) -> bool: + return self.path.name == "index.md" + + @property + def is_excluded(self) -> bool: + return bool(self.frontmatter and self.frontmatter.get("exclude") is True) + + @property + def no_fence_text(self) -> str: + return "\n".join(self.no_fence_lines) + + +def _first_line(text: str) -> str: + return text.splitlines()[0] if text.splitlines() else str(text) + + +def _parse_frontmatter( + lines: Sequence[str], +) -> tuple[dict | None, str | None, bool, int]: + """Parse front matter and return (data, error, has_frontmatter, body_start).""" + if not lines or lines[0].strip() != "---": + return None, None, False, 0 + + end: int | None = None + for index in range(1, len(lines)): + if lines[index].strip() in ("---", "..."): + end = index + break + + if end is None: + return None, "Missing closing front matter delimiter", True, 0 + + try: + data = yaml.safe_load("\n".join(lines[1:end])) + except yaml.YAMLError as exc: + return None, _first_line(str(exc)), True, end + 1 + + if data is None: + data = {} + if not isinstance(data, dict): + return None, "Front matter must be a YAML mapping", True, end + 1 + return data, None, True, end + 1 + + +def _mask_html_comments(lines: Sequence[str]) -> list[str]: + """Replace HTML comment content with spaces while preserving lines.""" + masked: list[str] = [] + in_comment = False + + for line in lines: + chars = list(line) + index = 0 + while index < len(line): + if in_comment: + end = line.find("-->", index) + if end == -1: + for position in range(index, len(line)): + chars[position] = " " + index = len(line) + else: + for position in range(index, end + 3): + chars[position] = " " + index = end + 3 + in_comment = False + else: + start = line.find("", start + 4) + if end == -1: + for position in range(start, len(line)): + chars[position] = " " + in_comment = True + index = len(line) + else: + for position in range(start, end + 3): + chars[position] = " " + index = end + 3 + masked.append("".join(chars)) + return masked + + +def _mask_inline_code(line: str) -> str: + """Replace inline code spans with spaces.""" + chars = list(line) + index = 0 + length = len(line) + + while index < length: + if line[index] != "`": + index += 1 + continue + + opening_end = index + while opening_end < length and line[opening_end] == "`": + opening_end += 1 + ticks = opening_end - index + + search = opening_end + closed = False + while search < length: + if line[search] != "`": + search += 1 + continue + + closing_end = search + while closing_end < length and line[closing_end] == "`": + closing_end += 1 + + if closing_end - search == ticks: + for position in range(index, closing_end): + chars[position] = " " + index = closing_end + closed = True + break + search = closing_end + + if not closed: + index = opening_end + + return "".join(chars) + + +def _mask_fences( + lines: Sequence[str], body_start: int +) -> tuple[list[str], list[Fence]]: + """Mask fenced code blocks and return opening fences.""" + masked = list(lines) + fences: list[Fence] = [] + fence_char: str | None = None + fence_length = 0 + current: Fence | None = None + + for index in range(body_start, len(lines)): + line = lines[index] + if fence_char is None: + match = FENCE_OPEN_RE.match(line) + if match: + marker = match.group(1) + current = Fence(line=index + 1, info=match.group(2).strip()) + fences.append(current) + fence_char = marker[0] + fence_length = len(marker) + masked[index] = "" + continue + + masked[index] = "" + match = FENCE_CLOSE_RE.match(line) + if match: + marker = match.group(1) + if marker[0] == fence_char and len(marker) >= fence_length: + if current is not None: + current.closed = True + fence_char = None + fence_length = 0 + current = None + + for index in range(0, body_start): + masked[index] = "" + + return masked, fences + + +def _extract_headings(lines: Sequence[str], body_start: int) -> list[Heading]: + """Extract ATX headings from masked lines.""" + headings: list[Heading] = [] + for index in range(body_start, len(lines)): + match = HEADING_RE.match(lines[index]) + if not match: + continue + text = re.sub(r"[ \t]+#+[ \t]*$", "", match.group(2).strip()).strip() + headings.append(Heading(line=index + 1, level=len(match.group(1)), text=text)) + return headings + + +def _parse_suppressions(lines: Sequence[str]) -> Suppressions: + """Parse gldq suppression comments.""" + suppressions = Suppressions() + for index, line in enumerate(lines, start=1): + for match in SUPPRESSION_RE.finditer(line): + kind = match.group(1).lower() + rules = { + value.strip().upper() + for value in re.split(r"[,\s]+", match.group(2).strip()) + if value.strip() + } + if not rules: + continue + if kind == "disable-file": + suppressions.file_rules.update(rules) + elif kind == "disable-next-line": + suppressions.next_line.setdefault(index + 1, set()).update(rules) + else: + suppressions.from_line.append((index, rules)) + suppressions.from_line.sort(key=lambda item: item[0]) + return suppressions + + +def _path_matches(path_text: str, pattern: str) -> bool: + """Match a POSIX path against a wildcard pattern.""" + pattern = pattern.strip().replace("\\", "/") + while pattern.startswith("./"): + pattern = pattern[2:] + if not pattern: + return False + + path_text = path_text.replace("\\", "/") + if fnmatch.fnmatchcase(path_text, pattern): + return True + + prefix = pattern.rstrip("/") + return bool(prefix) and path_text.startswith(prefix + "/") + + +def _string_list(value: object, path: Path, entry: int, field_name: str) -> list[str]: + """Normalize a YAML string or list of strings.""" + if isinstance(value, str): + values = [value] + elif isinstance(value, list) and all(isinstance(item, str) for item in value): + values = value + else: + raise ValueError( + f"{path}: exclude entry {entry} field '{field_name}' " + "must be a string or a list of strings" + ) + + cleaned = [item.strip() for item in values if item.strip()] + if not cleaned: + raise ValueError( + f"{path}: exclude entry {entry} field '{field_name}' must not be empty" + ) + return cleaned + + +def load_exclude_file(path: Path) -> ExcludeConfig: + """Load a rule-aware exclusion file.""" + try: + data = yaml.safe_load(path.read_text(encoding="utf-8")) + except yaml.YAMLError as exc: + raise ValueError(f"{path}: invalid YAML: {_first_line(str(exc))}") from exc + except OSError as exc: + raise ValueError(f"{path}: cannot read exclude file: {exc}") from exc + + if data is None: + data = {} + if not isinstance(data, dict): + raise ValueError(f"{path}: top-level YAML must be a mapping") + + entries = data.get("exclude") + if entries is None: + return ExcludeConfig(path=path) + if not isinstance(entries, list): + raise ValueError(f"{path}: 'exclude' must be a list") + + config = ExcludeConfig(path=path) + for index, entry in enumerate(entries, start=1): + if not isinstance(entry, dict): + raise ValueError(f"{path}: exclude entry {index} must be a mapping") + + rules_value = entry.get("rules") + if rules_value is None: + rules_value = ["*"] + paths_value = entry.get("paths") + if paths_value is None: + raise ValueError(f"{path}: exclude entry {index} is missing 'paths'") + + rule_patterns = _string_list(rules_value, path, index, "rules") + path_patterns = _string_list(paths_value, path, index, "paths") + + for pattern in rule_patterns: + normalized = pattern.upper() + if not any(character in normalized for character in "*?["): + if normalized not in RULES: + raise ValueError( + f"{path}: exclude entry {index} references unknown rule: " + f"{pattern}" + ) + + config.rules.append( + ExclusionRule( + rule_patterns=tuple(pattern.upper() for pattern in rule_patterns), + path_patterns=tuple(path_patterns), + entry=index, + ) + ) + + return config + + +def parse_document(path: Path, root: Path) -> Document: + """Parse a markdown file into a Document.""" + text = path.read_text(encoding="utf-8") + lines = text.splitlines() + frontmatter, frontmatter_error, has_frontmatter, body_start = _parse_frontmatter( + lines + ) + + comment_masked = _mask_html_comments(lines) + no_fence_lines, fences = _mask_fences(comment_masked, body_start) + prose_lines = [ + "" if index < body_start else _mask_inline_code(line) + for index, line in enumerate(no_fence_lines) + ] + headings = _extract_headings(no_fence_lines, body_start) + + return Document( + path=path, + root=root, + relative=path.relative_to(root), + lines=lines, + frontmatter=frontmatter, + frontmatter_error=frontmatter_error, + has_frontmatter=has_frontmatter, + body_start=body_start, + no_fence_lines=no_fence_lines, + prose_lines=prose_lines, + headings=headings, + fences=fences, + suppressions=_parse_suppressions(lines), + ) + + +def _resolve_target(root: Path, reference: str) -> bool: + """Resolve a related_topics reference against the docs root.""" + reference = reference.strip() + if not reference: + return False + if re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*:", reference) or reference.startswith("//"): + return True + + reference = reference.split("#", 1)[0].split("?", 1)[0].strip() + if not reference: + return False + + reference = reference.lstrip("/") + if not reference or reference == ".": + return (root / "index.md").is_file() + if reference.endswith("/"): + return (root / reference / "index.md").is_file() + + candidates = [root / reference] + if not reference.endswith(".md"): + candidates.append(root / f"{reference}.md") + candidates.append(root / reference / "index.md") + return any(candidate.is_file() for candidate in candidates) + + +def _finding( + document: Document, + rule_id: str, + line: int | None, + column: int | None, + message: str, +) -> Finding: + rule = RULES[rule_id] + return Finding( + rule_id=rule_id, + severity=rule.severity, + path=document.path, + line=line, + column=column, + message=message, + ) + + +def check_frontmatter(document: Document) -> Iterator[Finding]: + """Check front matter structure and related topics.""" + frontmatter = document.frontmatter or {} + + if document.frontmatter_error: + yield _finding( + document, + "FM-YAML", + 1, + 1, + f"Invalid front matter: {document.frontmatter_error}", + ) + + if document.is_home: + return + + title = frontmatter.get("title") + if not isinstance(title, str) or not title.strip(): + yield _finding( + document, "FM-TITLE", 1, 1, "Missing or empty title in front matter" + ) + + description = frontmatter.get("description") + if not isinstance(description, str) or not description.strip(): + yield _finding( + document, + "FM-DESC", + 1, + 1, + "Missing or empty description in front matter", + ) + + if "order" in frontmatter: + order = frontmatter["order"] + if isinstance(order, bool) or not isinstance(order, int): + yield _finding( + document, + "FM-ORDER", + 1, + 1, + "Front matter 'order' must be an integer", + ) + + if "related_topics" in frontmatter: + related_topics = frontmatter["related_topics"] + if not isinstance(related_topics, list): + yield _finding( + document, + "FM-RELATED", + 1, + 1, + "Front matter 'related_topics' must be a list", + ) + else: + for reference in related_topics: + if not isinstance(reference, str) or not reference.strip(): + yield _finding( + document, + "FM-RELATED", + 1, + 1, + "Front matter 'related_topics' entries must be non-empty strings", + ) + continue + if not _resolve_target(document.root, reference): + yield _finding( + document, + "FM-RELATED", + 1, + 1, + f"related_topics target not found: {reference}", + ) + + +def check_headings(document: Document) -> Iterator[Finding]: + """Check heading structure.""" + level_one = [heading for heading in document.headings if heading.level == 1] + + for heading in document.headings: + if not heading.text: + yield _finding(document, "H1-EMPTY", heading.line, 1, "Heading is empty") + + if not document.is_home: + if not level_one: + yield _finding(document, "H1-ONE", 1, 1, "Document has no level-1 heading") + elif len(level_one) > 1: + for heading in level_one[1:]: + yield _finding( + document, + "H1-ONE", + heading.line, + 1, + "Document has multiple level-1 headings", + ) + + previous: int | None = None + for heading in document.headings: + if previous is not None and heading.level > previous + 1: + yield _finding( + document, + "HEAD-SKIP", + heading.line, + 1, + f"Heading level jumps from {previous} to {heading.level}", + ) + previous = heading.level + + +def check_code(document: Document) -> Iterator[Finding]: + """Check fenced code block language and balance.""" + for fence in document.fences: + if not fence.info: + yield _finding( + document, + "CODE-LANG", + fence.line, + 1, + "Fenced code block has no language", + ) + if not fence.closed: + yield _finding( + document, + "CODE-BALANCE", + fence.line, + 1, + "Fenced code block is not closed", + ) + + +def check_images(document: Document) -> Iterator[Finding]: + """Check markdown and HTML image alt text.""" + for index in range(document.body_start, len(document.no_fence_lines)): + line = document.no_fence_lines[index] + line_number = index + 1 + + for match in MD_IMAGE_RE.finditer(line): + if document.prose_lines[index][match.start()] != "!": + continue + if not match.group(1).strip(): + yield _finding( + document, + "IMG-ALT", + line_number, + match.start() + 1, + "Image is missing alt text", + ) + + for match in HTML_IMG_RE.finditer(line): + if document.prose_lines[index][match.start()] != "<": + continue + alt_match = ALT_ATTR_RE.search(match.group(0)) + if alt_match is None: + yield _finding( + document, + "IMG-ALT", + line_number, + match.start() + 1, + "HTML image is missing alt text", + ) + continue + value = next( + (group for group in alt_match.groups() if group is not None), "" + ) + if not value.strip(): + yield _finding( + document, + "IMG-ALT", + line_number, + match.start() + 1, + "HTML image has empty alt text", + ) + + +def _normalize_link_text(text: str) -> str: + text = re.sub(r"`+", "", text) + text = re.sub(r"[*_~]", "", text) + text = " ".join(text.split()).strip().lower() + return text.strip(" .,:;!?()[]{}<>\"'") + + +def check_links(document: Document) -> Iterator[Finding]: + """Check for missing or generic link text.""" + for index in range(document.body_start, len(document.no_fence_lines)): + line = document.no_fence_lines[index] + for match in MD_LINK_RE.finditer(line): + if document.prose_lines[index][match.start()] != "[": + continue + text = match.group(1) + if _normalize_link_text(text) in GENERIC_LINK_TEXTS: + yield _finding( + document, + "LINK-TEXT", + index + 1, + match.start() + 1, + f"Link text is not descriptive: {text!r}", + ) + + +def check_emoji(document: Document) -> Iterator[Finding]: + """Check for emoji outside code fences and front matter.""" + for index in range(document.body_start, len(document.prose_lines)): + match = EMOJI_RE.search(document.prose_lines[index]) + if match: + yield _finding( + document, + "EMOJI", + index + 1, + match.start() + 1, + f"Emoji outside code fence: {match.group(0)}", + ) + + +def _first_line_with(lines: Sequence[str], needle: str) -> int | None: + for index, line in enumerate(lines): + if needle in line: + return index + 1 + return None + + +def _last_line_with(lines: Sequence[str], needle: str) -> int | None: + for index in range(len(lines) - 1, -1, -1): + if needle in lines[index]: + return index + 1 + return None + + +def check_components(document: Document) -> Iterator[Finding]: + """Check VitePress component requirements.""" + text = document.no_fence_text + has_related_topics = "", + ) + + if has_related_topics: + frontmatter = document.frontmatter or {} + related_line = _last_line_with(document.no_fence_lines, " requires related_topics in front matter", + ) + + if related_line is not None: + line_index = related_line - 1 + match = re.search( + r"]*>", document.no_fence_lines[line_index] + ) + tail = ( + document.no_fence_lines[line_index][match.end() :].strip() + if match + else "" + ) + if tail: + yield _finding( + document, + "RELATED-TOPICS-END", + related_line, + 1, + " must be the last content block", + ) + else: + for index in range(line_index + 1, len(document.no_fence_lines)): + if document.no_fence_lines[index].strip(): + yield _finding( + document, + "RELATED-TOPICS-END", + related_line, + 1, + " must be the last content block", + ) + break + + if ( + not document.is_index + and not document.is_home + and not document.is_excluded + and not has_related_topics + ): + yield _finding( + document, + "RELATED-TOPICS-PRESENT", + 1, + 1, + "Content page is missing ", + ) + + +CHECKS.extend( + [ + check_frontmatter, + check_headings, + check_code, + check_images, + check_links, + check_emoji, + check_components, + ] +) + + +def _should_skip(file_path: Path, root: Path, excludes: Sequence[str]) -> bool: + try: + relative = file_path.relative_to(root) + except ValueError: + relative = file_path + + if any(part in SKIP_DIRS for part in relative.parts): + return True + if file_path.name.startswith("_"): + return True + + relative_text = relative.as_posix() + full_text = file_path.as_posix() + for pattern in excludes: + cleaned = pattern.strip().lstrip("./") + if not cleaned: + continue + if fnmatch.fnmatch(relative_text, cleaned): + return True + if fnmatch.fnmatch(full_text, cleaned): + return True + if relative_text.startswith(cleaned.rstrip("/") + "/"): + return True + return False + + +def _infer_root(path: Path) -> Path: + """Infer the documentation root for a file or directory path.""" + candidate = path if path.is_dir() else path.parent + for parent in (candidate, *candidate.parents): + if parent.name == "docs": + return parent + return candidate + + +def iter_documents( + paths: Sequence[Path], excludes: Sequence[str] +) -> Iterator[Document]: + """Yield parsed documents for all markdown files under the given paths.""" + for path in paths: + root = _infer_root(path) + if path.is_file(): + if path.suffix.lower() == ".md": + yield parse_document(path, root) + continue + + for file_path in sorted(path.rglob("*.md")): + if _should_skip(file_path, root, excludes): + continue + yield parse_document(file_path, root) + + +def collect_findings( + documents: Sequence[Document], + disabled: set[str], + exclusions: ExcludeConfig | None = None, +) -> tuple[list[Finding], int, int]: + """Run all checks and return findings, suppressed, and excluded counts.""" + findings: list[Finding] = [] + suppressed = 0 + excluded = 0 + + for document in documents: + for check in CHECKS: + for finding in check(document): + if finding.rule_id in disabled or document.suppressions.suppresses( + finding.rule_id, finding.line + ): + suppressed += 1 + continue + if exclusions is not None and exclusions.matches( + finding.rule_id, document.path, document.root + ): + excluded += 1 + continue + findings.append(finding) + + findings.sort(key=lambda finding: finding.sort_key) + return findings, suppressed, excluded + + +def _counts(findings: Sequence[Finding]) -> tuple[int, int]: + errors = sum(1 for finding in findings if finding.severity == ERROR) + warnings = sum(1 for finding in findings if finding.severity == WARNING) + return errors, warnings + + +def _exclude_label(exclude_file: Path | None) -> str: + return exclude_file.as_posix() if exclude_file is not None else "exclude file" + + +def format_text( + findings: Sequence[Finding], + suppressed: int, + excluded: int, + file_count: int, + exclude_file: Path | None = None, +) -> str: + """Format findings as human-readable text.""" + lines: list[str] = [] + for finding in findings: + location = str(finding.path) + if finding.line is not None: + location += f":{finding.line}" + if finding.column is not None: + location += f":{finding.column}" + lines.append( + f"{location}: {finding.severity}: [{finding.rule_id}] {finding.message}" + ) + + errors, warnings = _counts(findings) + if lines: + lines.append("") + lines.append( + f"gldq: {errors} error(s), {warnings} warning(s) in {file_count} file(s)" + ) + if suppressed: + lines.append(f"gldq: {suppressed} finding(s) suppressed inline") + if excluded: + lines.append( + f"gldq: {excluded} finding(s) excluded by {_exclude_label(exclude_file)}" + ) + return "\n".join(lines) + + +def format_json( + findings: Sequence[Finding], + suppressed: int, + excluded: int, + file_count: int, + exclude_file: Path | None = None, +) -> str: + """Format findings as JSON.""" + errors, warnings = _counts(findings) + payload = { + "tool": "gldq", + "name": "Garden Linux Docs Quality", + "version": __version__, + "summary": { + "files": file_count, + "errors": errors, + "warnings": warnings, + "suppressed": suppressed, + "excluded": excluded, + "exclude_file": ( + exclude_file.as_posix() if exclude_file is not None else None + ), + }, + "findings": [ + { + "path": str(finding.path), + "line": finding.line, + "column": finding.column, + "severity": finding.severity, + "rule": finding.rule_id, + "message": finding.message, + } + for finding in findings + ], + } + return json.dumps(payload, indent=2) + + +def _escape_github(text: str) -> str: + return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + + +def format_github( + findings: Sequence[Finding], + suppressed: int, + excluded: int, + file_count: int, + exclude_file: Path | None = None, +) -> str: + """Format findings as GitHub Actions workflow annotations.""" + lines: list[str] = [] + for finding in findings: + kind = "error" if finding.severity == ERROR else "warning" + properties = [f"file={finding.path}"] + if finding.line is not None: + properties.append(f"line={finding.line}") + if finding.column is not None: + properties.append(f"col={finding.column}") + message = _escape_github(f"[{finding.rule_id}] {finding.message}") + lines.append(f"::{kind} {','.join(properties)}::{message}") + + if not lines: + lines.append("::notice title=gldq::No documentation quality findings") + + errors, warnings = _counts(findings) + summary = ( + "::notice title=gldq::" + f"{errors} error(s), {warnings} warning(s) in {file_count} file(s)" + ) + if suppressed: + summary += f", {suppressed} suppressed inline" + if excluded: + summary += f", {excluded} excluded by {_exclude_label(exclude_file)}" + lines.append(summary) + return "\n".join(lines) + + +def print_rules() -> None: + """Print the rule registry.""" + print(f"{'RULE':22} {'SEVERITY':8} DESCRIPTION") + for rule in sorted(RULES.values(), key=lambda item: item.rule_id): + print(f"{rule.rule_id:22} {rule.severity:8} {rule.description}") + + +def build_parser() -> argparse.ArgumentParser: + """Build the command-line parser.""" + parser = argparse.ArgumentParser( + prog="gldq", + description="Garden Linux Docs Quality", + ) + parser.add_argument( + "paths", + nargs="*", + default=["docs"], + help="Files or directories to check (default: docs)", + ) + parser.add_argument( + "--format", + choices=("text", "json", "github"), + default="text", + help="Output format (default: text)", + ) + parser.add_argument( + "--strict", + action="store_true", + help="Treat warnings as failures", + ) + parser.add_argument( + "--disable", + action="append", + default=[], + metavar="RULE", + help="Disable a rule (repeatable)", + ) + parser.add_argument( + "--exclude", + action="append", + default=[], + metavar="GLOB", + help="Exclude matching paths (repeatable)", + ) + exclude_group = parser.add_mutually_exclusive_group() + exclude_group.add_argument( + "--exclude-file", + metavar="PATH", + help="Use a custom rule-aware exclude file", + ) + exclude_group.add_argument( + "--no-exclude-file", + action="store_true", + help="Do not auto-load .gldq-exclude.yml", + ) + parser.add_argument( + "--list-rules", + action="store_true", + help="List available rules and exit", + ) + parser.add_argument( + "--version", + action="version", + version=f"%(prog)s {__version__}", + ) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + """Run gldq and return an exit code.""" + parser = build_parser() + args = parser.parse_args(argv) + + if args.list_rules: + print_rules() + return 0 + + paths = [Path(value) for value in args.paths] + missing = [path for path in paths if not path.exists()] + if missing: + for path in missing: + print(f"gldq: path not found: {path}", file=sys.stderr) + return 2 + + disabled = {rule.strip().upper() for rule in args.disable if rule.strip()} + unknown = disabled - set(RULES) + if unknown: + print( + f"gldq: unknown rule(s): {', '.join(sorted(unknown))}", + file=sys.stderr, + ) + return 2 + + exclude_file: Path | None = None + exclusions = ExcludeConfig() + if args.exclude_file: + exclude_file = Path(args.exclude_file) + if not exclude_file.is_file(): + print( + f"gldq: exclude file not found: {exclude_file}", + file=sys.stderr, + ) + return 2 + elif not args.no_exclude_file and DEFAULT_EXCLUDE_FILE.is_file(): + exclude_file = DEFAULT_EXCLUDE_FILE + + if exclude_file is not None: + try: + exclusions = load_exclude_file(exclude_file) + except ValueError as exc: + print(f"gldq: {exc}", file=sys.stderr) + return 2 + + try: + documents = list(iter_documents(paths, args.exclude)) + except OSError as exc: + print(f"gldq: {exc}", file=sys.stderr) + return 2 + + findings, suppressed, excluded = collect_findings(documents, disabled, exclusions) + file_count = len(documents) + + if args.format == "json": + print(format_json(findings, suppressed, excluded, file_count, exclude_file)) + elif args.format == "github": + print(format_github(findings, suppressed, excluded, file_count, exclude_file)) + else: + print(format_text(findings, suppressed, excluded, file_count, exclude_file)) + + errors, warnings = _counts(findings) + if errors or (args.strict and warnings): + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/unit/test_gldq.py b/tests/unit/test_gldq.py new file mode 100644 index 0000000..8dacb25 --- /dev/null +++ b/tests/unit/test_gldq.py @@ -0,0 +1,748 @@ +"""Unit tests for the Garden Linux Docs Quality Tool.""" + +import json +from pathlib import Path + +import gldq + + +def write_doc(tmp_path: Path, relative: str, content: str) -> Path: + """Write a markdown document below tmp_path.""" + path = tmp_path / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + return path + + +def make_doc( + body: str, frontmatter: str = "title: Page\ndescription: A test page\n" +) -> str: + """Build a markdown document with default valid front matter.""" + return f"---\n{frontmatter}---\n\n{body}" + + +def make_release_note(body: str = "Chart πŸ“Š\n") -> str: + """Build a valid release note document with a trailing RelatedTopics.""" + return make_doc( + f"# Release\n\n{body}\n\n", + frontmatter="title: Release\ndescription: Release notes\nrelated_topics: []\n", + ) + + +def find( + tmp_path: Path, + content: str, + relative: str = "docs/page.md", + root_relative: str = "docs", +) -> list[gldq.Finding]: + """Parse one document and return its unsuppressed findings.""" + path = write_doc(tmp_path, relative, content) + document = gldq.parse_document(path, tmp_path / root_relative) + findings, _, _ = gldq.collect_findings([document], set()) + return findings + + +def rule_ids(findings: list[gldq.Finding]) -> list[str]: + """Return the rule IDs from findings.""" + return [finding.rule_id for finding in findings] + + +class TestValidDocuments: + def test_valid_index_page_has_no_findings(self, tmp_path): + content = make_doc( + "# Guide\n\n" + "Text with a [descriptive link](https://example.com).\n\n" + "```shell\n" + "echo hello\n" + "```\n\n" + "![diagram](diagram.png)\n" + ) + findings = find(tmp_path, content, relative="docs/guide/index.md") + assert findings == [] + + def test_home_page_skips_title_and_h1_rules(self, tmp_path): + content = ( + "---\n" "layout: home\n" "hero:\n" " name: Test\n" "---\n\n" "Welcome.\n" + ) + findings = find(tmp_path, content) + ids = rule_ids(findings) + assert "FM-TITLE" not in ids + assert "FM-DESC" not in ids + assert "H1-ONE" not in ids + assert "RELATED-TOPICS-PRESENT" not in ids + + +class TestFrontmatter: + def test_missing_title_and_description_warn(self, tmp_path): + findings = find(tmp_path, "---\norder: 1\n---\n\n# Page\n") + ids = rule_ids(findings) + assert "FM-TITLE" in ids + assert "FM-DESC" in ids + + def test_invalid_yaml_is_an_error(self, tmp_path): + findings = find(tmp_path, "---\ntitle: [broken\n---\n\n# Page\n") + assert "FM-YAML" in rule_ids(findings) + + def test_unclosed_frontmatter_is_an_error(self, tmp_path): + findings = find(tmp_path, "---\ntitle: Page\n\n# Page\n") + assert "FM-YAML" in rule_ids(findings) + + def test_non_mapping_frontmatter_is_an_error(self, tmp_path): + findings = find(tmp_path, "---\n- one\n- two\n---\n\n# Page\n") + assert "FM-YAML" in rule_ids(findings) + + def test_non_integer_order_warns(self, tmp_path): + findings = find( + tmp_path, + make_doc( + "# Page\n", frontmatter="title: Page\ndescription: Page\norder: first\n" + ), + ) + assert "FM-ORDER" in rule_ids(findings) + + def test_related_topics_existing_targets_pass(self, tmp_path): + write_doc(tmp_path, "docs/target.md", make_doc("# Target\n")) + write_doc(tmp_path, "docs/dir/index.md", make_doc("# Directory\n")) + content = make_doc( + "# Page\n", + frontmatter=( + "title: Page\n" + "description: Page\n" + "related_topics:\n" + " - /target.md\n" + " - target\n" + " - /dir/\n" + " - dir/index.md\n" + " - https://example.com\n" + " - mailto:docs@example.com\n" + ), + ) + findings = find(tmp_path, content) + assert "FM-RELATED" not in rule_ids(findings) + + def test_related_topics_missing_target_is_an_error(self, tmp_path): + content = make_doc( + "# Page\n", + frontmatter=( + "title: Page\ndescription: Page\nrelated_topics:\n - /missing.md\n" + ), + ) + findings = find(tmp_path, content) + assert "FM-RELATED" in rule_ids(findings) + + def test_related_topics_must_be_a_list(self, tmp_path): + content = make_doc( + "# Page\n", + frontmatter="title: Page\ndescription: Page\nrelated_topics: target.md\n", + ) + findings = find(tmp_path, content) + assert "FM-RELATED" in rule_ids(findings) + + +class TestHeadings: + def test_missing_h1_warns(self, tmp_path): + findings = find(tmp_path, make_doc("## No level one\n")) + assert "H1-ONE" in rule_ids(findings) + + def test_multiple_h1_warn(self, tmp_path): + findings = find(tmp_path, make_doc("# One\n\n# Two\n")) + assert rule_ids(findings).count("H1-ONE") == 1 + + def test_empty_heading_is_an_error(self, tmp_path): + findings = find(tmp_path, make_doc("# \n")) + assert "H1-EMPTY" in rule_ids(findings) + + def test_skipped_heading_level_warns(self, tmp_path): + findings = find(tmp_path, make_doc("# Page\n\n### Skipped\n")) + assert "HEAD-SKIP" in rule_ids(findings) + + +class TestCodeBlocks: + def test_unclosed_fence_is_an_error(self, tmp_path): + findings = find(tmp_path, make_doc("# Page\n\n```shell\necho hello\n")) + assert "CODE-BALANCE" in rule_ids(findings) + + def test_fence_without_language_warns(self, tmp_path): + findings = find(tmp_path, make_doc("# Page\n\n```\necho hello\n```\n")) + assert rule_ids(findings).count("CODE-LANG") == 1 + + def test_indented_fence_is_detected(self, tmp_path): + content = make_doc( + "# Page\n\n" + "- item\n\n" + " ```shell\n" + " echo hello\n" + " ```\n" + ) + assert "CODE-BALANCE" not in rule_ids(find(tmp_path, content)) + + def test_markdown_inside_fence_is_ignored(self, tmp_path): + content = make_doc( + "# Page\n\n" + "```markdown\n" + "# Not a heading\n" + "[click here](https://example.com)\n" + "![](missing.png)\n" + "βœ…\n" + "```\n" + ) + ids = rule_ids(find(tmp_path, content)) + assert "HEAD-SKIP" not in ids + assert "LINK-TEXT" not in ids + assert "IMG-ALT" not in ids + assert "EMOJI" not in ids + + +class TestImages: + def test_missing_alt_text_is_an_error(self, tmp_path): + content = make_doc( + "# Page\n\n" + "![](diagram.png)\n\n" + '\n\n' + '\n' + ) + findings = find(tmp_path, content) + assert rule_ids(findings).count("IMG-ALT") == 3 + + def test_valid_alt_text_passes(self, tmp_path): + content = make_doc( + "# Page\n\n" + "![diagram](diagram.png)\n\n" + 'A diagram\n' + ) + assert "IMG-ALT" not in rule_ids(find(tmp_path, content)) + + def test_data_alt_is_not_a_valid_alt_attribute(self, tmp_path): + findings = find( + tmp_path, + make_doc("# Page\n\n" '\n'), + ) + assert "IMG-ALT" in rule_ids(findings) + + def test_inline_code_image_is_ignored(self, tmp_path): + findings = find(tmp_path, make_doc("# Page\n\n`![](missing.png)`\n")) + assert "IMG-ALT" not in rule_ids(findings) + + +class TestLinks: + def test_generic_link_text_is_an_error(self, tmp_path): + findings = find( + tmp_path, + make_doc("# Page\n\n[click here](https://example.com)\n"), + ) + assert "LINK-TEXT" in rule_ids(findings) + + def test_empty_link_text_is_an_error(self, tmp_path): + findings = find(tmp_path, make_doc("# Page\n\n[](https://example.com)\n")) + assert "LINK-TEXT" in rule_ids(findings) + + def test_descriptive_link_text_passes(self, tmp_path): + findings = find( + tmp_path, + make_doc("# Page\n\n[Garden Linux releases](https://example.com)\n"), + ) + assert "LINK-TEXT" not in rule_ids(findings) + + def test_inline_code_link_is_ignored(self, tmp_path): + findings = find( + tmp_path, + make_doc("# Page\n\n`[click here](https://example.com)`\n"), + ) + assert "LINK-TEXT" not in rule_ids(findings) + + +class TestEmoji: + def test_emoji_outside_code_warns(self, tmp_path): + findings = find(tmp_path, make_doc("# Page\n\nAll good βœ…\n")) + assert "EMOJI" in rule_ids(findings) + + def test_emoji_in_code_fence_is_ignored(self, tmp_path): + findings = find(tmp_path, make_doc("# Page\n\n```text\nβœ…\n```\n")) + assert "EMOJI" not in rule_ids(findings) + + def test_emoji_in_inline_code_is_ignored(self, tmp_path): + findings = find(tmp_path, make_doc("# Page\n\n`βœ…`\n")) + assert "EMOJI" not in rule_ids(findings) + + def test_emoji_in_frontmatter_is_ignored(self, tmp_path): + content = make_doc( + "# Page\n", + frontmatter="title: Page\ndescription: A page with βœ…\n", + ) + findings = find(tmp_path, content) + assert "EMOJI" not in rule_ids(findings) + + def test_disable_next_line(self, tmp_path): + content = make_doc("# Page\n\n\nβœ…\n") + assert "EMOJI" not in rule_ids(find(tmp_path, content)) + + def test_disable_from_line(self, tmp_path): + content = make_doc("# Page\n\n\nβœ…\n") + assert "EMOJI" not in rule_ids(find(tmp_path, content)) + + def test_disable_file(self, tmp_path): + content = make_doc("# Page\n\n\nβœ…\n") + assert "EMOJI" not in rule_ids(find(tmp_path, content)) + + +class TestComponents: + def test_section_index_requires_component(self, tmp_path): + findings = find( + tmp_path, + make_doc("# Explanation\n"), + relative="docs/explanation/index.md", + ) + assert "SECTION-INDEX" in rule_ids(findings) + + def test_section_index_with_component_passes(self, tmp_path): + findings = find( + tmp_path, + make_doc("# Explanation\n\n\n"), + relative="docs/explanation/index.md", + ) + assert "SECTION-INDEX" not in rule_ids(findings) + + def test_related_topics_requires_frontmatter(self, tmp_path): + findings = find(tmp_path, make_doc("# Page\n\n\n")) + assert "RELATED-TOPICS-FM" in rule_ids(findings) + + def test_related_topics_must_be_last(self, tmp_path): + content = make_doc( + "# Page\n\n\n\n## After\n", + frontmatter="title: Page\ndescription: Page\nrelated_topics: []\n", + ) + findings = find(tmp_path, content) + assert "RELATED-TOPICS-END" in rule_ids(findings) + + def test_related_topics_last_passes(self, tmp_path): + content = make_doc( + "# Page\n\n\n", + frontmatter="title: Page\ndescription: Page\nrelated_topics: []\n", + ) + findings = find(tmp_path, content) + assert "RELATED-TOPICS-END" not in rule_ids(findings) + + def test_related_topics_present_warns_on_content_pages(self, tmp_path): + findings = find(tmp_path, make_doc("# Page\n")) + assert "RELATED-TOPICS-PRESENT" in rule_ids(findings) + + def test_related_topics_present_skips_index_pages(self, tmp_path): + findings = find( + tmp_path, + make_doc("# Page\n"), + relative="docs/guide/index.md", + ) + assert "RELATED-TOPICS-PRESENT" not in rule_ids(findings) + + def test_related_topics_present_skips_excluded_pages(self, tmp_path): + content = make_doc( + "# Redirect\n", + frontmatter="title: Redirect\ndescription: Redirect\nexclude: true\n", + ) + findings = find(tmp_path, content) + assert "RELATED-TOPICS-PRESENT" not in rule_ids(findings) + + def test_excluded_pages_still_run_other_rules(self, tmp_path): + content = make_doc( + "# Redirect\n\nChart πŸ“Š\n", + frontmatter="title: Redirect\ndescription: Redirect\nexclude: true\n", + ) + findings = find(tmp_path, content) + assert "EMOJI" in rule_ids(findings) + + +class TestFalsePositives: + def test_markdown_in_inline_code_is_ignored(self, tmp_path): + content = make_doc( + "# Page\n\n" + "`# Not a heading` and `[click here](https://example.com)` " + "and `![](missing.png)` and `βœ…`\n" + ) + ids = rule_ids(find(tmp_path, content)) + assert "LINK-TEXT" not in ids + assert "IMG-ALT" not in ids + assert "EMOJI" not in ids + assert "HEAD-SKIP" not in ids + + def test_markdown_in_frontmatter_is_ignored(self, tmp_path): + content = make_doc( + "# Page\n", + frontmatter=( + "title: Page\n" + 'description: "Use [click here](https://example.com), ' + '![](missing.png), and βœ…"\n' + ), + ) + ids = rule_ids(find(tmp_path, content)) + assert "LINK-TEXT" not in ids + assert "IMG-ALT" not in ids + assert "EMOJI" not in ids + + +class TestDiscovery: + def test_partials_and_excluded_paths_are_skipped(self, tmp_path): + write_doc(tmp_path, "docs/keep.md", make_doc("# Keep\n")) + write_doc(tmp_path, "docs/_partial.md", make_doc("# Partial\n")) + write_doc(tmp_path, "docs/skip/ignored.md", make_doc("# Ignored\n")) + + documents = list(gldq.iter_documents([tmp_path / "docs"], [])) + names = {document.path.name for document in documents} + assert "keep.md" in names + assert "_partial.md" not in names + assert "ignored.md" in names + + documents = list(gldq.iter_documents([tmp_path / "docs"], ["skip/**"])) + names = {document.path.name for document in documents} + assert "ignored.md" not in names + + +class TestExcludeFile: + def write_exclude( + self, tmp_path: Path, content: str, name: str = ".gldq-exclude.yml" + ) -> Path: + path = tmp_path / name + path.write_text(content, encoding="utf-8") + return path + + def test_default_exclude_file_excludes_release_note_emoji( + self, tmp_path, monkeypatch, capsys + ): + self.write_exclude( + tmp_path, + "exclude:\n" + ' - rules: ["EMOJI"]\n' + " paths:\n" + ' - "docs/reference/releases/release-notes/**"\n', + ) + write_doc( + tmp_path, + "docs/reference/releases/release-notes/archived/2150-6-0.md", + make_release_note(), + ) + monkeypatch.chdir(tmp_path) + + assert gldq.main(["docs", "--strict", "--format", "json"]) == 0 + payload = json.loads(capsys.readouterr().out) + assert payload["summary"]["excluded"] == 1 + assert payload["summary"]["warnings"] == 0 + assert payload["findings"] == [] + + def test_exclusion_is_scoped_to_rule_and_path(self, tmp_path, monkeypatch, capsys): + self.write_exclude( + tmp_path, + "exclude:\n" + ' - rules: ["EMOJI"]\n' + ' paths: ["docs/reference/releases/release-notes/**"]\n', + ) + write_doc( + tmp_path, + "docs/reference/releases/release-notes/archived/release.md", + make_release_note("Chart πŸ“Š and [click here](https://example.com)\n"), + ) + write_doc( + tmp_path, + "docs/guide/index.md", + make_doc("# Guide\n\nChart πŸ“Š\n"), + ) + monkeypatch.chdir(tmp_path) + + assert gldq.main(["docs", "--format", "json"]) == 1 + payload = json.loads(capsys.readouterr().out) + assert payload["summary"]["excluded"] == 1 + + findings_by_path: dict[str, list[str]] = {} + for finding in payload["findings"]: + findings_by_path.setdefault(finding["path"], []).append(finding["rule"]) + + release_rules = next( + rules for path, rules in findings_by_path.items() if "release-notes" in path + ) + guide_rules = next( + rules for path, rules in findings_by_path.items() if "guide" in path + ) + assert "EMOJI" not in release_rules + assert "LINK-TEXT" in release_rules + assert "EMOJI" in guide_rules + + def test_rule_wildcard_and_relative_path(self, tmp_path): + path = self.write_exclude( + tmp_path, + "exclude:\n" + ' - rules: ["CODE-*"]\n' + ' paths: ["reference/features/**"]\n', + name="wildcards.yml", + ) + config = gldq.load_exclude_file(path) + root = Path("docs") + document = Path("docs/reference/features/a.md") + + assert config.matches("CODE-LANG", document, root) + assert config.matches("CODE-BALANCE", document, root) + assert not config.matches("EMOJI", document, root) + assert not config.matches("CODE-LANG", Path("docs/reference/other/a.md"), root) + + def test_star_and_omitted_rules_match_all(self, tmp_path): + path = self.write_exclude( + tmp_path, + "exclude:\n" + ' - rules: ["*"]\n' + ' paths: ["reference/**"]\n' + ' - paths: ["tutorials/**"]\n', + name="all.yml", + ) + config = gldq.load_exclude_file(path) + root = Path("docs") + + assert config.matches("EMOJI", Path("docs/reference/a.md"), root) + assert config.matches("FM-DESC", Path("docs/tutorials/a.md"), root) + + def test_path_patterns_match_relative_and_full(self, tmp_path): + full = self.write_exclude( + tmp_path, + "exclude:\n" + ' - rules: ["EMOJI"]\n' + ' paths: ["docs/reference/releases/release-notes/**"]\n', + name="full.yml", + ) + relative = self.write_exclude( + tmp_path, + "exclude:\n" + ' - rules: ["EMOJI"]\n' + ' paths: ["reference/releases/release-notes/**"]\n', + name="relative.yml", + ) + root = Path("docs") + document = Path("docs/reference/releases/release-notes/a.md") + + assert gldq.load_exclude_file(full).matches("EMOJI", document, root) + assert gldq.load_exclude_file(relative).matches("EMOJI", document, root) + + def test_directory_prefix_pattern_matches(self, tmp_path): + path = self.write_exclude( + tmp_path, + "exclude:\n" ' - rules: ["EMOJI"]\n' ' paths: ["reference/features"]\n', + name="prefix.yml", + ) + config = gldq.load_exclude_file(path) + assert config.matches( + "EMOJI", + Path("docs/reference/features/a.md"), + Path("docs"), + ) + + def test_comments_and_string_values(self, tmp_path): + path = self.write_exclude( + tmp_path, + "# comment\n\n" + "exclude:\n" + ' - rules: "EMOJI"\n' + ' paths: "reference/**"\n', + name="comments.yml", + ) + config = gldq.load_exclude_file(path) + assert config.matches("EMOJI", Path("docs/reference/a.md"), Path("docs")) + assert not config.matches("FM-DESC", Path("docs/reference/a.md"), Path("docs")) + + def test_empty_exclude_list_is_valid(self, tmp_path): + path = self.write_exclude(tmp_path, "exclude: []\n", name="empty.yml") + assert gldq.load_exclude_file(path).rules == [] + + def test_missing_explicit_exclude_file(self, tmp_path, capsys): + write_doc(tmp_path, "docs/page.md", make_doc("# Page\n")) + missing = tmp_path / "missing.yml" + + assert gldq.main([str(tmp_path / "docs"), "--exclude-file", str(missing)]) == 2 + assert "exclude file not found" in capsys.readouterr().err + + def test_invalid_yaml_exclude_file(self, tmp_path, capsys): + write_doc(tmp_path, "docs/page.md", make_doc("# Page\n")) + path = self.write_exclude(tmp_path, "exclude: [\n", name="bad.yml") + + assert gldq.main([str(tmp_path / "docs"), "--exclude-file", str(path)]) == 2 + assert "invalid YAML" in capsys.readouterr().err + + def test_unknown_literal_rule_is_an_error(self, tmp_path, capsys): + write_doc(tmp_path, "docs/page.md", make_doc("# Page\n")) + path = self.write_exclude( + tmp_path, + 'exclude:\n - rules: ["NOPE"]\n paths: ["docs/**"]\n', + name="unknown.yml", + ) + + assert gldq.main([str(tmp_path / "docs"), "--exclude-file", str(path)]) == 2 + assert "unknown rule" in capsys.readouterr().err + + def test_missing_paths_is_an_error(self, tmp_path, capsys): + write_doc(tmp_path, "docs/page.md", make_doc("# Page\n")) + path = self.write_exclude( + tmp_path, + 'exclude:\n - rules: ["EMOJI"]\n', + name="missing-paths.yml", + ) + + assert gldq.main([str(tmp_path / "docs"), "--exclude-file", str(path)]) == 2 + assert "missing 'paths'" in capsys.readouterr().err + + def test_no_exclude_file_disables_autoload(self, tmp_path, monkeypatch, capsys): + self.write_exclude( + tmp_path, + "exclude:\n" + ' - rules: ["EMOJI"]\n' + ' paths: ["docs/reference/releases/release-notes/**"]\n', + ) + write_doc( + tmp_path, + "docs/reference/releases/release-notes/a.md", + make_release_note(), + ) + monkeypatch.chdir(tmp_path) + + assert gldq.main(["docs", "--no-exclude-file", "--format", "json"]) == 0 + payload = json.loads(capsys.readouterr().out) + assert payload["summary"]["excluded"] == 0 + assert any(finding["rule"] == "EMOJI" for finding in payload["findings"]) + + def test_custom_exclude_file(self, tmp_path, capsys): + path = self.write_exclude( + tmp_path, + "exclude:\n" + ' - rules: ["EMOJI"]\n' + ' paths: ["docs/reference/releases/release-notes/**"]\n', + name="custom.yml", + ) + write_doc( + tmp_path, + "docs/reference/releases/release-notes/a.md", + make_release_note(), + ) + + assert ( + gldq.main( + [ + str(tmp_path / "docs"), + "--exclude-file", + str(path), + "--format", + "json", + ] + ) + == 0 + ) + payload = json.loads(capsys.readouterr().out) + assert payload["summary"]["excluded"] == 1 + assert payload["summary"]["exclude_file"] == path.as_posix() + + def test_excluded_count_in_text_output(self, tmp_path, monkeypatch, capsys): + self.write_exclude( + tmp_path, + "exclude:\n" + ' - rules: ["EMOJI"]\n' + ' paths: ["docs/reference/releases/release-notes/**"]\n', + ) + write_doc( + tmp_path, + "docs/reference/releases/release-notes/a.md", + make_release_note(), + ) + monkeypatch.chdir(tmp_path) + + assert gldq.main(["docs"]) == 0 + output = capsys.readouterr().out + assert "1 finding(s) excluded by .gldq-exclude.yml" in output + + def test_excluded_count_in_github_output(self, tmp_path, monkeypatch, capsys): + self.write_exclude( + tmp_path, + "exclude:\n" + ' - rules: ["EMOJI"]\n' + ' paths: ["docs/reference/releases/release-notes/**"]\n', + ) + write_doc( + tmp_path, + "docs/reference/releases/release-notes/a.md", + make_release_note(), + ) + monkeypatch.chdir(tmp_path) + + assert gldq.main(["docs", "--format", "github"]) == 0 + output = capsys.readouterr().out + assert "1 excluded by .gldq-exclude.yml" in output + + +class TestCli: + def test_warning_only_exit_codes(self, tmp_path): + path = write_doc(tmp_path, "docs/page.md", "---\norder: 1\n---\n\n# Page\n") + assert gldq.main([str(path), "--no-exclude-file"]) == 0 + assert gldq.main([str(path), "--no-exclude-file", "--strict"]) == 1 + + def test_error_exit_code(self, tmp_path): + path = write_doc( + tmp_path, + "docs/page.md", + make_doc("# \n"), + ) + assert gldq.main([str(path), "--no-exclude-file"]) == 1 + + def test_disable_cli_rule(self, tmp_path): + path = write_doc( + tmp_path, + "docs/guide/index.md", + make_doc("# Page\n\nβœ…\n"), + ) + assert gldq.main([str(path), "--no-exclude-file", "--strict"]) == 1 + assert ( + gldq.main( + [ + str(path), + "--no-exclude-file", + "--strict", + "--disable", + "EMOJI", + ] + ) + == 0 + ) + + def test_json_output(self, tmp_path, capsys): + path = write_doc(tmp_path, "docs/page.md", "---\norder: 1\n---\n\n# Page\n") + assert gldq.main([str(path), "--no-exclude-file", "--format", "json"]) == 0 + payload = json.loads(capsys.readouterr().out) + assert payload["tool"] == "gldq" + assert payload["name"] == "Garden Linux Docs Quality" + assert payload["summary"]["files"] == 1 + assert payload["summary"]["excluded"] == 0 + assert isinstance(payload["findings"], list) + + def test_github_output(self, tmp_path, capsys): + path = write_doc(tmp_path, "docs/page.md", "---\norder: 1\n---\n\n# Page\n") + assert gldq.main([str(path), "--no-exclude-file", "--format", "github"]) == 0 + output = capsys.readouterr().out + assert "::warning" in output + assert "::notice" in output + + def test_list_rules(self, capsys): + assert gldq.main(["--list-rules"]) == 0 + output = capsys.readouterr().out + assert "FM-YAML" in output + assert "RELATED-TOPICS-PRESENT" in output + + def test_missing_path_returns_usage_error(self, tmp_path, capsys): + assert gldq.main([str(tmp_path / "missing"), "--no-exclude-file"]) == 2 + assert "path not found" in capsys.readouterr().err + + def test_single_file_infers_docs_root_for_related_topics(self, tmp_path): + write_doc(tmp_path, "docs/target.md", make_doc("# Target\n")) + path = write_doc( + tmp_path, + "docs/page.md", + make_doc( + "# Page\n", + frontmatter=( + "title: Page\n" + "description: Page\n" + "related_topics:\n" + " - /target.md\n" + ), + ), + ) + assert gldq.main([str(path), "--no-exclude-file"]) == 0 From de28e49eb3cba8b28d605b4e034f0cc6aa2e6fd6 Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Tue, 10 Nov 2026 16:02:01 +0100 Subject: [PATCH 02/15] fix(docs): normalize generated release notes Signed-off-by: Eike Waldt On-behalf-of: SAP Assisted-by: Kilo:claude-sonnet-4-6 --- src/aggregation/release_notes.py | 112 +++++++++++++++++++++++++++++++ tests/unit/test_release_notes.py | 112 +++++++++++++++++++++++++++++++ 2 files changed, 224 insertions(+) diff --git a/src/aggregation/release_notes.py b/src/aggregation/release_notes.py index c32d05c..80f339a 100644 --- a/src/aggregation/release_notes.py +++ b/src/aggregation/release_notes.py @@ -13,6 +13,117 @@ # Configuration ARCHIVED_DIR = "archived" +EMOJI_RE = re.compile("[\U0001f000-\U0001faff\u2300-\u23ff\u2600-\u27bf\u2b00-\u2bff]") +LEGACY_EMOJI_REPLACEMENTS = ( + ("πŸ“Š Table View", "Table View"), + ("πŸ“ Detailed View", "Detailed View"), +) +ATX_HEADING_RE = re.compile(r"^(#{1,6})[ \t]+(.*)$") +FENCE_RE = re.compile(r"^(\s*)(`{3,}|~{3,})(.*)$") + + +def _strip_emoji(line: str) -> str: + """Remove emoji from a line, preserving leading indentation.""" + if not EMOJI_RE.search(line): + return line + + leading = line[: len(line) - len(line.lstrip())] + content = line.lstrip() + if EMOJI_RE.match(content): + content = EMOJI_RE.sub("", content).lstrip() + return leading + content + return EMOJI_RE.sub("", line) + + +def _has_h1_outside_fences(lines: list[str]) -> bool: + """Return whether the body contains a level-1 heading outside fences.""" + fence_marker: str | None = None + + for line in lines: + fence_match = FENCE_RE.match(line) + if fence_match: + marker = fence_match.group(2) + info = fence_match.group(3) + if fence_marker is None: + fence_marker = marker + elif ( + not info.strip() + and marker[0] == fence_marker[0] + and len(marker) >= len(fence_marker) + ): + fence_marker = None + continue + + if fence_marker is not None: + continue + + heading_match = ATX_HEADING_RE.match(line) + if heading_match and len(heading_match.group(1)) == 1: + return True + + return False + + +def sanitize_release_note_body(body: str) -> str: + """Normalize release-note bodies for gldq and VitePress. + + Removes legacy emoji, demotes body H1 headings below the generated page + title, prevents skipped heading levels, adds a language to unlabeled code + fences, and closes unclosed fences. + """ + if not body: + return body + + lines = body.splitlines() + shift = 1 if _has_h1_outside_fences(lines) else 0 + sanitized: list[str] = [] + fence_marker: str | None = None + fence_close: str | None = None + previous_heading = 1 + + for line in lines: + fence_match = FENCE_RE.match(line) + if fence_match: + indent, marker, info = fence_match.groups() + if fence_marker is None: + if not info.strip(): + line = f"{indent}{marker}text" + fence_marker = marker + fence_close = f"{indent}{marker}" + elif ( + not info.strip() + and marker[0] == fence_marker[0] + and len(marker) >= len(fence_marker) + ): + fence_marker = None + fence_close = None + + sanitized.append(line) + continue + + if fence_marker is not None: + sanitized.append(line) + continue + + for old, new in LEGACY_EMOJI_REPLACEMENTS: + line = line.replace(old, new) + line = _strip_emoji(line) + + heading_match = ATX_HEADING_RE.match(line) + if heading_match: + original_level = len(heading_match.group(1)) + shifted_level = min(6, original_level + shift) + level = max(2, min(shifted_level, previous_heading + 1)) + line = f"{'#' * level} {heading_match.group(2)}" + previous_heading = level + + sanitized.append(line) + + if fence_marker is not None: + sanitized.append(fence_close or fence_marker) + + return "\n".join(sanitized) + def parse_version(tag: str) -> tuple: """Parse version string into comparable tuple for semantic versioning. @@ -79,6 +190,7 @@ def format_release_entry(release: dict) -> str: # Clean up GitHub markdown for VitePress compatibility body = cleanup_github_markdown(body) + body = sanitize_release_note_body(body) # Header with Published, Commit, and GitHub Release header = f"## {name}\n" diff --git a/tests/unit/test_release_notes.py b/tests/unit/test_release_notes.py index 1540854..d1507c6 100644 --- a/tests/unit/test_release_notes.py +++ b/tests/unit/test_release_notes.py @@ -2,10 +2,13 @@ from pathlib import Path +import gldq from aggregation.release_notes import ( + format_release_entry, generate_release_notes_docs, render_redirect_page, render_release_page, + sanitize_release_note_body, ) @@ -23,6 +26,115 @@ def _make_release(tag: str, name: str | None = None, draft: bool = False) -> dic } +class TestSanitizeReleaseNoteBody: + """sanitize_release_note_body normalizes legacy release-note content.""" + + def test_replaces_legacy_emoji_markers(self): + result = sanitize_release_note_body("πŸ“Š Table View\n\nπŸ“ Detailed View\n") + assert "πŸ“Š" not in result + assert "πŸ“" not in result + assert result.splitlines() == ["Table View", "", "Detailed View"] + + def test_strips_remaining_emoji(self): + result = sanitize_release_note_body("Status βœ…\n") + assert "βœ…" not in result + assert "Status" in result + + def test_demotes_h1_and_prevents_skipped_levels(self): + result = sanitize_release_note_body( + "# Changes\n\n### Deep\n\n# Published images\n" + ) + lines = result.splitlines() + assert lines[0] == "## Changes" + assert lines[2] == "### Deep" + assert lines[4] == "## Published images" + + def test_body_without_h1_starts_at_h2(self): + result = sanitize_release_note_body("### Deep\n\n#### Deeper\n") + lines = result.splitlines() + assert lines[0] == "## Deep" + assert lines[2] == "### Deeper" + + def test_adds_language_to_unlabeled_fences(self): + result = sanitize_release_note_body("```\nfoo\n```\n") + assert result.splitlines() == ["```text", "foo", "```"] + + def test_preserves_fenced_content(self): + result = sanitize_release_note_body( + "```text\n# Not a heading\nπŸ“Š Table View\n```\n" + ) + assert result.splitlines()[0] == "```text" + assert "# Not a heading" in result + assert "πŸ“Š Table View" in result + + def test_closes_unclosed_fence(self): + result = sanitize_release_note_body("```text\nunclosed\n") + assert result.splitlines() == ["```text", "unclosed", "```"] + + def test_indented_unlabeled_fence_gets_language(self): + result = sanitize_release_note_body(" ```\n foo\n ```\n") + assert result.splitlines() == [" ```text", " foo", " ```"] + + def test_format_release_entry_sanitizes_body(self): + release = _make_release("2150.6.0") + release["body"] = "πŸ“Š Table View\n\n# Changes\n\n```\nfoo\n```\n" + + result = format_release_entry(release) + + assert "πŸ“Š" not in result + assert "## Changes" in result + assert "```text" in result + + def test_generated_release_page_passes_gldq(self, tmp_path): + release = _make_release("2150.6.0") + release["body"] = ( + "πŸ“Š Table View\n\n" + "πŸ“ Detailed View\n\n" + "# Changes\n\n" + "## Software Component Versions\n\n" + "```\ncontainerd 1.0\n```\n\n" + "```text\nunclosed\n" + ) + docs_dir = tmp_path / "docs" + docs_dir.mkdir() + assert generate_release_notes_docs(docs_dir, [release], set()) + + page = ( + docs_dir + / "reference" + / "releases" + / "release-notes" + / "archived" + / "2150-6-0.md" + ) + document = gldq.parse_document(page, docs_dir) + findings, _, _ = gldq.collect_findings([document], set()) + rule_ids = {finding.rule_id for finding in findings} + + for rule_id in ( + "CODE-BALANCE", + "CODE-LANG", + "EMOJI", + "H1-ONE", + "HEAD-SKIP", + "RELATED-TOPICS-PRESENT", + ): + assert rule_id not in rule_ids + + def test_redirect_alias_skips_related_topics_present(self, tmp_path): + docs_dir = tmp_path / "docs" + docs_dir.mkdir() + assert generate_release_notes_docs( + docs_dir, [_make_release("2150.13.0")], set() + ) + + alias = docs_dir / "reference" / "releases" / "release-notes" / "2150-13-0.md" + document = gldq.parse_document(alias, docs_dir) + findings, _, _ = gldq.collect_findings([document], set()) + + assert "RELATED-TOPICS-PRESENT" not in {finding.rule_id for finding in findings} + + class TestRenderReleasePage: """render_release_page controls the generated frontmatter.""" From 49906c3f186b47003c7d61d889488db54f281a30 Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Tue, 10 Nov 2026 16:02:13 +0100 Subject: [PATCH 03/15] chore(docs): add gldq exclusion rules Signed-off-by: Eike Waldt On-behalf-of: SAP Assisted-by: Kilo:claude-sonnet-4-6 --- .gldq-exclude.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .gldq-exclude.yml diff --git a/.gldq-exclude.yml b/.gldq-exclude.yml new file mode 100644 index 0000000..519e401 --- /dev/null +++ b/.gldq-exclude.yml @@ -0,0 +1,19 @@ +# Rule-aware exclusions for gldq. +# Aggregated files cannot be edited in this repository. +# +# Syntax: +# exclude: +# - rules: ["EMOJI", "CODE-*"] # rule wildcards; omit for all rules +# paths: ["docs/reference/**"] # paths are relative to the repo or docs root +exclude: + - rules: + - "FM-DESC" + - "RELATED-TOPICS-PRESENT" + paths: + - "docs/reference/adr/**" + - rules: + - "CODE-LANG" + paths: + - "docs/reference/adr/0014-enforce-pr-references-in-commits.md" + - "docs/reference/adr/0035-cname-flavor-artifact-naming.md" + - "docs/reference/adr/install.md" From 8baac174907e38965862426fa54942986e4176f0 Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Tue, 10 Nov 2026 16:13:07 +0100 Subject: [PATCH 04/15] Potential fix for pull request finding 'CodeQL / Workflow does not contain permissions' Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> Signed-off-by: Eike Waldt --- .github/workflows/docs-checks.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/docs-checks.yml b/.github/workflows/docs-checks.yml index e02a369..efa99f9 100644 --- a/.github/workflows/docs-checks.yml +++ b/.github/workflows/docs-checks.yml @@ -1,5 +1,10 @@ name: Documentation Quality Checks +permissions: + contents: read + actions: read + packages: read + on: workflow_call: inputs: From 6c14fa8918600ab3f1ffcde0da89b3112bef5c3e Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Wed, 18 Nov 2026 11:23:05 +0100 Subject: [PATCH 05/15] feat(docs): add vitepress callouts to gldq Signed-off-by: Eike Waldt On-behalf-of: SAP Assisted-by: Kilo:claude-sonnet-4-6 --- src/gldq.py | 360 +++++++++++++++++++++++----------------- tests/unit/test_gldq.py | 107 ++++++++++++ 2 files changed, 315 insertions(+), 152 deletions(-) diff --git a/src/gldq.py b/src/gldq.py index fc60a5a..85d98fc 100755 --- a/src/gldq.py +++ b/src/gldq.py @@ -64,6 +64,13 @@ ) DEFAULT_EXCLUDE_FILE = Path(".gldq-exclude.yml") +VITEPRESS_CALLOUT_TYPES = {"info", "tip", "warning", "danger", "details"} +CALLOUT_OPEN_RE = re.compile(r"^\s*(:{3,})\s*([A-Za-z][A-Za-z0-9_-]*)\b(.*)$") +CALLOUT_CLOSE_RE = re.compile(r"^\s*(:{3,})\s*$") +GITHUB_CALLOUT_RE = re.compile( + r"^\s*>\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$", re.IGNORECASE +) + @dataclass(frozen=True) class RuleInfo: @@ -122,6 +129,21 @@ class RuleInfo: WARNING, "Non-index pages should include ", ), + "CALLOUT-INVALID-TYPE": RuleInfo( + "CALLOUT-INVALID-TYPE", + ERROR, + "Invalid VitePress container type; use info, tip, warning, danger, or details", + ), + "CALLOUT-GITHUB-STYLE": RuleInfo( + "CALLOUT-GITHUB-STYLE", + ERROR, + "GitHub-style callouts are not supported; use VitePress ::: syntax", + ), + "CALLOUT-UNCLOSED": RuleInfo( + "CALLOUT-UNCLOSED", + ERROR, + "VitePress container is not closed with :::", + ), } CHECKS: list[Callable[["Document"], Iterator["Finding"]]] = [] @@ -267,7 +289,6 @@ def no_fence_text(self) -> str: def _first_line(text: str) -> str: return text.splitlines()[0] if text.splitlines() else str(text) - def _parse_frontmatter( lines: Sequence[str], ) -> tuple[dict | None, str | None, bool, int]: @@ -277,7 +298,7 @@ def _parse_frontmatter( end: int | None = None for index in range(1, len(lines)): - if lines[index].strip() in ("---", "..."): + if lines[index].strip() in ("---", "..."): # Allow "..." as an alternative closing delimiter for front matter. end = index break @@ -295,7 +316,6 @@ def _parse_frontmatter( return None, "Front matter must be a YAML mapping", True, end + 1 return data, None, True, end + 1 - def _mask_html_comments(lines: Sequence[str]) -> list[str]: """Replace HTML comment content with spaces while preserving lines.""" masked: list[str] = [] @@ -333,7 +353,6 @@ def _mask_html_comments(lines: Sequence[str]) -> list[str]: masked.append("".join(chars)) return masked - def _mask_inline_code(line: str) -> str: """Replace inline code spans with spaces.""" chars = list(line) @@ -374,7 +393,6 @@ def _mask_inline_code(line: str) -> str: return "".join(chars) - def _mask_fences( lines: Sequence[str], body_start: int ) -> tuple[list[str], list[Fence]]: @@ -414,7 +432,6 @@ def _mask_fences( return masked, fences - def _extract_headings(lines: Sequence[str], body_start: int) -> list[Heading]: """Extract ATX headings from masked lines.""" headings: list[Heading] = [] @@ -426,11 +443,12 @@ def _extract_headings(lines: Sequence[str], body_start: int) -> list[Heading]: headings.append(Heading(line=index + 1, level=len(match.group(1)), text=text)) return headings - def _parse_suppressions(lines: Sequence[str]) -> Suppressions: """Parse gldq suppression comments.""" suppressions = Suppressions() - for index, line in enumerate(lines, start=1): + for index in range(len(lines)): + line_number = index + 1 + line = lines[index] for match in SUPPRESSION_RE.finditer(line): kind = match.group(1).lower() rules = { @@ -443,13 +461,12 @@ def _parse_suppressions(lines: Sequence[str]) -> Suppressions: if kind == "disable-file": suppressions.file_rules.update(rules) elif kind == "disable-next-line": - suppressions.next_line.setdefault(index + 1, set()).update(rules) + suppressions.next_line.setdefault(line_number + 1, set()).update(rules) else: - suppressions.from_line.append((index, rules)) + suppressions.from_line.append((line_number, rules)) suppressions.from_line.sort(key=lambda item: item[0]) return suppressions - def _path_matches(path_text: str, pattern: str) -> bool: """Match a POSIX path against a wildcard pattern.""" pattern = pattern.strip().replace("\\", "/") @@ -465,7 +482,6 @@ def _path_matches(path_text: str, pattern: str) -> bool: prefix = pattern.rstrip("/") return bool(prefix) and path_text.startswith(prefix + "/") - def _string_list(value: object, path: Path, entry: int, field_name: str) -> list[str]: """Normalize a YAML string or list of strings.""" if isinstance(value, str): @@ -474,18 +490,17 @@ def _string_list(value: object, path: Path, entry: int, field_name: str) -> list values = value else: raise ValueError( - f"{path}: exclude entry {entry} field '{field_name}' " + f"{path}: exclude entry {entry} field \'{field_name}\' " "must be a string or a list of strings" ) cleaned = [item.strip() for item in values if item.strip()] if not cleaned: raise ValueError( - f"{path}: exclude entry {entry} field '{field_name}' must not be empty" + f"{path}: exclude entry {entry} field \'{field_name}\' must not be empty" ) return cleaned - def load_exclude_file(path: Path) -> ExcludeConfig: """Load a rule-aware exclusion file.""" try: @@ -504,7 +519,7 @@ def load_exclude_file(path: Path) -> ExcludeConfig: if entries is None: return ExcludeConfig(path=path) if not isinstance(entries, list): - raise ValueError(f"{path}: 'exclude' must be a list") + raise ValueError(f"{path}: \'exclude\' must be a list") config = ExcludeConfig(path=path) for index, entry in enumerate(entries, start=1): @@ -516,14 +531,14 @@ def load_exclude_file(path: Path) -> ExcludeConfig: rules_value = ["*"] paths_value = entry.get("paths") if paths_value is None: - raise ValueError(f"{path}: exclude entry {index} is missing 'paths'") + raise ValueError(f"{path}: exclude entry {index} is missing \'paths\'") rule_patterns = _string_list(rules_value, path, index, "rules") path_patterns = _string_list(paths_value, path, index, "paths") for pattern in rule_patterns: normalized = pattern.upper() - if not any(character in normalized for character in "*?["): + if not any(character in normalized for character in "*?[]"): if normalized not in RULES: raise ValueError( f"{path}: exclude entry {index} references unknown rule: " @@ -539,7 +554,40 @@ def load_exclude_file(path: Path) -> ExcludeConfig: ) return config +def _infer_root(path: Path) -> Path: + """Infer the documentation root for a file or directory path.""" + candidate = path if path.is_dir() else path.parent + for parent in (candidate, *candidate.parents): + if parent.name == "docs": + return parent + return candidate +def _should_skip(file_path: Path, root: Path, excludes: Sequence[str]) -> bool: + """Return whether a path should be skipped.""" + try: + relative = file_path.relative_to(root) + except ValueError: + relative = file_path + if any(part in SKIP_DIRS for part in relative.parts): + return True + if file_path.name.startswith("_"): + return True + + relative_text = relative.as_posix() + full_text = file_path.as_posix() + for pattern in excludes: + cleaned = pattern.strip() + while cleaned.startswith("./"): + cleaned = cleaned[2:] + if not cleaned: + continue + if fnmatch.fnmatch(relative_text, cleaned): + return True + if fnmatch.fnmatch(full_text, cleaned): + return True + if relative_text.startswith(cleaned.rstrip("/") + "/"): + return True + return False def parse_document(path: Path, root: Path) -> Document: """Parse a markdown file into a Document.""" @@ -574,6 +622,60 @@ def parse_document(path: Path, root: Path) -> Document: ) +def iter_documents( + paths: Sequence[Path], excludes: Sequence[str] +) -> Iterator[Document]: + """Yield parsed markdown documents for the given paths.""" + seen: set[Path] = set() + for path in paths: + if path.is_dir(): + root = path + candidates = sorted(path.rglob("*.md")) + else: + root = _infer_root(path) + candidates = [path] + + for file_path in candidates: + if file_path.suffix.lower() != ".md": + continue + if _should_skip(file_path, root, excludes): + continue + resolved = file_path.resolve() + if resolved in seen: + continue + seen.add(resolved) + yield parse_document(file_path, root) + + +def collect_findings( + documents: Sequence[Document], + disabled: set[str], + exclusions: ExcludeConfig | None = None, +) -> tuple[list[Finding], int, int]: + """Run every check and apply suppressions and exclusions.""" + if exclusions is None: + exclusions = ExcludeConfig() + + findings: list[Finding] = [] + suppressed = 0 + excluded = 0 + + for document in documents: + for check in CHECKS: + for finding in check(document): + if finding.rule_id in disabled or document.suppressions.suppresses( + finding.rule_id, finding.line + ): + suppressed += 1 + continue + if exclusions.matches(finding.rule_id, document.path, document.root): + excluded += 1 + continue + findings.append(finding) + + findings.sort(key=lambda item: item.sort_key) + return findings, suppressed, excluded + def _resolve_target(root: Path, reference: str) -> bool: """Resolve a related_topics reference against the docs root.""" reference = reference.strip() @@ -589,7 +691,7 @@ def _resolve_target(root: Path, reference: str) -> bool: reference = reference.lstrip("/") if not reference or reference == ".": return (root / "index.md").is_file() - if reference.endswith("/"): + if reference.endswith("/"): return (root / reference / "index.md").is_file() candidates = [root / reference] @@ -598,7 +700,6 @@ def _resolve_target(root: Path, reference: str) -> bool: candidates.append(root / reference / "index.md") return any(candidate.is_file() for candidate in candidates) - def _finding( document: Document, rule_id: str, @@ -616,7 +717,6 @@ def _finding( message=message, ) - def check_frontmatter(document: Document) -> Iterator[Finding]: """Check front matter structure and related topics.""" frontmatter = document.frontmatter or {} @@ -657,7 +757,7 @@ def check_frontmatter(document: Document) -> Iterator[Finding]: "FM-ORDER", 1, 1, - "Front matter 'order' must be an integer", + "Front matter \'order\' must be an integer", ) if "related_topics" in frontmatter: @@ -668,7 +768,7 @@ def check_frontmatter(document: Document) -> Iterator[Finding]: "FM-RELATED", 1, 1, - "Front matter 'related_topics' must be a list", + "Front matter \'related_topics\' must be a list", ) else: for reference in related_topics: @@ -678,7 +778,7 @@ def check_frontmatter(document: Document) -> Iterator[Finding]: "FM-RELATED", 1, 1, - "Front matter 'related_topics' entries must be non-empty strings", + "Front matter \'related_topics\' entries must be non-empty strings", ) continue if not _resolve_target(document.root, reference): @@ -690,7 +790,6 @@ def check_frontmatter(document: Document) -> Iterator[Finding]: f"related_topics target not found: {reference}", ) - def check_headings(document: Document) -> Iterator[Finding]: """Check heading structure.""" level_one = [heading for heading in document.headings if heading.level == 1] @@ -724,7 +823,6 @@ def check_headings(document: Document) -> Iterator[Finding]: ) previous = heading.level - def check_code(document: Document) -> Iterator[Finding]: """Check fenced code block language and balance.""" for fence in document.fences: @@ -745,7 +843,6 @@ def check_code(document: Document) -> Iterator[Finding]: "Fenced code block is not closed", ) - def check_images(document: Document) -> Iterator[Finding]: """Check markdown and HTML image alt text.""" for index in range(document.body_start, len(document.no_fence_lines)): @@ -789,14 +886,12 @@ def check_images(document: Document) -> Iterator[Finding]: "HTML image has empty alt text", ) - def _normalize_link_text(text: str) -> str: text = re.sub(r"`+", "", text) text = re.sub(r"[*_~]", "", text) text = " ".join(text.split()).strip().lower() return text.strip(" .,:;!?()[]{}<>\"'") - def check_links(document: Document) -> Iterator[Finding]: """Check for missing or generic link text.""" for index in range(document.body_start, len(document.no_fence_lines)): @@ -814,7 +909,6 @@ def check_links(document: Document) -> Iterator[Finding]: f"Link text is not descriptive: {text!r}", ) - def check_emoji(document: Document) -> Iterator[Finding]: """Check for emoji outside code fences and front matter.""" for index in range(document.body_start, len(document.prose_lines)): @@ -828,21 +922,18 @@ def check_emoji(document: Document) -> Iterator[Finding]: f"Emoji outside code fence: {match.group(0)}", ) - def _first_line_with(lines: Sequence[str], needle: str) -> int | None: for index, line in enumerate(lines): if needle in line: return index + 1 return None - def _last_line_with(lines: Sequence[str], needle: str) -> int | None: for index in range(len(lines) - 1, -1, -1): if needle in lines[index]: return index + 1 return None - def check_components(document: Document) -> Iterator[Finding]: """Check VitePress component requirements.""" text = document.no_fence_text @@ -903,11 +994,10 @@ def check_components(document: Document) -> Iterator[Finding]: 1, " must be the last content block", ) - break if ( - not document.is_index - and not document.is_home + not document.is_home + and not document.is_index and not document.is_excluded and not has_related_topics ): @@ -916,7 +1006,55 @@ def check_components(document: Document) -> Iterator[Finding]: "RELATED-TOPICS-PRESENT", 1, 1, - "Content page is missing ", + "Non-index pages should include ", + ) + + +def check_callouts(document: Document) -> Iterator[Finding]: + """Check VitePress container callouts and reject unsupported syntax.""" + stack: list[tuple[int, str, int]] = [] + + for index in range(document.body_start, len(document.no_fence_lines)): + line = document.no_fence_lines[index] + line_number = index + 1 + + if GITHUB_CALLOUT_RE.match(line): + yield _finding( + document, + "CALLOUT-GITHUB-STYLE", + line_number, + 1, + "GitHub-style callouts are not supported; use VitePress ::: syntax", + ) + continue + + close_match = CALLOUT_CLOSE_RE.match(line) + if close_match and stack: + if len(close_match.group(1)) >= stack[-1][2]: + stack.pop() + continue + + open_match = CALLOUT_OPEN_RE.match(line) + if open_match: + callout_type = open_match.group(2).lower() + if callout_type not in VITEPRESS_CALLOUT_TYPES: + yield _finding( + document, + "CALLOUT-INVALID-TYPE", + line_number, + 1, + "Invalid VitePress container type " + f"{callout_type!r}; use info, tip, warning, danger, or details", + ) + stack.append((line_number, callout_type, len(open_match.group(1)))) + + for line_number, _, _ in stack: + yield _finding( + document, + "CALLOUT-UNCLOSED", + line_number, + 1, + "VitePress container is not closed with :::", ) @@ -929,99 +1067,32 @@ def check_components(document: Document) -> Iterator[Finding]: check_links, check_emoji, check_components, + check_callouts, ] ) -def _should_skip(file_path: Path, root: Path, excludes: Sequence[str]) -> bool: - try: - relative = file_path.relative_to(root) - except ValueError: - relative = file_path - - if any(part in SKIP_DIRS for part in relative.parts): - return True - if file_path.name.startswith("_"): - return True - - relative_text = relative.as_posix() - full_text = file_path.as_posix() - for pattern in excludes: - cleaned = pattern.strip().lstrip("./") - if not cleaned: - continue - if fnmatch.fnmatch(relative_text, cleaned): - return True - if fnmatch.fnmatch(full_text, cleaned): - return True - if relative_text.startswith(cleaned.rstrip("/") + "/"): - return True - return False - - -def _infer_root(path: Path) -> Path: - """Infer the documentation root for a file or directory path.""" - candidate = path if path.is_dir() else path.parent - for parent in (candidate, *candidate.parents): - if parent.name == "docs": - return parent - return candidate - - -def iter_documents( - paths: Sequence[Path], excludes: Sequence[str] -) -> Iterator[Document]: - """Yield parsed documents for all markdown files under the given paths.""" - for path in paths: - root = _infer_root(path) - if path.is_file(): - if path.suffix.lower() == ".md": - yield parse_document(path, root) - continue - - for file_path in sorted(path.rglob("*.md")): - if _should_skip(file_path, root, excludes): - continue - yield parse_document(file_path, root) - - -def collect_findings( - documents: Sequence[Document], - disabled: set[str], - exclusions: ExcludeConfig | None = None, -) -> tuple[list[Finding], int, int]: - """Run all checks and return findings, suppressed, and excluded counts.""" - findings: list[Finding] = [] - suppressed = 0 - excluded = 0 - - for document in documents: - for check in CHECKS: - for finding in check(document): - if finding.rule_id in disabled or document.suppressions.suppresses( - finding.rule_id, finding.line - ): - suppressed += 1 - continue - if exclusions is not None and exclusions.matches( - finding.rule_id, document.path, document.root - ): - excluded += 1 - continue - findings.append(finding) - - findings.sort(key=lambda finding: finding.sort_key) - return findings, suppressed, excluded - - def _counts(findings: Sequence[Finding]) -> tuple[int, int]: errors = sum(1 for finding in findings if finding.severity == ERROR) warnings = sum(1 for finding in findings if finding.severity == WARNING) return errors, warnings +def _escape_github(text: str) -> str: + return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + + def _exclude_label(exclude_file: Path | None) -> str: - return exclude_file.as_posix() if exclude_file is not None else "exclude file" + return exclude_file.as_posix() if exclude_file else "exclude file" + + +def _format_location(finding: Finding) -> str: + location = f"{finding.path}" + if finding.line is not None: + location += f":{finding.line}" + if finding.column is not None: + location += f":{finding.column}" + return location def format_text( @@ -1032,29 +1103,23 @@ def format_text( exclude_file: Path | None = None, ) -> str: """Format findings as human-readable text.""" - lines: list[str] = [] - for finding in findings: - location = str(finding.path) - if finding.line is not None: - location += f":{finding.line}" - if finding.column is not None: - location += f":{finding.column}" - lines.append( - f"{location}: {finding.severity}: [{finding.rule_id}] {finding.message}" - ) + lines = [ + f"{_format_location(finding)}: {finding.severity} " + f"{finding.rule_id}: {finding.message}" + for finding in findings + ] + if not lines: + lines.append("No documentation quality findings.") errors, warnings = _counts(findings) - if lines: - lines.append("") - lines.append( - f"gldq: {errors} error(s), {warnings} warning(s) in {file_count} file(s)" - ) + summary = f"{errors} error(s), {warnings} warning(s) in {file_count} file(s)" if suppressed: - lines.append(f"gldq: {suppressed} finding(s) suppressed inline") + summary += f", {suppressed} suppressed inline" if excluded: - lines.append( - f"gldq: {excluded} finding(s) excluded by {_exclude_label(exclude_file)}" + summary += ( + f", {excluded} finding(s) excluded by {_exclude_label(exclude_file)}" ) + lines.append(summary) return "\n".join(lines) @@ -1069,25 +1134,23 @@ def format_json( errors, warnings = _counts(findings) payload = { "tool": "gldq", - "name": "Garden Linux Docs Quality", "version": __version__, + "name": "Garden Linux Docs Quality", "summary": { "files": file_count, "errors": errors, "warnings": warnings, "suppressed": suppressed, "excluded": excluded, - "exclude_file": ( - exclude_file.as_posix() if exclude_file is not None else None - ), + "exclude_file": exclude_file.as_posix() if exclude_file else None, }, "findings": [ { - "path": str(finding.path), + "path": finding.path.as_posix(), "line": finding.line, "column": finding.column, - "severity": finding.severity, "rule": finding.rule_id, + "severity": finding.severity, "message": finding.message, } for finding in findings @@ -1096,10 +1159,6 @@ def format_json( return json.dumps(payload, indent=2) -def _escape_github(text: str) -> str: - return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") - - def format_github( findings: Sequence[Finding], suppressed: int, @@ -1134,14 +1193,12 @@ def format_github( lines.append(summary) return "\n".join(lines) - def print_rules() -> None: """Print the rule registry.""" print(f"{'RULE':22} {'SEVERITY':8} DESCRIPTION") for rule in sorted(RULES.values(), key=lambda item: item.rule_id): print(f"{rule.rule_id:22} {rule.severity:8} {rule.description}") - def build_parser() -> argparse.ArgumentParser: """Build the command-line parser.""" parser = argparse.ArgumentParser( @@ -1202,7 +1259,6 @@ def build_parser() -> argparse.ArgumentParser: ) return parser - def main(argv: Sequence[str] | None = None) -> int: """Run gldq and return an exit code.""" parser = build_parser() @@ -1223,7 +1279,7 @@ def main(argv: Sequence[str] | None = None) -> int: unknown = disabled - set(RULES) if unknown: print( - f"gldq: unknown rule(s): {', '.join(sorted(unknown))}", + f"gldq: unknown rule(s): {','.join(sorted(unknown))}", file=sys.stderr, ) return 2 @@ -1271,4 +1327,4 @@ def main(argv: Sequence[str] | None = None) -> int: if __name__ == "__main__": - sys.exit(main()) + sys.exit(main()) \ No newline at end of file diff --git a/tests/unit/test_gldq.py b/tests/unit/test_gldq.py index 8dacb25..77c43a7 100644 --- a/tests/unit/test_gldq.py +++ b/tests/unit/test_gldq.py @@ -725,6 +725,9 @@ def test_list_rules(self, capsys): output = capsys.readouterr().out assert "FM-YAML" in output assert "RELATED-TOPICS-PRESENT" in output + assert "CALLOUT-INVALID-TYPE" in output + assert "CALLOUT-GITHUB-STYLE" in output + assert "CALLOUT-UNCLOSED" in output def test_missing_path_returns_usage_error(self, tmp_path, capsys): assert gldq.main([str(tmp_path / "missing"), "--no-exclude-file"]) == 2 @@ -746,3 +749,107 @@ def test_single_file_infers_docs_root_for_related_topics(self, tmp_path): ), ) assert gldq.main([str(path), "--no-exclude-file"]) == 0 + + +class TestCallouts: + """Tests for VitePress container callout validation.""" + + @staticmethod + def callout_ids(findings: list[gldq.Finding]) -> list[str]: + """Return only CALLOUT rule IDs from findings.""" + return [rule for rule in rule_ids(findings) if rule.startswith("CALLOUT")] + + def test_valid_containers_pass(self, tmp_path): + content = make_doc( + "# Page\n\n" + ":::tip\nAdvice\n:::\n\n" + "::: info\nInformation\n:::\n\n" + "::: tip Spaced\nAdvice\n:::\n\n" + "::: details Click to expand\nDetails\n:::\n\n" + ":::warning\nCaveat\n:::\n\n" + ":::danger\nCritical\n:::\n" + ) + assert self.callout_ids(find(tmp_path, content)) == [] + + def test_false_friends_are_errors(self, tmp_path): + content = make_doc( + "# Page\n\n" + ":::note\nNote\n:::\n\n" + ":::important\nImportant\n:::\n\n" + ":::success\nSuccess\n:::\n\n" + "::: error\nError\n:::\n" + ) + ids = self.callout_ids(find(tmp_path, content)) + assert ids.count("CALLOUT-INVALID-TYPE") == 4 + + def test_github_style_callouts_are_errors(self, tmp_path): + content = make_doc( + "# Page\n\n" + "> [!NOTE]\n" + "> Text\n\n" + "> [!IMPORTANT]\n" + "> Text\n\n" + " > [!WARNING] \n" + ) + ids = self.callout_ids(find(tmp_path, content)) + assert ids.count("CALLOUT-GITHUB-STYLE") == 3 + + def test_fenced_examples_are_ignored(self, tmp_path): + content = make_doc( + "# Page\n\n" + "```markdown\n" + ":::note\n" + "> [!NOTE]\n" + ":::\n" + "```\n" + ) + assert self.callout_ids(find(tmp_path, content)) == [] + + def test_indented_container_in_list_passes(self, tmp_path): + content = make_doc( + "# Page\n\n" + "- item\n\n" + " ::: tip\n" + " Advice\n" + " :::\n" + ) + assert self.callout_ids(find(tmp_path, content)) == [] + + def test_nested_containers_balance(self, tmp_path): + content = make_doc( + "# Page\n\n" + "::: details\n" + "Outer\n\n" + ":::: tip\n" + "Inner\n" + "::::\n\n" + ":::\n" + ) + assert "CALLOUT-UNCLOSED" not in self.callout_ids(find(tmp_path, content)) + + def test_unclosed_container_is_an_error(self, tmp_path): + content = make_doc("# Page\n\n:::tip\nAdvice\n") + findings = [ + finding + for finding in find(tmp_path, content) + if finding.rule_id == "CALLOUT-UNCLOSED" + ] + assert len(findings) == 1 + assert findings[0].line == 8 + + def test_suppression_comment_is_honored(self, tmp_path): + content = make_doc( + "# Page\n\n" + "\n" + "> [!NOTE]\n" + "> Text\n" + ) + assert "CALLOUT-GITHUB-STYLE" not in self.callout_ids(find(tmp_path, content)) + + def test_path_matches_wildcard_and_dot_prefix(self): + assert gldq._path_matches( + "reference/features/a.md", "./reference/features/**" + ) + assert not gldq._path_matches( + "docs/reference/other/a.md", "./reference/features/**" + ) From 812bb3eae9afdbde0f627f7d700217e1cf39740f Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Wed, 25 Nov 2026 16:19:00 +0100 Subject: [PATCH 06/15] docs: convert github callouts in release notes Signed-off-by: Eike Waldt On-behalf-of: SAP Assisted-by: opencode:claude-opus-4-8 --- src/aggregation/release_notes.py | 91 ++++++++++++++++++++++++++++++-- tests/unit/test_release_notes.py | 32 +++++++++++ 2 files changed, 119 insertions(+), 4 deletions(-) diff --git a/src/aggregation/release_notes.py b/src/aggregation/release_notes.py index 80f339a..fda2ece 100644 --- a/src/aggregation/release_notes.py +++ b/src/aggregation/release_notes.py @@ -21,6 +21,21 @@ ATX_HEADING_RE = re.compile(r"^(#{1,6})[ \t]+(.*)$") FENCE_RE = re.compile(r"^(\s*)(`{3,}|~{3,})(.*)$") +# GitHub-style callout opener, e.g. ``> [!NOTE]`` (trailing whitespace allowed). +GITHUB_CALLOUT_RE = re.compile( + r"^\s*>\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$", re.IGNORECASE +) +# Blockquote body line, e.g. ``> text`` or a bare ``>``. +BLOCKQUOTE_RE = re.compile(r"^\s*>\s?(.*)$") +# Map GitHub callout types to VitePress container types accepted by gldq. +GITHUB_CALLOUT_TYPES = { + "NOTE": "info", + "IMPORTANT": "info", + "TIP": "tip", + "WARNING": "warning", + "CAUTION": "danger", +} + def _strip_emoji(line: str) -> str: """Remove emoji from a line, preserving leading indentation.""" @@ -64,17 +79,85 @@ def _has_h1_outside_fences(lines: list[str]) -> bool: return False +def _convert_github_callouts(lines: list[str]) -> list[str]: + """Rewrite GitHub-style blockquote callouts as VitePress containers. + + GitHub renders ``> [!NOTE]`` blockquotes as admonitions; VitePress uses + ``::: info`` containers instead. This converts the GitHub syntax (which the + gldq ``CALLOUT-GITHUB-STYLE`` rule rejects) into the semantic VitePress + equivalent, preserving the original type as the container title. + + Code fences are skipped so blockquote-looking lines inside fenced blocks are + left untouched. + """ + converted: list[str] = [] + fence_marker: str | None = None + index = 0 + + while index < len(lines): + line = lines[index] + fence_match = FENCE_RE.match(line) + if fence_match: + marker, info = fence_match.group(2), fence_match.group(3) + if fence_marker is None: + fence_marker = marker + elif ( + not info.strip() + and marker[0] == fence_marker[0] + and len(marker) >= len(fence_marker) + ): + fence_marker = None + converted.append(line) + index += 1 + continue + + if fence_marker is not None: + converted.append(line) + index += 1 + continue + + opener = GITHUB_CALLOUT_RE.match(line) + if not opener: + converted.append(line) + index += 1 + continue + + callout_type = opener.group(1).upper() + container = GITHUB_CALLOUT_TYPES.get(callout_type, "info") + + # Collect the blockquote body lines that follow the opener. + body: list[str] = [] + index += 1 + while index < len(lines): + body_match = BLOCKQUOTE_RE.match(lines[index]) + if body_match is None: + break + body.append(body_match.group(1).rstrip()) + index += 1 + + # Drop trailing blank blockquote lines for a tidy container. + while body and not body[-1]: + body.pop() + + converted.append(f"::: {container} {callout_type}") + converted.extend(body) + converted.append(":::") + + return converted + + def sanitize_release_note_body(body: str) -> str: """Normalize release-note bodies for gldq and VitePress. - Removes legacy emoji, demotes body H1 headings below the generated page - title, prevents skipped heading levels, adds a language to unlabeled code - fences, and closes unclosed fences. + Removes legacy emoji, converts GitHub-style callouts to VitePress + containers, demotes body H1 headings below the generated page title, + prevents skipped heading levels, adds a language to unlabeled code fences, + and closes unclosed fences. """ if not body: return body - lines = body.splitlines() + lines = _convert_github_callouts(body.splitlines()) shift = 1 if _has_h1_outside_fences(lines) else 0 sanitized: list[str] = [] fence_marker: str | None = None diff --git a/tests/unit/test_release_notes.py b/tests/unit/test_release_notes.py index d1507c6..fb21aa7 100644 --- a/tests/unit/test_release_notes.py +++ b/tests/unit/test_release_notes.py @@ -75,6 +75,35 @@ def test_indented_unlabeled_fence_gets_language(self): result = sanitize_release_note_body(" ```\n foo\n ```\n") assert result.splitlines() == [" ```text", " foo", " ```"] + def test_converts_github_callout_to_vitepress_container(self): + result = sanitize_release_note_body( + "> [!NOTE] \n" + "> This release is `1443.15`.\n" + "> It follows `1443.10`.\n" + ) + assert result.splitlines() == [ + "::: info NOTE", + "This release is `1443.15`.", + "It follows `1443.10`.", + ":::", + ] + + def test_github_callout_type_mapping(self): + for github_type, container in ( + ("NOTE", "info"), + ("IMPORTANT", "info"), + ("TIP", "tip"), + ("WARNING", "warning"), + ("CAUTION", "danger"), + ): + result = sanitize_release_note_body(f"> [!{github_type}]\n> body\n") + assert result.splitlines()[0] == f"::: {container} {github_type}" + + def test_leaves_github_callout_inside_fence_untouched(self): + result = sanitize_release_note_body("```text\n> [!NOTE]\n> keep\n```\n") + assert "> [!NOTE]" in result + assert "::: info" not in result + def test_format_release_entry_sanitizes_body(self): release = _make_release("2150.6.0") release["body"] = "πŸ“Š Table View\n\n# Changes\n\n```\nfoo\n```\n" @@ -91,6 +120,8 @@ def test_generated_release_page_passes_gldq(self, tmp_path): "πŸ“Š Table View\n\n" "πŸ“ Detailed View\n\n" "# Changes\n\n" + "> [!NOTE] \n" + "> This release follows `1443.10`.\n\n" "## Software Component Versions\n\n" "```\ncontainerd 1.0\n```\n\n" "```text\nunclosed\n" @@ -112,6 +143,7 @@ def test_generated_release_page_passes_gldq(self, tmp_path): rule_ids = {finding.rule_id for finding in findings} for rule_id in ( + "CALLOUT-GITHUB-STYLE", "CODE-BALANCE", "CODE-LANG", "EMOJI", From f5bd6754348364f096551f0fe19de8ba1a0a96b5 Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Wed, 25 Nov 2026 16:52:43 +0100 Subject: [PATCH 07/15] docs: tag docs-native pages and enforce FM-REPO rule Add github_org: gardenlinux / github_repo: docs to the 24 git-tracked docs-native pages, fix two pages that used github_repo: gardenlinux, and add the FM-REPO gldq error so any page missing github_org/github_repo fails. Exclude the un-editable aggregated pages (python-gardenlinux-lib reference, release notes, home page) from FM-REPO. Signed-off-by: Eike Waldt On-behalf-of: SAP Assisted-by: opencode:claude-opus-4-8 --- .gldq-exclude.yml | 7 + .../documentation/adding-repos.md | 2 + .../documentation/aggregation-architecture.md | 2 + .../documentation/auto-glossary.md | 2 + .../documentation/ci-architecture.md | 2 + .../documentation/ci-workflows-reference.md | 2 + .../documentation/configuration.md | 2 + .../documentation/documentation_workflow.md | 2 + docs/contributing/documentation/features.md | 162 ----------- docs/contributing/documentation/index.md | 2 + docs/contributing/documentation/technical.md | 2 + docs/contributing/documentation/testing.md | 2 + .../documentation/vitepress-features.md | 2 + .../documentation/working-locally.md | 2 + .../documentation/writing_good_docs.md | 2 + docs/contributing/index.md | 2 + docs/explanation/history.md | 2 +- docs/explanation/index.md | 2 + docs/how-to/index.md | 2 + docs/how-to/reporting-issues.md | 2 + docs/introduction/index.md | 2 + docs/reference/glossary.md | 2 + docs/reference/index.md | 2 + docs/reference/supporting_tools/index.md | 2 + docs/tutorials/index.md | 2 + src/gldq.py | 133 +++++++-- tests/unit/test_gldq.py | 256 +++++++++++++++++- 27 files changed, 409 insertions(+), 195 deletions(-) delete mode 100644 docs/contributing/documentation/features.md diff --git a/.gldq-exclude.yml b/.gldq-exclude.yml index 519e401..bea5708 100644 --- a/.gldq-exclude.yml +++ b/.gldq-exclude.yml @@ -17,3 +17,10 @@ exclude: - "docs/reference/adr/0014-enforce-pr-references-in-commits.md" - "docs/reference/adr/0035-cname-flavor-artifact-naming.md" - "docs/reference/adr/install.md" + - rules: + - "FM-REPO" + paths: + - "docs/index.md" + - "docs/reference/python-gardenlinux-lib-api.md" + - "docs/reference/python-gardenlinux-lib-cli.md" + - "docs/reference/releases/release-notes/**" diff --git a/docs/contributing/documentation/adding-repos.md b/docs/contributing/documentation/adding-repos.md index 6eb71ad..5f8ac1f 100644 --- a/docs/contributing/documentation/adding-repos.md +++ b/docs/contributing/documentation/adding-repos.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/technical.md - /contributing/documentation/testing.md - /contributing/documentation/vitepress-features.md +github_org: gardenlinux +github_repo: docs --- # Adding Repositories to Documentation Aggregation diff --git a/docs/contributing/documentation/aggregation-architecture.md b/docs/contributing/documentation/aggregation-architecture.md index bc72030..0ce6382 100644 --- a/docs/contributing/documentation/aggregation-architecture.md +++ b/docs/contributing/documentation/aggregation-architecture.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/technical.md - /contributing/documentation/testing.md - /contributing/documentation/vitepress-features.md +github_org: gardenlinux +github_repo: docs --- # Documentation Aggregation Architecture diff --git a/docs/contributing/documentation/auto-glossary.md b/docs/contributing/documentation/auto-glossary.md index 1552113..21de445 100644 --- a/docs/contributing/documentation/auto-glossary.md +++ b/docs/contributing/documentation/auto-glossary.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/technical.md - /contributing/documentation/testing.md - /contributing/documentation/vitepress-features.md +github_org: gardenlinux +github_repo: docs --- # Auto Glossary diff --git a/docs/contributing/documentation/ci-architecture.md b/docs/contributing/documentation/ci-architecture.md index 3d79f24..872a70c 100644 --- a/docs/contributing/documentation/ci-architecture.md +++ b/docs/contributing/documentation/ci-architecture.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/technical.md - /contributing/documentation/testing.md - /contributing/documentation/vitepress-features.md +github_org: gardenlinux +github_repo: docs --- # Documentation CI Architecture diff --git a/docs/contributing/documentation/ci-workflows-reference.md b/docs/contributing/documentation/ci-workflows-reference.md index 643b4f2..99a1bf7 100644 --- a/docs/contributing/documentation/ci-workflows-reference.md +++ b/docs/contributing/documentation/ci-workflows-reference.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/technical.md - /contributing/documentation/testing.md - /contributing/documentation/vitepress-features.md +github_org: gardenlinux +github_repo: docs --- # Documentation CI Workflows Reference diff --git a/docs/contributing/documentation/configuration.md b/docs/contributing/documentation/configuration.md index ff72caf..c944f1f 100644 --- a/docs/contributing/documentation/configuration.md +++ b/docs/contributing/documentation/configuration.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/technical.md - /contributing/documentation/testing.md - /contributing/documentation/vitepress-features.md +github_org: gardenlinux +github_repo: docs --- # Documentation Aggregation Configuration Reference diff --git a/docs/contributing/documentation/documentation_workflow.md b/docs/contributing/documentation/documentation_workflow.md index 65cc75c..3431900 100644 --- a/docs/contributing/documentation/documentation_workflow.md +++ b/docs/contributing/documentation/documentation_workflow.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/technical.md - /contributing/documentation/testing.md - /contributing/documentation/vitepress-features.md +github_org: gardenlinux +github_repo: docs --- # Documenting Garden Linux diff --git a/docs/contributing/documentation/features.md b/docs/contributing/documentation/features.md deleted file mode 100644 index c869350..0000000 --- a/docs/contributing/documentation/features.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: "Contributing Features" -description: "How to write a feature README and info.yaml for Garden Linux features" -related_topics: - - /how-to/custom-feature - - /reference/features/ - - /explanation/features -github_org: gardenlinux -github_repo: gardenlinux -github_source_path: docs/contributing/documentation/features.md -github_target_path: docs/contributing/documentation/features.md ---- - - -# Contributing Features - -Every feature under `features/` must have a `README.md` that describes what the -feature does, which files it provides, and how it relates to other features. This -page defines the authoring standard for those READMEs. - -It does not talk in-depth about the builder feature `info.yaml`, read the -[`info.yaml` file structure](/reference/features/#info-yaml-file-structure) to get -familiar. -For the file-type semantics of `pkg.include`, `exec.config`, `file.include` and -the other builder file types, see the [feature file reference](/reference/features/) -To get to know feature types (`platform`, `element`, `flag`), the dependency graph and -composition rules, see [Features](/explanation/features). - -## Scaffolding the Files table - -Run the scaffold script to generate a `### Files` table and a `### Related features` -skeleton for a given feature: - -```bash -bin/gl-feature-readme-scaffold features/ -``` - -Paste the output into the README, then fill in the Purpose stubs and the prose -sections. The script reads `info.yaml` for `type` and dependency lists, walks the -feature directory for files (excluding `README.md`), and prints stub Purpose entries -pre-linked to the [feature file reference](/reference/features/). - -## Standard README structure - -Each feature README must follow this template. Each file in the `### Files` table -links to the file on GitHub (latest `main`); the builder file-type reference, if -applicable, follows as `([ref](…))`. - -```markdown ---- -title: "Feature: " -related_topics: - - /how-to/custom-feature - - /reference/features/ - - /explanation/features -github_org: gardenlinux -github_repo: gardenlinux -github_source_path: features//README.md -github_target_path: docs/reference/features/.md ---- - -## Feature: - -### Description -One or two sentences on what this feature does, in user-facing terms. -Link glossary terms on first use, e.g. -[platform](/reference/glossary.html#platform), -[flavor](/reference/glossary.html#flavor). - -### What it does -Expanded description of the capability or configuration this feature adds to -the image. Reference related docs where useful. - -### How it works - - -### Files -Files present in this feature and their purpose. -See the [feature file reference](/reference/features/) for the semantics of -each file type. - -| File | Purpose | -|---|---| -| [`info.yaml`](/reference/features/#info-yaml-file-structure) | Declares `type: `. | -| [`pkg.include`](/reference/features/#pkg-include) | Installs ``. | -| [`exec.config`](https://github.com/gardenlinux/gardenlinux/blob/main/features//exec.config) ([ref](/reference/features/#exec-config-exec-early-exec-late-exec-post)) | | -| [`file.include/etc/example.conf`](https://github.com/gardenlinux/gardenlinux/blob/main/features//file.include/etc/example.conf) ([`file.include`](/reference/features/#file-include)) | | -| ... | ... | - -### Related features - -- [``](/reference/features/) β€” - - - -### Further reading - - -## Related topics - - -``` - -## Section rules - -| Section | Mandatory | Notes | -|---|---|---| -| Frontmatter | yes | Never change `github_target_path` | -| `### Description` | yes | Plain prose; no `` tag | -| `### What it does` | yes | Replaces old `### Features` | -| `### How it works` | no | Only for non-trivial behavior | -| `### Files` | yes | Files only (no directory rows); link file types | -| `### Related features` | yes | State "none" if feature has no relationships | -| `### Further reading` | no | Recommended; always include if there are relevant docs | - -## Inline linking rules - -Every backtick-quoted feature name or file name in prose must be a hyperlink. - -**Other features:** link to the rendered reference page. - -```markdown -[`cloud`](/reference/features/cloud) -[`_prod`](/reference/features/_prod) -``` - -Do not link a feature's own name when it refers to itself β€” a self-link is circular. - -**Top-level feature files** (e.g. `exec.config`, `convert.qcow2`, `fstab`): link to the -file on GitHub. - -```markdown -[`exec.config`](https://github.com/gardenlinux/gardenlinux/blob/main/features//exec.config) -[`convert.qcow2`](https://github.com/gardenlinux/gardenlinux/blob/main/features//convert.qcow2) -``` - -**`file.include` as a concept** (no path component): link to the builder file-type reference. - -```markdown -[`file.include`](/reference/features/#file-include) -``` - -**`initrd.include` directory**: link to the directory tree on GitHub. - -```markdown -[`initrd.include`](https://github.com/gardenlinux/gardenlinux/tree/main/features//initrd.include) -``` - -**Subtree paths** (e.g. `file.include/etc/example.conf` in prose): link directly to -the file on GitHub. - -```markdown -[`file.include/etc/example.conf`](https://github.com/gardenlinux/gardenlinux/blob/main/features//file.include/etc/example.conf) -``` - -## Related topics - - diff --git a/docs/contributing/documentation/index.md b/docs/contributing/documentation/index.md index 259d685..9fb872f 100644 --- a/docs/contributing/documentation/index.md +++ b/docs/contributing/documentation/index.md @@ -2,6 +2,8 @@ title: Documentation description: Everything You Need to Know about Documenting Garde Linux order: 0 +github_org: gardenlinux +github_repo: docs --- # Documentation diff --git a/docs/contributing/documentation/technical.md b/docs/contributing/documentation/technical.md index 6fd080f..129054e 100644 --- a/docs/contributing/documentation/technical.md +++ b/docs/contributing/documentation/technical.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/configuration.md - /contributing/documentation/testing.md - /contributing/documentation/vitepress-features.md +github_org: gardenlinux +github_repo: docs --- # Documentation Aggregation Technical Reference diff --git a/docs/contributing/documentation/testing.md b/docs/contributing/documentation/testing.md index 0605787..b896047 100644 --- a/docs/contributing/documentation/testing.md +++ b/docs/contributing/documentation/testing.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/configuration.md - /contributing/documentation/technical.md - /contributing/documentation/vitepress-features.md +github_org: gardenlinux +github_repo: docs --- # Documentation Aggregation Testing Guide diff --git a/docs/contributing/documentation/vitepress-features.md b/docs/contributing/documentation/vitepress-features.md index f62d958..4251ce9 100644 --- a/docs/contributing/documentation/vitepress-features.md +++ b/docs/contributing/documentation/vitepress-features.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/configuration.md - /contributing/documentation/technical.md - /contributing/documentation/testing.md +github_org: gardenlinux +github_repo: docs --- # VitePress Features and Customizations diff --git a/docs/contributing/documentation/working-locally.md b/docs/contributing/documentation/working-locally.md index 088f095..8391c3f 100644 --- a/docs/contributing/documentation/working-locally.md +++ b/docs/contributing/documentation/working-locally.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/technical.md - /contributing/documentation/testing.md - /contributing/documentation/vitepress-features.md +github_org: gardenlinux +github_repo: docs --- # Contributing to the Garden Linux Documentation diff --git a/docs/contributing/documentation/writing_good_docs.md b/docs/contributing/documentation/writing_good_docs.md index e598dad..c7909d5 100644 --- a/docs/contributing/documentation/writing_good_docs.md +++ b/docs/contributing/documentation/writing_good_docs.md @@ -13,6 +13,8 @@ related_topics: - /contributing/documentation/technical.md - /contributing/documentation/testing.md - /contributing/documentation/vitepress-features.md +github_org: gardenlinux +github_repo: docs --- # Documentation Quality Markers diff --git a/docs/contributing/index.md b/docs/contributing/index.md index ad4c539..e805b37 100644 --- a/docs/contributing/index.md +++ b/docs/contributing/index.md @@ -2,6 +2,8 @@ title: Contributing description: Guidelines and information for contributing to Garden Linux order: 6 +github_org: gardenlinux +github_repo: docs --- # Contributing diff --git a/docs/explanation/history.md b/docs/explanation/history.md index 8a4d5eb..0dbe59a 100644 --- a/docs/explanation/history.md +++ b/docs/explanation/history.md @@ -12,7 +12,7 @@ related_topics: - /explanation/secure-boot.md order: 1 github_org: gardenlinux -github_repo: gardenlinux +github_repo: docs github_source_path: docs/explanation/history.md github_target_path: docs/explanation/history.md --- diff --git a/docs/explanation/index.md b/docs/explanation/index.md index 0c613ae..4c848ea 100644 --- a/docs/explanation/index.md +++ b/docs/explanation/index.md @@ -2,6 +2,8 @@ title: Explanation description: Understanding-oriented articles that clarify and illuminate concepts order: 4 +github_org: gardenlinux +github_repo: docs --- # Explanation diff --git a/docs/how-to/index.md b/docs/how-to/index.md index c91a06c..15ccd80 100644 --- a/docs/how-to/index.md +++ b/docs/how-to/index.md @@ -2,6 +2,8 @@ title: How-To Guides description: Task-oriented guides that show you how to solve specific problems order: 3 +github_org: gardenlinux +github_repo: docs --- # How-To Guides diff --git a/docs/how-to/reporting-issues.md b/docs/how-to/reporting-issues.md index 1c404fa..681e150 100644 --- a/docs/how-to/reporting-issues.md +++ b/docs/how-to/reporting-issues.md @@ -2,6 +2,8 @@ title: Reporting Issues description: How to report issues when working with garden linux order: 999 +github_org: gardenlinux +github_repo: docs --- # Reporting Issues diff --git a/docs/introduction/index.md b/docs/introduction/index.md index 9e16631..58f6b7c 100644 --- a/docs/introduction/index.md +++ b/docs/introduction/index.md @@ -2,6 +2,8 @@ title: "Introduction" description: "How Garden Linux documentation is organized" order: 1 +github_org: gardenlinux +github_repo: docs --- # Garden Linux diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md index 0033009..1cd505f 100644 --- a/docs/reference/glossary.md +++ b/docs/reference/glossary.md @@ -1,6 +1,8 @@ --- title: "Glossary" order: 1 +github_org: gardenlinux +github_repo: docs --- # Glossary diff --git a/docs/reference/index.md b/docs/reference/index.md index 8e2dca1..83e0cab 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -2,6 +2,8 @@ title: Reference description: Information-oriented technical descriptions and specifications order: 5 +github_org: gardenlinux +github_repo: docs --- # Reference diff --git a/docs/reference/supporting_tools/index.md b/docs/reference/supporting_tools/index.md index 385db0f..bbf416e 100644 --- a/docs/reference/supporting_tools/index.md +++ b/docs/reference/supporting_tools/index.md @@ -2,6 +2,8 @@ title: Supporting Tools description: Documentation of several Garden Linux related Tools order: 1 +github_org: gardenlinux +github_repo: docs --- # Supporting Tools diff --git a/docs/tutorials/index.md b/docs/tutorials/index.md index 0d1508d..a3b38e9 100644 --- a/docs/tutorials/index.md +++ b/docs/tutorials/index.md @@ -2,6 +2,8 @@ title: Tutorials description: Learning-oriented guides that take you through a series of steps to complete a project order: 2 +github_org: gardenlinux +github_repo: docs --- # Tutorials diff --git a/src/gldq.py b/src/gldq.py index 85d98fc..83153cd 100755 --- a/src/gldq.py +++ b/src/gldq.py @@ -22,6 +22,7 @@ ERROR = "error" WARNING = "warning" +NO_REPO_GROUP = "(no repo)" SKIP_DIRS = { ".git", @@ -92,6 +93,11 @@ class RuleInfo: "FM-ORDER": RuleInfo( "FM-ORDER", WARNING, "Front matter order must be an integer when present" ), + "FM-REPO": RuleInfo( + "FM-REPO", + ERROR, + "Front matter must include github_org and github_repo", + ), "FM-RELATED": RuleInfo( "FM-RELATED", ERROR, "related_topics must be a list of existing documents" ), @@ -159,6 +165,7 @@ class Finding: line: int | None column: int | None message: str + group: str = "(no repo)" @property def sort_key(self) -> tuple[str, int, int, str]: @@ -708,6 +715,10 @@ def _finding( message: str, ) -> Finding: rule = RULES[rule_id] + frontmatter = document.frontmatter or {} + org = frontmatter.get("github_org") + repo = frontmatter.get("github_repo") + group = f"{org}/{repo}" if org and repo else NO_REPO_GROUP return Finding( rule_id=rule_id, severity=rule.severity, @@ -715,6 +726,7 @@ def _finding( line=line, column=column, message=message, + group=group, ) def check_frontmatter(document: Document) -> Iterator[Finding]: @@ -790,6 +802,28 @@ def check_frontmatter(document: Document) -> Iterator[Finding]: f"related_topics target not found: {reference}", ) +def check_repo(document: Document) -> Iterator[Finding]: + """Require github_org and github_repo front matter.""" + if document.is_home or document.is_excluded: + return + + frontmatter = document.frontmatter or {} + org = frontmatter.get("github_org") + repo = frontmatter.get("github_repo") + if ( + not isinstance(org, str) + or not org.strip() + or not isinstance(repo, str) + or not repo.strip() + ): + yield _finding( + document, + "FM-REPO", + 1, + 1, + "Missing github_org or github_repo in front matter", + ) + def check_headings(document: Document) -> Iterator[Finding]: """Check heading structure.""" level_one = [heading for heading in document.headings if heading.level == 1] @@ -1061,6 +1095,7 @@ def check_callouts(document: Document) -> Iterator[Finding]: CHECKS.extend( [ check_frontmatter, + check_repo, check_headings, check_code, check_images, @@ -1072,6 +1107,34 @@ def check_callouts(document: Document) -> Iterator[Finding]: ) +def _group_findings( + findings: Sequence[Finding], +) -> list[tuple[str, list[tuple[Path, list[Finding]]]]]: + """Group findings by github_org/github_repo, then by filename. + + Groups are sorted alphabetically with the "(no repo)" group last. Files + within each group are sorted alphabetically by path, and findings within + each file retain their sort_key ordering. + """ + by_group: dict[str, dict[Path, list[Finding]]] = {} + for finding in findings: + files = by_group.setdefault(finding.group, {}) + files.setdefault(finding.path, []).append(finding) + + def group_sort_key(label: str) -> tuple[bool, str]: + return (label == NO_REPO_GROUP, label) + + grouped: list[tuple[str, list[tuple[Path, list[Finding]]]]] = [] + for label in sorted(by_group, key=group_sort_key): + files = by_group[label] + file_entries = [ + (path, sorted(files[path], key=lambda item: item.sort_key)) + for path in sorted(files, key=lambda item: item.as_posix()) + ] + grouped.append((label, file_entries)) + return grouped + + def _counts(findings: Sequence[Finding]) -> tuple[int, int]: errors = sum(1 for finding in findings if finding.severity == ERROR) warnings = sum(1 for finding in findings if finding.severity == WARNING) @@ -1103,13 +1166,24 @@ def format_text( exclude_file: Path | None = None, ) -> str: """Format findings as human-readable text.""" - lines = [ - f"{_format_location(finding)}: {finding.severity} " - f"{finding.rule_id}: {finding.message}" - for finding in findings - ] + lines: list[str] = [] + for label, file_entries in _group_findings(findings): + if lines: + lines.append("") + lines.append(f"## {label}") + for path, file_findings in file_entries: + lines.append("") + lines.append(f"{path.as_posix()}:") + for finding in file_findings: + lines.append( + f" {_format_location(finding)}: {finding.severity} " + f"{finding.rule_id}: {finding.message}" + ) + if not lines: lines.append("No documentation quality findings.") + else: + lines.append("") errors, warnings = _counts(findings) summary = f"{errors} error(s), {warnings} warning(s) in {file_count} file(s)" @@ -1144,16 +1218,27 @@ def format_json( "excluded": excluded, "exclude_file": exclude_file.as_posix() if exclude_file else None, }, - "findings": [ + "groups": [ { - "path": finding.path.as_posix(), - "line": finding.line, - "column": finding.column, - "rule": finding.rule_id, - "severity": finding.severity, - "message": finding.message, + "group": label, + "files": [ + { + "path": path.as_posix(), + "findings": [ + { + "line": finding.line, + "column": finding.column, + "rule": finding.rule_id, + "severity": finding.severity, + "message": finding.message, + } + for finding in file_findings + ], + } + for path, file_findings in file_entries + ], } - for finding in findings + for label, file_entries in _group_findings(findings) ], } return json.dumps(payload, indent=2) @@ -1168,15 +1253,19 @@ def format_github( ) -> str: """Format findings as GitHub Actions workflow annotations.""" lines: list[str] = [] - for finding in findings: - kind = "error" if finding.severity == ERROR else "warning" - properties = [f"file={finding.path}"] - if finding.line is not None: - properties.append(f"line={finding.line}") - if finding.column is not None: - properties.append(f"col={finding.column}") - message = _escape_github(f"[{finding.rule_id}] {finding.message}") - lines.append(f"::{kind} {','.join(properties)}::{message}") + for label, file_entries in _group_findings(findings): + lines.append(f"::group::{_escape_github(label)}") + for _, file_findings in file_entries: + for finding in file_findings: + kind = "error" if finding.severity == ERROR else "warning" + properties = [f"file={finding.path}"] + if finding.line is not None: + properties.append(f"line={finding.line}") + if finding.column is not None: + properties.append(f"col={finding.column}") + message = _escape_github(f"[{finding.rule_id}] {finding.message}") + lines.append(f"::{kind} {','.join(properties)}::{message}") + lines.append("::endgroup::") if not lines: lines.append("::notice title=gldq::No documentation quality findings") diff --git a/tests/unit/test_gldq.py b/tests/unit/test_gldq.py index 77c43a7..47dcdf7 100644 --- a/tests/unit/test_gldq.py +++ b/tests/unit/test_gldq.py @@ -15,7 +15,13 @@ def write_doc(tmp_path: Path, relative: str, content: str) -> Path: def make_doc( - body: str, frontmatter: str = "title: Page\ndescription: A test page\n" + body: str, + frontmatter: str = ( + "title: Page\n" + "description: A test page\n" + "github_org: gardenlinux\n" + "github_repo: docs\n" + ), ) -> str: """Build a markdown document with default valid front matter.""" return f"---\n{frontmatter}---\n\n{body}" @@ -25,7 +31,13 @@ def make_release_note(body: str = "Chart πŸ“Š\n") -> str: """Build a valid release note document with a trailing RelatedTopics.""" return make_doc( f"# Release\n\n{body}\n\n", - frontmatter="title: Release\ndescription: Release notes\nrelated_topics: []\n", + frontmatter=( + "title: Release\n" + "description: Release notes\n" + "github_org: gardenlinux\n" + "github_repo: docs\n" + "related_topics: []\n" + ), ) @@ -47,6 +59,22 @@ def rule_ids(findings: list[gldq.Finding]) -> list[str]: return [finding.rule_id for finding in findings] +def flatten_json_findings(payload: dict) -> list[dict]: + """Flatten the grouped JSON payload into a flat list of findings. + + Each finding dict is augmented with its ``group`` and ``path`` for + assertions that predate the grouped output structure. + """ + flattened: list[dict] = [] + for group in payload["groups"]: + for file_entry in group["files"]: + for finding in file_entry["findings"]: + flattened.append( + {**finding, "group": group["group"], "path": file_entry["path"]} + ) + return flattened + + class TestValidDocuments: def test_valid_index_page_has_no_findings(self, tmp_path): content = make_doc( @@ -425,7 +453,7 @@ def test_default_exclude_file_excludes_release_note_emoji( payload = json.loads(capsys.readouterr().out) assert payload["summary"]["excluded"] == 1 assert payload["summary"]["warnings"] == 0 - assert payload["findings"] == [] + assert flatten_json_findings(payload) == [] def test_exclusion_is_scoped_to_rule_and_path(self, tmp_path, monkeypatch, capsys): self.write_exclude( @@ -451,7 +479,7 @@ def test_exclusion_is_scoped_to_rule_and_path(self, tmp_path, monkeypatch, capsy assert payload["summary"]["excluded"] == 1 findings_by_path: dict[str, list[str]] = {} - for finding in payload["findings"]: + for finding in flatten_json_findings(payload): findings_by_path.setdefault(finding["path"], []).append(finding["rule"]) release_rules = next( @@ -600,7 +628,9 @@ def test_no_exclude_file_disables_autoload(self, tmp_path, monkeypatch, capsys): assert gldq.main(["docs", "--no-exclude-file", "--format", "json"]) == 0 payload = json.loads(capsys.readouterr().out) assert payload["summary"]["excluded"] == 0 - assert any(finding["rule"] == "EMOJI" for finding in payload["findings"]) + assert any( + finding["rule"] == "EMOJI" for finding in flatten_json_findings(payload) + ) def test_custom_exclude_file(self, tmp_path, capsys): path = self.write_exclude( @@ -671,7 +701,11 @@ def test_excluded_count_in_github_output(self, tmp_path, monkeypatch, capsys): class TestCli: def test_warning_only_exit_codes(self, tmp_path): - path = write_doc(tmp_path, "docs/page.md", "---\norder: 1\n---\n\n# Page\n") + path = write_doc( + tmp_path, + "docs/page.md", + "---\norder: 1\ngithub_org: gardenlinux\ngithub_repo: docs\n---\n\n# Page\n", + ) assert gldq.main([str(path), "--no-exclude-file"]) == 0 assert gldq.main([str(path), "--no-exclude-file", "--strict"]) == 1 @@ -704,17 +738,25 @@ def test_disable_cli_rule(self, tmp_path): ) def test_json_output(self, tmp_path, capsys): - path = write_doc(tmp_path, "docs/page.md", "---\norder: 1\n---\n\n# Page\n") + path = write_doc( + tmp_path, + "docs/page.md", + "---\norder: 1\ngithub_org: gardenlinux\ngithub_repo: docs\n---\n\n# Page\n", + ) assert gldq.main([str(path), "--no-exclude-file", "--format", "json"]) == 0 payload = json.loads(capsys.readouterr().out) assert payload["tool"] == "gldq" assert payload["name"] == "Garden Linux Docs Quality" assert payload["summary"]["files"] == 1 assert payload["summary"]["excluded"] == 0 - assert isinstance(payload["findings"], list) + assert isinstance(payload["groups"], list) def test_github_output(self, tmp_path, capsys): - path = write_doc(tmp_path, "docs/page.md", "---\norder: 1\n---\n\n# Page\n") + path = write_doc( + tmp_path, + "docs/page.md", + "---\norder: 1\ngithub_org: gardenlinux\ngithub_repo: docs\n---\n\n# Page\n", + ) assert gldq.main([str(path), "--no-exclude-file", "--format", "github"]) == 0 output = capsys.readouterr().out assert "::warning" in output @@ -724,6 +766,7 @@ def test_list_rules(self, capsys): assert gldq.main(["--list-rules"]) == 0 output = capsys.readouterr().out assert "FM-YAML" in output + assert "FM-REPO" in output assert "RELATED-TOPICS-PRESENT" in output assert "CALLOUT-INVALID-TYPE" in output assert "CALLOUT-GITHUB-STYLE" in output @@ -743,6 +786,8 @@ def test_single_file_infers_docs_root_for_related_topics(self, tmp_path): frontmatter=( "title: Page\n" "description: Page\n" + "github_org: gardenlinux\n" + "github_repo: docs\n" "related_topics:\n" " - /target.md\n" ), @@ -835,7 +880,7 @@ def test_unclosed_container_is_an_error(self, tmp_path): if finding.rule_id == "CALLOUT-UNCLOSED" ] assert len(findings) == 1 - assert findings[0].line == 8 + assert findings[0].line == 10 def test_suppression_comment_is_honored(self, tmp_path): content = make_doc( @@ -853,3 +898,194 @@ def test_path_matches_wildcard_and_dot_prefix(self): assert not gldq._path_matches( "docs/reference/other/a.md", "./reference/features/**" ) + + +class TestGrouping: + def _finding(self, path, group, rule="FM-TITLE", line=1, column=1): + return gldq.Finding( + rule_id=rule, + severity=gldq.WARNING, + path=Path(path), + line=line, + column=column, + message="message", + group=group, + ) + + def test_group_is_derived_from_frontmatter(self, tmp_path): + findings = find( + tmp_path, + make_doc( + "# Page\n", + frontmatter=( + "title: Page\n" + "description: A page\n" + "github_org: gardenlinux\n" + "github_repo: builder\n" + ), + ), + ) + assert findings + assert all(f.group == "gardenlinux/builder" for f in findings) + + def test_group_defaults_to_no_repo(self, tmp_path): + findings = find( + tmp_path, + make_doc("# Page\n", frontmatter="title: Page\ndescription: A page\n"), + ) + assert findings + assert all(f.group == gldq.NO_REPO_GROUP for f in findings) + + def test_partial_frontmatter_falls_back_to_no_repo(self, tmp_path): + findings = find( + tmp_path, + make_doc( + "# Page\n", + frontmatter=( + "title: Page\n" + "description: A page\n" + "github_org: gardenlinux\n" + ), + ), + ) + assert findings + assert all(f.group == gldq.NO_REPO_GROUP for f in findings) + + def test_group_findings_orders_groups_and_files(self): + findings = [ + self._finding("docs/z.md", "gardenlinux/builder"), + self._finding("docs/a.md", "gardenlinux/builder"), + self._finding("docs/b.md", "gardenlinux/daily"), + self._finding("docs/c.md", gldq.NO_REPO_GROUP), + ] + grouped = gldq._group_findings(findings) + labels = [label for label, _ in grouped] + assert labels == [ + "gardenlinux/builder", + "gardenlinux/daily", + gldq.NO_REPO_GROUP, + ] + builder_files = [path.as_posix() for path, _ in grouped[0][1]] + assert builder_files == ["docs/a.md", "docs/z.md"] + + def test_group_findings_keeps_sort_key_within_file(self): + findings = [ + self._finding("docs/a.md", "org/repo", rule="CODE-LANG", line=5), + self._finding("docs/a.md", "org/repo", rule="FM-TITLE", line=1), + ] + grouped = gldq._group_findings(findings) + _, file_findings = grouped[0][1][0] + assert [f.line for f in file_findings] == [1, 5] + + def test_text_output_is_grouped(self, tmp_path, monkeypatch, capsys): + write_doc( + tmp_path, + "docs/a.md", + make_doc( + "# A\n", + frontmatter=( + "title: A\n" + "description: Page A\n" + "github_org: gardenlinux\n" + "github_repo: builder\n" + ), + ), + ) + write_doc( + tmp_path, + "docs/b.md", + make_doc("# B\n", frontmatter="title: B\ndescription: Page B\n"), + ) + monkeypatch.chdir(tmp_path) + assert gldq.main(["docs", "--no-exclude-file"]) != 2 + output = capsys.readouterr().out + assert "## gardenlinux/builder" in output + assert f"## {gldq.NO_REPO_GROUP}" in output + assert output.index("## gardenlinux/builder") < output.index( + f"## {gldq.NO_REPO_GROUP}" + ) + + def test_json_output_is_grouped(self, tmp_path, monkeypatch, capsys): + write_doc( + tmp_path, + "docs/a.md", + make_doc( + "# A\n", + frontmatter=( + "title: A\n" + "description: Page A\n" + "github_org: gardenlinux\n" + "github_repo: builder\n" + ), + ), + ) + write_doc( + tmp_path, + "docs/b.md", + make_doc("# B\n", frontmatter="title: B\ndescription: Page B\n"), + ) + monkeypatch.chdir(tmp_path) + gldq.main(["docs", "--no-exclude-file", "--format", "json"]) + payload = json.loads(capsys.readouterr().out) + assert "findings" not in payload + labels = [group["group"] for group in payload["groups"]] + assert labels == ["gardenlinux/builder", gldq.NO_REPO_GROUP] + builder = payload["groups"][0]["files"][0] + assert builder["path"] == "docs/a.md" + assert "path" not in builder["findings"][0] + + def test_github_output_wraps_groups(self, tmp_path, monkeypatch, capsys): + write_doc( + tmp_path, + "docs/b.md", + make_doc("# B\n", frontmatter="title: B\ndescription: Page B\n"), + ) + monkeypatch.chdir(tmp_path) + gldq.main(["docs", "--no-exclude-file", "--format", "github"]) + output = capsys.readouterr().out + assert f"::group::{gldq.NO_REPO_GROUP}" in output + assert "::endgroup::" in output + + +class TestRepo: + def _no_repo_doc(self, body: str = "# Page\n") -> str: + return make_doc(body, frontmatter="title: Page\ndescription: A page\n") + + def test_missing_repo_fields_is_an_error(self, tmp_path): + findings = find(tmp_path, self._no_repo_doc()) + repo_findings = [f for f in findings if f.rule_id == "FM-REPO"] + assert len(repo_findings) == 1 + assert repo_findings[0].severity == gldq.ERROR + assert repo_findings[0].group == gldq.NO_REPO_GROUP + + def test_both_repo_fields_present_passes(self, tmp_path): + findings = find(tmp_path, make_doc("# Page\n")) + assert "FM-REPO" not in rule_ids(findings) + + def test_missing_only_repo_is_an_error(self, tmp_path): + content = make_doc( + "# Page\n", + frontmatter=( + "title: Page\ndescription: A page\ngithub_org: gardenlinux\n" + ), + ) + assert "FM-REPO" in rule_ids(find(tmp_path, content)) + + def test_home_page_is_exempt(self, tmp_path): + content = "---\nlayout: home\nhero:\n name: Test\n---\n\nWelcome.\n" + assert "FM-REPO" not in rule_ids(find(tmp_path, content)) + + def test_excluded_page_is_exempt(self, tmp_path): + content = make_doc( + "# Page\n", + frontmatter="title: Page\ndescription: A page\nexclude: true\n", + ) + assert "FM-REPO" not in rule_ids(find(tmp_path, content)) + + def test_missing_repo_fails_run_as_error(self, tmp_path, monkeypatch, capsys): + write_doc(tmp_path, "docs/page.md", self._no_repo_doc()) + monkeypatch.chdir(tmp_path) + assert gldq.main(["docs", "--no-exclude-file"]) == 1 + output = capsys.readouterr().out + assert f"## {gldq.NO_REPO_GROUP}" in output + assert "FM-REPO" in output From 2c47fb8ed0c560a5d590d5811b448639f24129ee Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Thu, 26 Nov 2026 09:53:30 +0100 Subject: [PATCH 08/15] docs: fix gldq finding Signed-off-by: Eike Waldt On-behalf-of: SAP --- .gldq-exclude.yml | 13 ++++++++++++- .../documentation/aggregation-architecture.md | 4 ++-- docs/contributing/documentation/auto-glossary.md | 10 +++++++--- .../documentation/ci-workflows-reference.md | 2 +- docs/contributing/documentation/technical.md | 2 +- docs/contributing/documentation/testing.md | 2 +- docs/contributing/documentation/working-locally.md | 4 +++- docs/explanation/history.md | 6 +++++- docs/how-to/reporting-issues.md | 7 +++++++ docs/reference/glossary.md | 11 ++++++----- 10 files changed, 45 insertions(+), 16 deletions(-) diff --git a/.gldq-exclude.yml b/.gldq-exclude.yml index bea5708..b109d29 100644 --- a/.gldq-exclude.yml +++ b/.gldq-exclude.yml @@ -11,6 +11,13 @@ exclude: - "RELATED-TOPICS-PRESENT" paths: - "docs/reference/adr/**" + - rules: + - "RELATED-TOPICS-PRESENT" + paths: + - "docs/contributing/security.md" + - "docs/contributing/workflow.md" + - "docs/reference/flavor-matrix.md" + - "docs/reference/glossary.md" - rules: - "CODE-LANG" paths: @@ -21,6 +28,10 @@ exclude: - "FM-REPO" paths: - "docs/index.md" + - "docs/reference/releases/release-notes/**" + - rules: + - "FM-REPO" + - "RELATED-TOPICS-PRESENT" + paths: - "docs/reference/python-gardenlinux-lib-api.md" - "docs/reference/python-gardenlinux-lib-cli.md" - - "docs/reference/releases/release-notes/**" diff --git a/docs/contributing/documentation/aggregation-architecture.md b/docs/contributing/documentation/aggregation-architecture.md index 0ce6382..c6bbf6d 100644 --- a/docs/contributing/documentation/aggregation-architecture.md +++ b/docs/contributing/documentation/aggregation-architecture.md @@ -285,7 +285,7 @@ This fetches the latest from `ref` and updates commit locks. ### Repository β†’ Temporary Directory -``` +```text Source Repo Temp Directory β”œβ”€β”€ docs/ β†’ /tmp/xyz/repo-name/ β”‚ β”œβ”€β”€ tutorials/ β”œβ”€β”€ tutorials/ @@ -297,7 +297,7 @@ Source Repo Temp Directory ### Temporary Directory β†’ Docs Output -``` +```text Temp Directory Docs Output /tmp/xyz/repo-name/ β†’ β”œβ”€β”€ tutorials/ docs/ diff --git a/docs/contributing/documentation/auto-glossary.md b/docs/contributing/documentation/auto-glossary.md index 21de445..fec90ce 100644 --- a/docs/contributing/documentation/auto-glossary.md +++ b/docs/contributing/documentation/auto-glossary.md @@ -117,7 +117,7 @@ Auto-linking creates links for glossary terms without requiring explicit markers With auto-linking enabled, input text: -``` +```text Deploy Gardenlinux on AWS using KVM virtualization. ``` @@ -159,7 +159,7 @@ make glossary-check **Term not found:** -``` +```text [Warning][auto-glossary] Term 'xyz' not found in glossary (referenced in file.md) ``` @@ -167,7 +167,7 @@ The marker remains unchanged. Add the term to the glossary, fix the spelling, or **Anchor collision:** -``` +```text [Warning][auto-glossary] Anchor collision detected: 'Term 1' and 'Term 2' both generate anchor 'term-1-2' ``` @@ -211,3 +211,7 @@ python3 -m pytest tests/unit/test_auto_glossary*.py tests/unit/test_generate_anc ``` Test coverage includes format validation, anchor generation, alias extraction, auto-linking, and integration tests. + +## Related Topics + + diff --git a/docs/contributing/documentation/ci-workflows-reference.md b/docs/contributing/documentation/ci-workflows-reference.md index 99a1bf7..058ab96 100644 --- a/docs/contributing/documentation/ci-workflows-reference.md +++ b/docs/contributing/documentation/ci-workflows-reference.md @@ -463,7 +463,7 @@ The `client_payload` (or `inputs` for manual dispatch) must contain: All automated branches follow the pattern: -``` +```text auto// ``` diff --git a/docs/contributing/documentation/technical.md b/docs/contributing/documentation/technical.md index 129054e..5c28593 100644 --- a/docs/contributing/documentation/technical.md +++ b/docs/contributing/documentation/technical.md @@ -23,7 +23,7 @@ Source code documentation for the documentation aggregation system. ## Source Code Structure -``` +```text src/ β”œβ”€β”€ aggregate.py # CLI entry point β”œβ”€β”€ migration_tracker.py # Standalone utility diff --git a/docs/contributing/documentation/testing.md b/docs/contributing/documentation/testing.md index b896047..2b37285 100644 --- a/docs/contributing/documentation/testing.md +++ b/docs/contributing/documentation/testing.md @@ -23,7 +23,7 @@ Test suite documentation for the documentation aggregation system. ## Test Structure -``` +```text tests/ β”œβ”€β”€ conftest.py # pytest configuration β”œβ”€β”€ fixtures/ # Test data diff --git a/docs/contributing/documentation/working-locally.md b/docs/contributing/documentation/working-locally.md index 8391c3f..7c3c9c3 100644 --- a/docs/contributing/documentation/working-locally.md +++ b/docs/contributing/documentation/working-locally.md @@ -103,6 +103,8 @@ export GH_COM_TOKEN=$(gh auth token --hostname github.com) make aggregate ``` +::: + :::tip You can add the `export` statement to you Shell's configuration file to avoid having to re-export it in different sessions. @@ -210,7 +212,7 @@ make test After aggregation, your docs directory will look like: -``` +```text docs/ β”œβ”€β”€ tutorials/ # Aggregated tutorials β”œβ”€β”€ how-to/ # Aggregated guides diff --git a/docs/explanation/history.md b/docs/explanation/history.md index 0dbe59a..6023006 100644 --- a/docs/explanation/history.md +++ b/docs/explanation/history.md @@ -8,7 +8,7 @@ related_topics: - /explanation/release-hierarchy.md - /reference/releases/release-lifecycle.md - /explanation/architecture.md - - /explanation/compliance.md + - /explanation/compliance-frameworks.md - /explanation/secure-boot.md order: 1 github_org: gardenlinux @@ -109,3 +109,7 @@ replaced without any manual intervention. | Aug 2026 | Licensing/Legal | **License changed to Apache 2.0** β€” the project re-licenses under the Apache License 2.0. | - | | Aug 2026 | Feature | **Cross-version in-place updates** β€” in-place updates across minor and major versions are supported using [`gardenlinux-update`](/reference/features/_usi). | [1877.27](/reference/releases/release-notes/1877-27) / [2150.13.0](/reference/releases/release-notes/2150-13-0) | | Oct 2026 | Feature (Compliance) | **FIPS 140-3 submission** β€” all crypto modules have been successfully submitted to NIST and are now in the review phase. | - | + +## Related Topics + + diff --git a/docs/how-to/reporting-issues.md b/docs/how-to/reporting-issues.md index 681e150..9c29971 100644 --- a/docs/how-to/reporting-issues.md +++ b/docs/how-to/reporting-issues.md @@ -2,6 +2,9 @@ title: Reporting Issues description: How to report issues when working with garden linux order: 999 +related_topics: + - /contributing/workflow.md + - /contributing/documentation/documentation_workflow.md github_org: gardenlinux github_repo: docs --- @@ -50,3 +53,7 @@ and analyze the issue._ ## Documentation Issue? Did you find something to improve in this documentation? [Open a new issue](https://github.com/gardenlinux/docs/issues/new/choose). + +## Related Topics + + diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md index 1cd505f..04b8607 100644 --- a/docs/reference/glossary.md +++ b/docs/reference/glossary.md @@ -1,5 +1,6 @@ --- title: "Glossary" +description: "Lookup definitions for Garden Linux specifc terminology" order: 1 github_org: gardenlinux github_repo: docs @@ -7,7 +8,7 @@ github_repo: docs # Glossary -This glossary provides definitions for Garden Linux-specific terminology. To contribute additional terms or improve existing definitions, visit our [contributing guide](../contributing/index.md). +This glossary provides definitions for Garden Linux specific terminology. To contribute additional terms or improve existing definitions, visit our [contributing guide](../contributing/index.md). **Jump to:** [A](#a) Β· [B](#b) Β· [C](#c) Β· [D](#d) Β· [E](#e) Β· [F](#f) Β· [G](#g) Β· [I](#i) Β· [K](#k) Β· [L](#l) Β· [M](#m) Β· [N](#n) Β· [O](#o) Β· [P](#p) Β· [Q](#q) Β· [R](#r) Β· [S](#s) Β· [T](#t) Β· [U](#u) Β· [V](#v) @@ -35,7 +36,7 @@ The processor architecture for which a Garden Linux image is built. Supported ar The **artifact base name** is the versioned flavor qualified with a short commit hash: -``` +```text {cname}-{arch}-{version}-{short_commit} ``` @@ -65,7 +66,7 @@ The [gardenlinux/builder](https://github.com/gardenlinux/builder) component that A **versioned flavor** is the flavor qualified with a version β€” the string passed to the `./build` script to invoke a build: -``` +```text {cname}-{arch}-{version} ``` @@ -102,7 +103,7 @@ A Garden Linux image optimized for cloud platforms (AWS, Azure, GCP, etc.) with The **cname** is the minimal, canonically-sorted encoding of the feature set β€” and only the feature set. Architecture, version, and commit are not part of the cname: -``` +```text cname = {feature-encoding} ``` @@ -198,7 +199,7 @@ A feature of type `flag` represents a lightweight modifier. Flags are identified A **flavor** is the cname qualified with a target architecture: -``` +```text {cname}-{arch} ``` From 09f058d82b282e625add6a1527e8e2e262fbc0af Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Thu, 26 Nov 2026 11:52:31 +0100 Subject: [PATCH 09/15] chore: update dependencies Signed-off-by: Eike Waldt On-behalf-of: SAP --- requirements.txt | 4 ++-- src/aggregation/flavor_matrix.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements.txt b/requirements.txt index a0547d1..2788f2d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,8 +3,8 @@ black isort pytest pyyaml -glrd @ git+https://github.com/gardenlinux/glrd.git@v5.1.0 -gardenlinux @ git+https://github.com/gardenlinux/python-gardenlinux-lib.git@0.10.24 +glrd @ git+https://github.com/gardenlinux/glrd.git@v5.2.0 +gardenlinux @ git+https://github.com/gardenlinux/python-gardenlinux-lib.git@1.0.6 sphinx sphinx-markdown-builder sphinx-rtd-theme diff --git a/src/aggregation/flavor_matrix.py b/src/aggregation/flavor_matrix.py index ea7ac57..56b41ca 100644 --- a/src/aggregation/flavor_matrix.py +++ b/src/aggregation/flavor_matrix.py @@ -77,7 +77,7 @@ def generate_flavor_matrix_docs(docs_dir: Path, gardenlinux_repo_dir: Path) -> b flavor_base = flavor.replace(f"-{arch}", "") # Explicit features from cname - explicit = FeaturesParser.get_flavor_as_feature_set(flavor_base) + explicit = FeaturesParser.get_cname_as_feature_set(flavor_base) # Full recursive feature set try: From 293c94e6cd636d066575aee86bbb7cbd919a767d Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Thu, 26 Nov 2026 12:25:03 +0100 Subject: [PATCH 10/15] chore: ignore features docs Signed-off-by: Eike Waldt On-behalf-of: SAP --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 248e03b..38309cc 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,7 @@ docs/contributing/** !docs/contributing/documentation/ !docs/contributing/documentation/** !docs/contributing/documentation_workflow.md +docs/contributing/documentation/features.md docs/explanation/** !docs/explanation/index.md !docs/explanation/history.md From 08ac93bee35f5c8daa125e18b3cb0624cae066bd Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Thu, 26 Nov 2026 12:25:25 +0100 Subject: [PATCH 11/15] ci: output human readble logs and github format for gldq Signed-off-by: Eike Waldt On-behalf-of: SAP --- .github/workflows/docs-checks.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docs-checks.yml b/.github/workflows/docs-checks.yml index efa99f9..c8df7e1 100644 --- a/.github/workflows/docs-checks.yml +++ b/.github/workflows/docs-checks.yml @@ -222,5 +222,8 @@ jobs: run: pip install pyyaml - name: Run Garden Linux Docs Quality - continue-on-error: true - run: python3 src/gldq.py docs/ --format github + run: python3 src/gldq.py docs/ --strict + + - name: Publish Garden Linux Docs Quality annotations + if: always() + run: python3 src/gldq.py docs/ --strict --format github From 9348c3879d72c7168838eabaec281d70df8a1e73 Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Thu, 26 Nov 2026 12:31:13 +0100 Subject: [PATCH 12/15] chore: spelling Signed-off-by: Eike Waldt On-behalf-of: SAP --- docs/reference/glossary.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md index 04b8607..3dc5df5 100644 --- a/docs/reference/glossary.md +++ b/docs/reference/glossary.md @@ -1,6 +1,6 @@ --- title: "Glossary" -description: "Lookup definitions for Garden Linux specifc terminology" +description: "Lookup definitions for Garden Linux specific terminology" order: 1 github_org: gardenlinux github_repo: docs From 64b9fb5c7bdb7be4a427447959424a2174414a32 Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Thu, 26 Nov 2026 15:57:38 +0100 Subject: [PATCH 13/15] docs: update writing good docs to include GLDQ Signed-off-by: Eike Waldt On-behalf-of: SAP Assisted-by: opencode:claude-opus-4-8 --- .agents/skills/humanizer/SKILL.md | 122 ++++++++++ .../documentation/writing_good_docs.md | 224 ++++++++++++++---- 2 files changed, 301 insertions(+), 45 deletions(-) create mode 100644 .agents/skills/humanizer/SKILL.md diff --git a/.agents/skills/humanizer/SKILL.md b/.agents/skills/humanizer/SKILL.md new file mode 100644 index 0000000..8b33667 --- /dev/null +++ b/.agents/skills/humanizer/SKILL.md @@ -0,0 +1,122 @@ +--- +name: humanizer +description: > + Rework AI-generated phrasing in Garden Linux documentation. Use for "humanize + this doc", "rework AI phrasing", "remove AI tells", "this reads like it was + written by an LLM", or when editing Markdown under docs/ that shows chatbot or + hype patterns. Provides the full pattern catalog and a minimal-rewrite workflow. +--- + +# Humanizer + +Rework prose that carries AI-generated writing patterns into clear, direct +documentation. The goal is to remove recognizable LLM phrasing without changing +technical meaning. + +This skill is the single source of truth for the AI-phrasing pattern catalog. +The documentation quality guide +(`docs/contributing/documentation/writing_good_docs.md`) summarizes the categories +and links here for the full list and rework guidance. + +## Workflow + +1. Scan the prose (ignore fenced code blocks and front matter). +2. For each suspect sentence, identify a **specific pattern ID** from the catalog + below. If no pattern applies, leave the text unchanged. +3. Rewrite with the smallest possible edit that removes the pattern. +4. Preserve technical meaning. Do not add new claims, numbers, or sources. +5. Keep the result consistent with the project style guide (active voice, concise + sentences, consistent terminology). + +Refuse vague polish: never rewrite "to make it flow better". Every edit must cite +a pattern ID. Reviewers apply the same rule. + +## Pattern catalog + +Each entry gives the rule ID, the trigger, and a before to after example. + +- **`HYPE-OPEN` - Hype openers and filler adjectives** (`delve`, `dive into`, + `embark`, `unlock`, `elevate`, `seamlessly`, `robust`, `comprehensive`, + `cutting-edge`, `powerful`, `leverage`, `harness`, `empower`, `streamline`, + `effortless`, `tapestry`, `intricate`, `interplay`, `realm`, `pivotal`, + `crucial`, `nuanced`, `dynamic`, `multifaceted`, `paradigm`, `synergy`, + `holistic`, `unleash`, `foster`). Example: "This guide will help you unlock the + full potential of..." to "This guide covers..." +- **`TRANS-BLOAT` - Transitional bloat** (`Moreover`, `Furthermore`, + `In conclusion`, `In summary`, `It's worth noting`, `It's important to note`). + Example: "Furthermore, the builder supports..." to "The builder supports..." +- **`PROMO` - Promotional flourish** (`world-class`, `best-in-class`, + `next-generation`, `revolutionary`, `game-changing`, `state-of-the-art`, + `seamless`, `unparalleled`, `unrivaled`, `premier`). Example: "a + next-generation build system" to "a purpose-built build system" +- **`HEDGE` - Contextual hedging openers** (`In today's fast-paced world`, + `In the ever-evolving landscape of`, `As we all know`, `It goes without + saying`). Delete the opener and start with the actual statement. +- **`PRONOUN-OVERREACH` - Presumptuous collective pronouns** (`we've all been + there`, `let's explore together`, `join me on this journey`). Use second person + or neutral framing instead. +- **`RHETQ` - Rhetorical-question openers** (`Ever wondered...?`, `What if I told + you...?`). State the topic directly. +- **`CANONICAL-LINT` - Canonical style anti-patterns** (`please`, `kindly`, + `note that` as filler, ornamental parentheticals such as `(and this is + important)`). Remove the filler; keep the statement. +- **`EM-DASH-DRAMA` - Em-dash as rhetorical pause** - em-dash used before a hype + word or as a dramatic mid-sentence aside (for example `- unlocking`, `- making + it`). Legitimate parenthetical em-dashes are fine. +- **`LEGACY-PUFF` - Significance or legacy claims** (`has left a lasting legacy`, + `has had a profound impact on`, `stands as a testament to`, `remains a + cornerstone of`). Replace with a specific, verifiable statement or delete. +- **`NOTABILITY-PUFF` - Notability flex** (`widely regarded as`, `has gained + recognition`, `experts agree`, `industry leaders have noted`) *(advisory)*. + Cite a source or delete. +- **`ING-BLOAT` - Gerund-chain abstractions** - chains of -ing nouns as subject + or object where a finite verb would be clearer. Example: "Configuring and + deploying involves setting up..." to "To deploy, set up..." +- **`WEASEL` - Vague attributions** (`some say`, `many believe`, `it has been + suggested`, `critics argue`). Name the source or rewrite as a factual claim. +- **`FUTURE-OUTLOOK` - "Challenges and Future Prospects" boilerplate** - section + headings or closing paragraphs following the AI outline pattern (`Looking + Ahead`, `Future Directions`, `The Road Ahead`). Replace with a specific heading + or delete. +- **`COPULA-DODGE` - Copula avoidance** (`serves as`, `functions as`, `acts as`, + `operates as`, `plays the role of` where "is" or a concrete verb suffices). + Example: "serves as the single source of truth" to "is the single source of + truth" +- **`NEG-PARALLEL` - Negative parallelisms** (`not just ... but`, `not only ... + but also`, `more than just`). State what the subject does directly. +- **`RULE-OF-THREE` - Rule-of-three overuse** - exactly three adjectives or nouns + grouped for rhetorical balance rather than precision *(advisory)*. Use the most + precise term. +- **`SYN-CYCLE` - Synonym cycling** - using different words for the same concept + within a short span (for example "build manifest", "build descriptor", "build + specification" for the same thing). Pick one term and use it throughout. +- **`FALSE-RANGE` - False ranges** (`from ... to ...` implying broad coverage from + two arbitrary endpoints). List specific items instead. +- **`BOLD-OVERUSE` - Boldface overuse** - bold applied to adjectives, adverbs, or + transitional words for decoration rather than to mark key terms or critical + warnings. +- **`EMOJI` - Emojis** - any emoji outside a code fence. Delete; replace with a + VitePress callout if semantic meaning is needed. GLDQ also enforces this + automatically via the `EMOJI` rule. +- **`CHATBOT-ARTIFACT` - Chatbot artifacts** (`Certainly!`, `Great question!`, + `As I mentioned`, `I hope this helps`, `Feel free to ask`). Delete entirely. +- **`SYCOPHANT` - Sycophantic tone** (`great job`, `well done`, `excellent + choice`, `congratulations on`). Delete; state the outcome directly. +- **`OVER-HEDGE` - Excessive hedging** - two or more hedges in one clause (`might + possibly`, `could potentially`, `may perhaps`). Use at most one hedge where + genuine uncertainty exists. +- **`GENERIC-CONCLUSION` - Generic positive conclusions** (`By following these + steps`, `Armed with this knowledge`, `You are now ready to`, `You now have a + solid understanding of`). Delete or replace with a concrete next step or link. + +## Filler words + +Filler words (`simply`, `just`, `easy`/`easily`, `actually`, `basically`, +`obviously`) are a separate category governed by the style guide's +banned-filler-word rule. Delete them unless they carry literal meaning. + +## References + +- [Wikipedia: Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing) +- [softaworks/agent-toolkit humanizer skill](https://github.com/softaworks/agent-toolkit/blob/3027f20f3181758385a1bb8c022d4041dfb4de84/skills/humanizer/SKILL.md) +- [blader/humanizer](https://github.com/blader/humanizer/blob/1b48564898e999219882660237fde01bf4843a0f/SKILL.md) diff --git a/docs/contributing/documentation/writing_good_docs.md b/docs/contributing/documentation/writing_good_docs.md index c7909d5..1e30b51 100644 --- a/docs/contributing/documentation/writing_good_docs.md +++ b/docs/contributing/documentation/writing_good_docs.md @@ -26,6 +26,127 @@ These markers can roughly be split into required markers, that every documentation submission should have, and those which are context dependent and therefore optional. +Quality is enforced in two complementary ways: + +- **Automated checks** run in CI and locally. The + [Garden Linux Docs Quality (GLDQ)](#automated-quality-checks-gldq) tool + verifies structural markers, and additional tools cover spelling, dead links, + and inclusive language. +- **Human review** covers everything a machine cannot judge, such as technical + accuracy, readability, and consistent terminology. The + [Documentation Workflow](./documentation_workflow.md) describes who reviews and + how. + +For how to use the custom components and front-matter fields referenced +throughout this guide, see +[VitePress Features](./vitepress-features.md). To rework AI-generated phrasing, +use the [humanizer skill](/.agents/skills/humanizer/SKILL.md) (see +[AI-generated phrasing to avoid](#ai-generated-phrasing-to-avoid)). + +## Automated Quality Checks (GLDQ) + +Garden Linux Docs Quality (GLDQ) is a linter that checks documentation for the +structural markers described in this guide. It runs in CI on every pull request +with `--strict`, which treats warnings as failures and blocks merges until the +findings are resolved. + +### Running GLDQ locally + +Run GLDQ before opening a pull request: + +```bash +# Report findings (warnings do not fail the run) +make docs-check + +# Treat warnings as failures, matching CI +make docs-check-strict + +# Call the tool directly on any path +python3 src/gldq.py docs/ + +# List every rule with its severity +python3 src/gldq.py --list-rules +``` + +Spelling, dead links, and inclusive language are checked by separate tools: +`make spelling`, `make linkcheck`, and `make woke`. + +### Rules + +GLDQ findings have one of two severities. An `error` always fails the run; a +`warning` fails only under `--strict` (and therefore in CI). + +#### Front matter + +| Rule | Severity | What it checks | +| --- | --- | --- | +| `FM-YAML` | error | Front matter must be valid YAML. | +| `FM-TITLE` | warning | Front matter must include a non-empty `title`. | +| `FM-DESC` | warning | Front matter must include a non-empty `description`. | +| `FM-ORDER` | warning | `order` must be an integer when present. | +| `FM-REPO` | error | Front matter must include `github_org` and `github_repo`. | +| `FM-RELATED` | error | `related_topics` must be a list of existing documents. | + +#### Headings + +| Rule | Severity | What it checks | +| --- | --- | --- | +| `H1-ONE` | warning | Document must have exactly one level-1 heading. | +| `H1-EMPTY` | error | Headings must not be empty. | +| `HEAD-SKIP` | warning | Heading levels must not be skipped. | + +#### Code blocks + +| Rule | Severity | What it checks | +| --- | --- | --- | +| `CODE-LANG` | warning | Fenced code blocks must declare a language. | +| `CODE-BALANCE` | error | Fenced code blocks must be closed. | + +#### Media and links + +| Rule | Severity | What it checks | +| --- | --- | --- | +| `IMG-ALT` | error | Images must have non-empty alt text. | +| `LINK-TEXT` | error | Links must use descriptive link text, not "click here". | +| `EMOJI` | warning | Emoji are not allowed outside code fences. | + +#### Components + +| Rule | Severity | What it checks | +| --- | --- | --- | +| `SECTION-INDEX` | error | Section index pages must include ``. | +| `RELATED-TOPICS-END` | error | `` must be the last content block. | +| `RELATED-TOPICS-FM` | error | `` requires `related_topics` in front matter. | +| `RELATED-TOPICS-PRESENT` | warning | Non-index pages should include ``. | + +#### Callouts + +| Rule | Severity | What it checks | +| --- | --- | --- | +| `CALLOUT-INVALID-TYPE` | error | Container type must be `info`, `tip`, `warning`, `danger`, or `details`. | +| `CALLOUT-GITHUB-STYLE` | error | GitHub-style callouts are rejected; use VitePress `:::` syntax. | +| `CALLOUT-UNCLOSED` | error | VitePress containers must be closed with `:::`. | + +### Suppressing and excluding findings + +When a finding does not apply, suppress it inline with a comment rather than +leaving the whole file unchecked: + +```markdown + + + +``` + +`disable-next-line` affects the following line, `disable` affects the rest of +the file from that point, and `disable-file` affects the entire file. Each +directive takes one or more rule IDs. + +Files that cannot be edited in this repository (for example aggregated content) +are handled by the rule-aware exclusion file `.gldq-exclude.yml`, which maps rule +patterns to path patterns. Prefer inline suppressions for authored content and +reserve the exclusion file for generated files. + ## Required Markers ### Accuracy & Completeness @@ -99,40 +220,35 @@ readers to action. #### AI-generated phrasing to avoid -AI-assisted writing introduces recognizable patterns that reduce documentation quality through repetition. Avoid these categories when authoring (see also [Wikipedia: Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing), [softaworks/agent-toolkit humanizer skill](https://github.com/softaworks/agent-toolkit/blob/3027f20f3181758385a1bb8c022d4041dfb4de84/skills/humanizer/SKILL.md), and [blader/humanizer](https://github.com/blader/humanizer/blob/1b48564898e999219882660237fde01bf4843a0f/SKILL.md)): - -:::details Examples of common LLM patterns - -- **`HYPE-OPEN` - Hype openers and filler adjectives** (`delve`, `dive into`, `embark`, `unlock`, `elevate`, `seamlessly`, `robust`, `comprehensive`, `cutting-edge`, `powerful`, `leverage`, `harness`, `empower`, `streamline`, `effortless`, `tapestry`, `intricate`, `interplay`, `realm`, `pivotal`, `crucial`, `nuanced`, `dynamic`, `multifaceted`, `paradigm`, `synergy`, `holistic`, `unleash`, `foster`). Example: "This guide will help you unlock the full potential of..." β†’ "This guide covers..." -- **`TRANS-BLOAT` - Transitional bloat** (`Moreover`, `Furthermore`, `In conclusion`, `In summary`, `It's worth noting`, `It's important to note`). Example: "Furthermore, the builder supports..." β†’ "The builder supports..." -- **`PROMO` - Promotional flourish** (`world-class`, `best-in-class`, `next-generation`, `revolutionary`, `game-changing`, `state-of-the-art`, `seamless`, `unparalleled`, `unrivaled`, `premier`). Example: "a next-generation build system" β†’ "a purpose-built build system" -- **`HEDGE` - Contextual hedging openers** (`In today's fast-paced world`, `In the ever-evolving landscape of`, `As we all know`, `It goes without saying`). Delete the opener and start with the actual statement. -- **`PRONOUN-OVERREACH` - Presumptuous collective pronouns** (`we've all been there`, `let's explore together`, `join me on this journey`). Use second person or neutral framing instead. -- **`RHETQ` - Rhetorical-question openers** (`Ever wondered…?`, `What if I told you…?`). State the topic directly. -- **`CANONICAL-LINT` - Canonical style anti-patterns** (`please`, `kindly`, `note that` as filler, ornamental parentheticals such as `(and this is important)`). Remove the filler; keep the statement. -- **`EM-DASH-DRAMA` - Em-dash as rhetorical pause** β€” em-dash used before a hype word or as a dramatic mid-sentence aside (e.g., `β€” unlocking`, `β€” making it`). Legitimate parenthetical em-dashes are fine. -- **`LEGACY-PUFF` - Significance or legacy claims** (`has left a lasting legacy`, `has had a profound impact on`, `stands as a testament to`, `remains a cornerstone of`). Replace with a specific, verifiable statement or delete. -- **`NOTABILITY-PUFF` - Notability flex** (`widely regarded as`, `has gained recognition`, `experts agree`, `industry leaders have noted`) *(advisory)*. Cite a source or delete. -- **`ING-BLOAT` - Gerund-chain abstractions** β€” chains of -ing nouns as subject or object where a finite verb would be clearer. Example: "Configuring and deploying involves setting up..." β†’ "To deploy, set up..." -- **`WEASEL` - Vague attributions** (`some say`, `many believe`, `it has been suggested`, `critics argue`). Name the source or rewrite as a factual claim. -- **`FUTURE-OUTLOOK` - "Challenges and Future Prospects" boilerplate** β€” section headings or closing paragraphs following the AI outline pattern (`Looking Ahead`, `Future Directions`, `The Road Ahead`). Replace with a specific heading or delete. -- **`COPULA-DODGE` - Copula avoidance** (`serves as`, `functions as`, `acts as`, `operates as`, `plays the role of` where "is" or a concrete verb suffices). Example: "serves as the single source of truth" β†’ "is the single source of truth" -- **`NEG-PARALLEL` - Negative parallelisms** (`not just … but`, `not only … but also`, `more than just`). State what the subject does directly. -- **`RULE-OF-THREE` - Rule-of-three overuse** β€” exactly three adjectives or nouns grouped for rhetorical balance rather than precision *(advisory)*. Use the most precise term. -- **`SYN-CYCLE` - Synonym cycling** β€” using different words for the same concept within a short span (e.g., "build manifest", "build descriptor", "build specification" for the same thing). Pick one term and use it throughout. -- **`FALSE-RANGE` - False ranges** (`from … to …` implying broad coverage from two arbitrary endpoints). List specific items instead. -- **`BOLD-OVERUSE` - Boldface overuse** β€” bold applied to adjectives, adverbs, or transitional words for decoration rather than to mark key terms or critical warnings. -- **`EMOJI` - Emojis** β€” any emoji outside a code fence. Delete; replace with a VitePress callout if semantic meaning is needed. -- **`CHATBOT-ARTIFACT` - Chatbot artifacts** (`Certainly!`, `Great question!`, `As I mentioned`, `I hope this helps`, `Feel free to ask`). Delete entirely. -- **`SYCOPHANT` - Sycophantic tone** (`great job`, `well done`, `excellent choice`, `congratulations on`). Delete; state the outcome directly. -- **`OVER-HEDGE` - Excessive hedging** β€” two or more hedges in one clause (`might possibly`, `could potentially`, `may perhaps`). Use at most one hedge where genuine uncertainty exists. -- **`GENERIC-CONCLUSION` - Generic positive conclusions** (`By following these steps`, `Armed with this knowledge`, `You are now ready to`, `You now have a solid understanding of`). Delete or replace with a concrete next step or link. - -::: - -Filler words (`simply`, `just`, `easy`/`easily`, `actually`, `basically`, `obviously`) are a separate category governed by the style guide's banned-filler-word rule. - -These categories describe concrete patterns to avoid at authoring time. The "no vague polish" refusal policy still applies for reviewers: contributors must identify a specific pattern from this list. +AI-assisted writing introduces recognizable patterns that reduce documentation +quality through repetition. Avoid these categories when authoring: + +- Hype openers and filler adjectives (`unlock`, `seamlessly`, `robust`, + `leverage`) +- Transitional bloat (`Moreover`, `It's worth noting`) +- Promotional flourish (`world-class`, `next-generation`, `game-changing`) +- Hedging and rhetorical-question openers (`In today's fast-paced world`, + `Ever wondered...?`) +- Chatbot artifacts and sycophancy (`Certainly!`, `Great question!`, + `excellent choice`) +- Copula avoidance (`serves as` where `is` fits), negative parallelisms + (`not just ... but`), and synonym cycling for one concept +- Generic conclusions (`By following these steps`, `You are now ready to`) +- Emoji outside code fences (also enforced by the GLDQ `EMOJI` rule) + +The [humanizer skill](/.agents/skills/humanizer/SKILL.md) is the single source +of truth for the full pattern catalog, each with a before-to-after example and a +minimal-rewrite workflow. See also +[Wikipedia: Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing), +the [softaworks/agent-toolkit humanizer skill](https://github.com/softaworks/agent-toolkit/blob/3027f20f3181758385a1bb8c022d4041dfb4de84/skills/humanizer/SKILL.md), +and [blader/humanizer](https://github.com/blader/humanizer/blob/1b48564898e999219882660237fde01bf4843a0f/SKILL.md). + +Filler words (`simply`, `just`, `easy`/`easily`, `actually`, `basically`, +`obviously`) are a separate category governed by the style guide's +banned-filler-word rule. + +The "no vague polish" refusal policy applies for reviewers: contributors must +identify a specific pattern from the humanizer catalog when reworking phrasing. ### Usability & Accessibility @@ -219,28 +335,46 @@ Version-specific content should include: ## Checklist -Use this checklist when reviewing or submitting documentation: +The checklist is split by who verifies each item. The automated half is already +enforced by tooling, so do not tick it by hand; run the commands instead. The +human review half covers everything a machine cannot judge. + +### Automated checks (enforced in CI) + +Run these before opening a pull request. They fail the build if findings remain: + +```bash +make docs-check-strict # GLDQ structural markers +make spelling # spelling +make linkcheck # dead links +make woke # inclusive language +``` + +`make docs-check-strict` covers, among others: image alt text +([`IMG-ALT`](#media-and-links)), descriptive link text +([`LINK-TEXT`](#media-and-links)), code block languages +([`CODE-LANG`](#code-blocks)), heading hierarchy +([`HEAD-SKIP`](#headings) and [`H1-ONE`](#headings)), emoji +([`EMOJI`](#media-and-links)), related topics +([`RELATED-TOPICS-PRESENT`](#components)), front matter +([`FM-*`](#front-matter)), and callout syntax ([`CALLOUT-*`](#callouts)). See the +[GLDQ rules](#rules) for the full list. Spelling, dead links, and inclusive +language are handled by `make spelling`, `make linkcheck`, and `make woke`. + +### Human review checklist -### Core Markers +A reviewer must confirm the items that tooling cannot verify: - All code and commands are tested and working - Prerequisites are clearly stated - Expected output is shown for verification steps -- Document has clear structure with descriptive headings - One main idea per paragraph - Sentences are concise and use active voice - Neutral and professional language throughout -- Gender-neutral language used - Consistent terminology (no synonym confusion) - Project-specific abbreviations link to Glossary -- All images have descriptive alt text -- Links use descriptive text (not "click here") -- Proper heading hierarchy maintained -- Code examples have syntax highlighting - Color is not the only indicator in visual media -- All links verified as working -- Document is discoverable via navigation/index -- Cross-referenced from related documentation +- Document is discoverable and cross-referenced in the right context - Clear ownership indicated - No AI-tell phrasing (see [AI-generated phrasing to avoid](#ai-generated-phrasing-to-avoid)) From b0ba52ea0eb47465f5b00a2eb453eb02a044622f Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Thu, 26 Nov 2026 16:08:25 +0100 Subject: [PATCH 14/15] chore: update docs dependencies Signed-off-by: Eike Waldt On-behalf-of: SAP --- repos-config.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/repos-config.json b/repos-config.json index cc274e7..eaa51c7 100644 --- a/repos-config.json +++ b/repos-config.json @@ -26,7 +26,7 @@ "url": "https://github.com/gardenlinux/python-gardenlinux-lib", "docs_path": "docs", "ref": "main", - "commit": "40c75314a77f3c6b08835d7ba019ac4b202b9816", + "commit": "51a93bcab598b762753b073bd22ee00dcf622e3a", "structure": "sphinx", "target_map": { "cli.md": "reference/python-gardenlinux-lib-cli.md", @@ -38,7 +38,7 @@ "url": "https://github.com/gardenlinux/package-linux", "docs_path": "docs", "ref": "main", - "commit": "39d7639fdaceb3249732eaf8286898a011067600" + "commit": "233ec051633bc6d100d6dd509d0c5fed69c8f5ef" }, { "name": "package-build", @@ -59,28 +59,28 @@ "url": "https://github.com/gardenlinux/glrd", "docs_path": "docs", "ref": "main", - "commit": "0da9dd60384959e07fda23f6e29f52b7f1da00aa" + "commit": "06ed95af19f2680579917c4c251f4bf1c3d1d81a" }, { "name": "gardenlinux-nvidia-installer", "url": "https://github.com/gardenlinux/gardenlinux-nvidia-installer", "docs_path": "docs", "ref": "main", - "commit": "7dd97a72be5e54cd8ba2e531c32c3a56e2e07fa0" + "commit": "bf88ee1255b59d00b9c176968cdd24a49bd6692a" }, { "name": "glci", "url": "https://github.com/gardenlinux/glci", "docs_path": "docs", "ref": "main", - "commit": "aba79d68db666b3095dd196a68c13dffbf28e838" + "commit": "bf8eca79b45eadc40efc0f40a274ae93a33da742" }, { "name": "daily", "url": "https://github.com/gardenlinux/daily", "docs_path": "docs", "ref": "gh-pages", - "commit": "490c3b4bc74a03b4895497ebac5be29401aa426b", + "commit": "082d7ec9b88b709031747bd16d01a895020b6cbf", "docs_paths": [ "docs/**", ".github/workflows/docs-check.yml", From b2520af532e90fb7380a0012ae6a5a9d14191e83 Mon Sep 17 00:00:00 2001 From: Eike Waldt Date: Thu, 26 Nov 2026 16:25:28 +0100 Subject: [PATCH 15/15] docs: fix link to skill Signed-off-by: Eike Waldt On-behalf-of: SAP --- docs/.vitepress/config.mts | 2 ++ docs/contributing/documentation/writing_good_docs.md | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 0bfa142..4a8b230 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -103,6 +103,8 @@ export default defineConfig({ /test\//, /tests\//, /samples\//, + // humanizer skill lives in .agents/ outside the published docs root + /\.agents\/skills\/humanizer\/SKILL/, ], head: [ [ diff --git a/docs/contributing/documentation/writing_good_docs.md b/docs/contributing/documentation/writing_good_docs.md index 1e30b51..2276a2f 100644 --- a/docs/contributing/documentation/writing_good_docs.md +++ b/docs/contributing/documentation/writing_good_docs.md @@ -40,7 +40,7 @@ Quality is enforced in two complementary ways: For how to use the custom components and front-matter fields referenced throughout this guide, see [VitePress Features](./vitepress-features.md). To rework AI-generated phrasing, -use the [humanizer skill](/.agents/skills/humanizer/SKILL.md) (see +use the [humanizer skill](../../../.agents/skills/humanizer/SKILL.md) (see [AI-generated phrasing to avoid](#ai-generated-phrasing-to-avoid)). ## Automated Quality Checks (GLDQ) @@ -236,7 +236,7 @@ quality through repetition. Avoid these categories when authoring: - Generic conclusions (`By following these steps`, `You are now ready to`) - Emoji outside code fences (also enforced by the GLDQ `EMOJI` rule) -The [humanizer skill](/.agents/skills/humanizer/SKILL.md) is the single source +The [humanizer skill](../../../.agents/skills/humanizer/SKILL.md) is the single source of truth for the full pattern catalog, each with a before-to-after example and a minimal-rewrite workflow. See also [Wikipedia: Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing),