filedocs.py¶
clew/filedocs.py
File-level documentation ingestion: module docstrings and `@file` blocks.
_raw
str clew.filedocs.FileDocExtractor._raw(self, str text)
Locate the raw, un-normalised documentation block.
Source · 7 lines
def _raw(self, text: str) -> str:
"""@brief Language-specific location of the leading doc block.
@return Raw block text or "".
@version 1
"""
str clew.filedocs.PythonFileDoc._raw(self, str text)
The module docstring, or "" when the file has none or will not parse.
Source · 15 lines
def _raw(self, text: str) -> str:
"""A `SyntaxError` yields "" rather than propagating: this stage annotates
an index, and one unparseable file must not fail a build that doxygen
already indexed successfully.
@brief Read the module docstring via the AST.
@return Docstring or "".
@version 1
"""
try:
return ast.get_docstring(ast.parse(text)) or ""
except (SyntaxError, ValueError):
return ""
Activity · 4 steps
str clew.filedocs.CFamilyFileDoc._raw(self, str text)
The leading doxygen comment, block form or line-run form.
Source · 16 lines
def _raw(self, text: str) -> str:
"""The preamble — blanks, `#` and non-doxygen `//` lines, and plain `/* */`
blocks — is skipped OVER rather than treated as the end of the search, so an
SPDX line or a copyright block above the real `@file` block does not hide it.
That is the same shape as the `#`-divider trap that used to make doxygen-guard
read the wrong block, and it is why the license case needed a control test
rather than an assumption.
@brief Locate the leading doxygen comment in C-family source.
@return Raw body text or "".
@version 2
"""
rest = _strip_preamble(text)
block = _CXX_BLOCK_DOC.match(rest)
return block.group("body") if block else self._line_run(rest.splitlines())
Activity · 3 steps
str clew.filedocs.JsFileDoc._raw(self, str text)
The leading JSDoc block, when it declares itself file-level.
Source · 11 lines
def _raw(self, text: str) -> str:
"""@brief Read a file-level JSDoc block."""
while True:
match = _JS_PREAMBLE.match(text)
if not match:
break
text = text[match.end() :]
raw = super()._raw(text)
return raw if _JSDOC_FILE_TAG.search(raw) else ""
Activity · 7 steps
str clew.filedocs.HashFileDoc._raw(self, str text)
The leading # block, licence lines removed.
Source · 21 lines
def _raw(self, text: str) -> str:
"""@brief Read a leading hash-comment block.
@return The prose lines, or "".
@version 1
"""
while True:
match = _HASH_PREAMBLE.match(text)
if not match:
break
text = text[match.end() :]
block = _HASH_BLOCK.match(text)
if not block:
return ""
kept = []
for line in block.group(0).splitlines():
stripped = line.strip().lstrip("#").strip()
if stripped and not _LICENCE_LINE.match(stripped):
kept.append(stripped)
return "\n".join(kept)
Activity · 14 steps
Requirements
doc_for
str clew.filedocs.FileDocExtractor.doc_for(self, str text)
The file-level documentation for one file's text, or "".
Source · 11 lines
def doc_for(self, text: str) -> str:
"""Template method: locate, then normalise. Returning "" rather than None
for "no documentation" keeps the caller's filter a plain truth test, and a
file with no module doc is the common case, not an error.
@brief Extract and normalise one file's leading documentation.
@return Cleaned text, or "" when there is none.
@version 1
"""
return _clean(self._raw(text))
Activity · 1 steps
Requirements
ensure_file_docs_table
None clew.filedocs.ensure_file_docs_table(sqlite3.Connection conn)
Create the file_docs table if it is absent.
Source · 13 lines
def ensure_file_docs_table(conn: sqlite3.Connection) -> None:
"""No enumerated column, so nothing here comes from `vocabulary` — there is
no `CHECK` to generate. `IF NOT EXISTS` plus a `DELETE` at ingest time makes
the stage idempotent across rebuilds of the same database.
@brief Ensure the file-level documentation table exists.
@version 1
"""
conn.execute(
"CREATE TABLE IF NOT EXISTS file_docs ( file_path TEXT NOT NULL, doc TEXT NOT NULL)"
)
Activity · 1 steps
Requirements
extract_file_doc
str clew.filedocs.extract_file_doc(str rel_path, str text)
The file-level documentation for one repo-relative source file.
Called by _doc_of
Tested by 13 tests
test_a_comment_after_code_is_not_a_file_doc, test_a_licence_only_header_is_rejected, test_a_plain_comment_header_is_not_documentation, test_an_unclaimed_suffix_yields_no_documentation, test_c_family_doxygen_block_is_found_past_a_license_header, test_c_family_line_comment_run_is_extracted, test_every_hash_comment_type_is_read, test_licence_lines_are_dropped_from_a_real_header, test_python_module_docstring_is_the_file_documentation, test_rust_module_doc_comment_is_extracted, test_the_graded_perl_header_is_extracted, test_the_shebang_is_skipped
Calls none
Source · 18 lines
def extract_file_doc(rel_path: str, text: str) -> str:
"""Dispatch on suffix. Exposed separately from the ingest stage so the
extraction is testable against a string without a database anywhere near it.
@brief Extract one file's file-level documentation.
@return Cleaned text or "".
@version 1
"""
suffix = Path(rel_path).suffix.lower()
## MATCHED AS A PATH COMPONENT, never as a suffix: `CMakeLists.txt` and `Makefile` are
## claimed by whole name, and `endswith("makefile")` would also claim `oldmakefile.txt`.
name = PurePosixPath(rel_path.replace("\\", "/")).name.lower()
for extractor in _EXTRACTORS:
if suffix in extractor.EXTENSIONS or name in getattr(extractor, "NAMES", ()):
return extractor.doc_for(text)
return ""
Activity · 6 steps
Requirements
ingest_file_docs
int clew.filedocs.ingest_file_docs(Path db_path, Path repo_root, IndexCache|None cache=None)
Ingest every indexed file's file-level documentation.
Source · 43 lines
def ingest_file_docs(db_path: Path, repo_root: Path, cache: IndexCache | None = None) -> int:
"""MUST RUN AFTER `prose.ingest_supplementary_docs`, which DROPs and recreates
`supplementary_docs` on every build — above it, these rows would be inserted
and then deleted, and the observable result would be an empty search with no
error anywhere. The same trap `kconfig.ingest_kconfig_prose` documents.
MUST ALSO RUN AFTER `coverage.report_index_coverage`, which is a SECOND and
less obvious ordering constraint. Coverage excludes files that yielded PROSE
instead of symbols, by reading `supplementary_docs` — a markdown file is not
barren, it is not code. Run above it, every source file with a module
docstring would suddenly count as "yielded prose" and the barren ratio, whose
whole job is to say how much of the index is empty, would silently improve
without a single extra symbol being indexed.
The path is repeated inside the content because FTS5 ranks over the columns it
is given, and someone searching for a capability types words from the prose
while someone auditing a file types its name. Both have to hit.
@brief Ingest module docstrings and file-level doxygen comments.
@return Count of files that yielded documentation.
@version 1
"""
conn = sqlite3.connect(str(db_path))
try:
ensure_file_docs_table(conn)
conn.execute("DELETE FROM file_docs")
rows = _collect_file_docs(conn, repo_root, cache)
conn.executemany("INSERT INTO file_docs (file_path, doc) VALUES (?, ?)", rows)
conn.execute(
"CREATE VIRTUAL TABLE IF NOT EXISTS supplementary_docs "
"USING fts5(file_path, heading, content)"
)
conn.executemany(
"INSERT INTO supplementary_docs (file_path, heading, content) VALUES (?, ?, ?)",
[(rel, f"{rel} — file-level documentation", f"{rel}\n{doc}") for rel, doc in rows],
)
conn.commit()
finally:
conn.close()
logger.info("file_docs: %d file(s) yielded file-level documentation", len(rows))
return len(rows)