Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ cd "${SCRIPT_DIR}"

rm -rf build 2> /dev/null

python3 -m unittest test_rustdoc_trim.py

# Keep the workspace dependency graph in sync with the codebase.
scripts/generate_dependency_graph.sh

Expand Down
95 changes: 52 additions & 43 deletions docs/rustdoc_trim.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,55 @@
# SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
# SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

import re
from sphinx.application import Sphinx

# Regex pattern to match Rust code blocks in Markdown
RUST_CODE_BLOCK_PATTERN = re.compile(r"```rust(?:,ignore)?\s*(.*?)```", re.DOTALL)


def remove_hashtag_lines_in_rust_blocks(markdown_content):
"""
Removes lines starting with '# ' in Rust code blocks within a Markdown string.
"""

def _process_code_block(match):
# Extract the code block content
code_block_content = match.group(1).strip()

# Remove lines starting with '#'
modified_code_block = "\n".join(
line
for line in code_block_content.splitlines()
if (not line.lstrip().startswith("# ")) and line.strip() != "#"
)

# Return the modified code block wrapped in triple backticks
return f"```rust\n{modified_code_block}\n```"

# Replace all Rust code blocks using the _process_code_block function
return RUST_CODE_BLOCK_PATTERN.sub(_process_code_block, markdown_content)


def process_source_file(app: Sphinx, docname: str, source: list[str]):
original_content = source[0]
# Remove lines starting with '#' in Rust code blocks
modified_content = remove_hashtag_lines_in_rust_blocks(original_content)
source[0] = modified_content


def setup(app: Sphinx):
app.connect("source-read", process_source_file)
return dict(
parallel_read_safe=True,
parallel_write_safe=True,
)
from __future__ import annotations

from typing import TYPE_CHECKING

from docutils import nodes

if TYPE_CHECKING:
from sphinx.application import Sphinx


def _is_rust_language(language: str) -> bool:
return language == "rust" or language.startswith("rust,")


def trim_rustdoc_code(code: str) -> str:
"""Strip hidden `#` lines and unescape `##` lines following rustdoc rules."""
kept: list[str] = []
for line in code.split("\n"):
stripped = line.lstrip(" \t")
if stripped == "#" or stripped.startswith("# "):
continue
if stripped.startswith("##"):
indent_len = len(line) - len(stripped)
kept.append(f"{line[:indent_len]}{stripped[1:]}")
else:
kept.append(line)

start = 0
while start < len(kept) and not kept[start].strip():
start += 1
end = len(kept)
while end > start and not kept[end - 1].strip():
end -= 1
return "\n".join(kept[start:end])


def process_doctree(app: Sphinx, doctree: nodes.document) -> None:
for node in doctree.findall(nodes.literal_block):
if _is_rust_language(node.get("language", "")):
trimmed = trim_rustdoc_code(node.astext())
node["language"] = "rust"
# Sphinx skips Pygments highlighting when rawsource != astext().
node.rawsource = trimmed
node[:] = [nodes.Text(trimmed)]


def setup(app: Sphinx) -> dict[str, bool]:
app.connect("doctree-read", process_doctree)
return {
"parallel_read_safe": True,
"parallel_write_safe": True,
}
117 changes: 117 additions & 0 deletions docs/test_rustdoc_trim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
# SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

import html as html_lib
import re
import tempfile
import unittest
from pathlib import Path

from docutils import nodes
from rustdoc_trim import process_doctree, trim_rustdoc_code
from sphinx.cmd.build import build_main

DOCS_DIR = Path(__file__).resolve().parent


class RustdocTrimTest(unittest.TestCase):
def test_strips_hidden_lines_and_unescapes_double_hashes(self):
src = (
"# use std::sync::Arc;\n"
"#\n"
"\n"
"#[derive(Debug)]\n"
"## shown_comment\n"
" ## indented_escaped\n"
"##\n"
" # let hidden = 1;\n"
"let visible = 2;\n"
"\n"
)
expected = (
"#[derive(Debug)]\n"
"# shown_comment\n"
" # indented_escaped\n"
"#\n"
"let visible = 2;"
)
self.assertEqual(trim_rustdoc_code(src), expected)

def test_preserves_leading_indentation_on_first_kept_line(self):
src = "# fn wrapper() {\n let indented = 42;\n# }\n"
self.assertEqual(trim_rustdoc_code(src), " let indented = 42;")

def test_process_doctree_normalizes_rust_blocks_and_skips_other_languages(self):
doc = nodes.document("", nodes.Element())
rust_ignore = nodes.literal_block(
"# hidden\nlet x = 1;\n",
"# hidden\nlet x = 1;\n",
language="rust,ignore",
)
rustfmt = nodes.literal_block(
"# keep\nmax_width = 100\n",
"# keep\nmax_width = 100\n",
language="rustfmt",
)
doc += rust_ignore
doc += rustfmt

process_doctree(None, doc)

self.assertEqual(rust_ignore["language"], "rust")
self.assertEqual(rust_ignore.astext(), "let x = 1;")
self.assertEqual(rust_ignore.rawsource, "let x = 1;")
self.assertEqual(rustfmt["language"], "rustfmt")
self.assertEqual(rustfmt.astext(), "# keep\nmax_width = 100\n")

def test_sphinx_myst_end_to_end_fences_and_directives(self):
with tempfile.TemporaryDirectory() as tmp:
src_dir = Path(tmp) / "source"
out_dir = Path(tmp) / "build"
src_dir.mkdir()
(src_dir / "conf.py").write_text(
f"import sys\nsys.path.insert(0, {str(DOCS_DIR)!r})\n"
"extensions = ['myst_parser', 'rustdoc_trim']\n",
encoding="utf-8",
)
(src_dir / "index.md").write_text(
"# Test\n\n"
"````rust\n"
"/// ```\n"
"# let hidden_after_inner_fence = 1;\n"
"/// let value = 42;\n"
"/// ```\n"
"````\n\n"
"````{note}\n"
"```rust,no_run\n"
"# use std::sync::Arc;\n"
"let in_note = 1;\n"
"```\n"
"````\n\n"
"````markdown\n"
"```rust\n"
"# keep_inside_markdown_example\n"
"```\n"
"````\n\n"
"```rust\n"
"# hidden_in_unclosed_eof_fence\n"
"let unclosed = 3;\n",
encoding="utf-8",
)
rc = build_main(["-W", "-q", "-b", "html", str(src_dir), str(out_dir)])
self.assertEqual(rc, 0)
raw_html = (out_dir / "index.html").read_text(encoding="utf-8")
plain = html_lib.unescape(re.sub(r"<[^>]+>", "", raw_html))
self.assertIn("highlight-rust", raw_html)
self.assertIn("/// ```\n/// let value = 42;\n/// ```", plain)
self.assertNotIn("hidden_after_inner_fence", plain)
self.assertNotIn("use std::sync::Arc", plain)
self.assertIn("let in_note = 1;", plain)
self.assertIn("```rust\n# keep_inside_markdown_example\n```", plain)
self.assertNotIn("hidden_in_unclosed_eof_fence", plain)
self.assertIn("let unclosed = 3;", plain)


if __name__ == "__main__":
unittest.main()