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.

clew/filedocs.py:163

Show on the map →

Called by doc_for

Calls none

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.

clew/filedocs.py:188

Show on the map →

Called by doc_for

Calls none

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
lines 197–197trylines 198–198return ast.get_docstring(ast.parse(text)) or ""lines 199–199except (SyntaxError, ValueError)lines 200–200return ""
str clew.filedocs.CFamilyFileDoc._raw(self, str text)

The leading doxygen comment, block form or line-run form.

clew/filedocs.py:241

Show on the map →

Called by doc_for

Calls _line_run, _strip_preamble

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
lines 253–253rest = _strip_preamble(text)lines 254–254block = _CXX_BLOCK_DOC.match(rest)lines 255–255return block.group("body") if block else self._line_run(rest.splitlines())
str clew.filedocs.JsFileDoc._raw(self, str text)

The leading JSDoc block, when it declares itself file-level.

clew/filedocs.py:313

Show on the map →

Called by doc_for

Calls none

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
lines 315–315◇ while Truelines 316–316match = _JS_PREAMBLE.match(text)lines 317–317◇ if not matchlines 318–318breaklines 319–319text = text[match.end() :]lines 320–320raw = super()._raw(text)lines 321–321return raw if _JSDOC_FILE_TAG.search(raw) else ""
str clew.filedocs.HashFileDoc._raw(self, str text)

The leading # block, licence lines removed.

clew/filedocs.py:391

Show on the map →

Called by doc_for

Calls none

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
lines 396–396◇ while Truelines 397–397match = _HASH_PREAMBLE.match(text)lines 398–398◇ if not matchlines 399–399breaklines 400–400text = text[match.end() :]lines 401–401block = _HASH_BLOCK.match(text)lines 402–402◇ if not blocklines 403–403return ""lines 404–404kept = []lines 405–405◇ for line in block.group(0).splitlines()lines 406–406stripped = line.strip().lstrip("#").strip()lines 407–407◇ if stripped and not _LICENCE_LINE.match(stripped)lines 408–408kept.append(stripped)lines 409–409return "\n".join(kept)

Requirements

REQ-DDB-PIPE-008 REQ-DDB-PIPE-012

doc_for

str clew.filedocs.FileDocExtractor.doc_for(self, str text)

The file-level documentation for one file's text, or "".

clew/filedocs.py:146

Show on the map →

Called by none

Calls _clean, _raw

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
lines 155–155return _clean(self._raw(text))

Requirements

REQ-DDB-PIPE-008

ensure_file_docs_table

None clew.filedocs.ensure_file_docs_table(sqlite3.Connection conn)

Create the file_docs table if it is absent.

clew/filedocs.py:451

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
lines 459–461conn.execute( "CREATE TABLE IF NOT EXISTS file_docs ( file_path TEXT NOT NULL, doc TEXT NOT NULL)" )

Requirements

REQ-DDB-SCHEMA-014

extract_file_doc

str clew.filedocs.extract_file_doc(str rel_path, str text)

The file-level documentation for one repo-relative source file.

clew/filedocs.py:428

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
lines 436–436suffix = Path(rel_path).suffix.lower()lines 439–439name = PurePosixPath(rel_path.replace("\\", "/")).name.lower()lines 440–440◇ for extractor in _EXTRACTORSlines 441–441◇ if suffix in extractor.EXTENSIONS or name in getattr(extractor, "NAMES", ())lines 442–442return extractor.doc_for(text)lines 443–443return ""

Requirements

REQ-DDB-PIPE-008

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.

clew/filedocs.py:526

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)

Activity · 11 steps
lines 548–548conn = sqlite3.connect(str(db_path))lines 549–549trylines 550–550ensure_file_docs_table(conn)lines 551–551conn.execute("DELETE FROM file_docs")lines 552–552rows = _collect_file_docs(conn, repo_root, cache)lines 553–553conn.executemany("INSERT INTO file_docs (file_path, doc) VALUES (?, ?)", rows)lines 554–557conn.execute( "CREATE VIRTUAL TABLE IF NOT EXISTS supplementary_docs " "USING fts5(file_path, heading, content)" )lines 558–561conn.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], )lines 562–562conn.commit()lines 565–565logger.info("file_docs: %d file(s) yielded file-level documentation", len(rows))lines 566–566return len(rows)

Requirements

REQ-DDB-PIPE-008