kconfig.py¶
clew/kconfig.py
The CONFIGURATION SPACE a repo declares in Kconfig — structure and help text.
_served_parse_error
str clew.kconfig._served_parse_error(Exception exc)
The parse error as it may be SERVED: its type and location, never a quoted line.
Source · 24 lines
def _served_parse_error(exc: Exception) -> str:
"""`kconfig.error` IS A SERVED `build_meta` VALUE, and kconfiglib's messages QUOTE THE
OFFENDING LINE. A repository whose `source` reaches a file it should not read therefore got
that file's content back out through the failure text even when the parse failed and every
row was discarded (1.1.0 audit, M2).
The type and the `file:line:` prefix are kept because they are what makes the value
diagnostic — an owner can open that line. The remainder is dropped from the SERVED value
only: `load_kconfig` has already logged the full message at WARNING, which is the
operator's to read and is not published over MCP. This is the same split
`_warn_unwalkable` makes in `scope.py` — the gap is reported, the content is not.
@brief Reduce a parse error to type and location.
@return "<Type>: <file>:<line>" where a location is present, else "<Type>".
@version 1
"""
located = re.match(r"([^\s:]+:\d+)", str(exc))
where = f": {located.group(1)}" if located else ""
return (
f"{type(exc).__name__}{where} — the full message is in the build log, and is not "
f"published here because it quotes the line it failed on"
)
Activity · 3 steps
Requirements
_sourced_outside
list[str] clew.kconfig._sourced_outside(Any kconf, Path root)
Files this parse read that lie outside the repository.
Source · 22 lines
def _sourced_outside(kconf: Any, root: Path) -> list[str]:
"""kconfiglib resolves `source` against `$srctree` and offers NO HOOK on that resolution,
so `source "/abs/path"` parsed a file anywhere on the machine and served its symbols,
prompts and help text as this repository's configuration space (1.1.0 audit, M2).
CHECKED AFTER THE PARSE, from `kconf.kconfig_filenames` — kconfiglib's own record of every
file it read. The read has happened by the time this runs; what the check prevents is
DISCLOSURE, which is the harm. A pre-parse scan of the text was the alternative and it is
the fragile one: `source` takes globs and preprocessor-expanded variables, so a scanner
would have to re-implement the parser to be right.
@brief Report sourced files that escape the repository.
@return The escaping paths.
@version 1
"""
escaped = set()
for name in getattr(kconf, "kconfig_filenames", ()) or ():
if within_repo(root / str(name), root, setting=f"kconfig source {name}") is None:
escaped.add(str(name))
return sorted(escaped)
Activity · 5 steps
Requirements
as_meta
dict[str, str] clew.kconfig.KconfigModel.as_meta(self)
Flatten to string values for build_meta persistence.
Source · 30 lines
def as_meta(self) -> dict[str, str]:
"""Counts are STRINGS because `write_build_signature` drops falsy values, and a
measured zero must survive: `"0"` is truthy where `0` is not. That is the same
rule `coverage.as_meta` and `preprocessor.as_meta` document, and here it is
what makes "found a Kconfig, parsed it, it declares nothing" distinguishable
from "no Kconfig".
Returns {} — no `kconfig.*` rows at all — only when NOTHING was found, so an
absent key honestly reads as "not recorded" and every existing target's
`build_meta` is unchanged.
@brief Kconfig provenance and counts as build_meta values.
@return Unprefixed key -> string value.
@version 1
"""
if not self.found:
return {}
return {
"source": self.location.source,
"root": str(self.location.path),
"symbol_count": str(len(self.symbols)),
"choice_count": str(len(self.choices)),
"documented_count": str(self.documented),
"error": self.error,
## A STRING COUNT for the reason every count here is one: `write_build_signature`
## drops falsy values, so a measured zero has to survive as "0".
"shell_refused": str(len(self.shell_refused)),
}
Activity · 3 steps
Requirements
describe_search
str clew.kconfig.KconfigLocation.describe_search(self)
Human-readable list of the locations that were tried.
Source · 9 lines
def describe_search(self) -> str:
"""@brief Render `searched` for a log line or a recorded reason.
@return Comma-joined locations, or a note that none were tried.
@version 1
"""
return ", ".join(self.searched) if self.searched else "no locations searched"
Activity · 1 steps
Requirements
discover_kconfig
KconfigLocation clew.kconfig.discover_kconfig(Path|str|None repo_root, dict[str, Any]|None declaration=None)
Locate a repo's top-level Kconfig: declared, root, then convention.
Called by import_kconfig
Tested by 14 tests
test_a_declared_but_missing_root_is_not_silently_replaced_by_convention, test_a_declared_root_beats_convention, test_a_declared_root_outside_the_repository_is_refused, test_a_kconfig_parse_is_given_a_minimal_environment, test_a_kconfig_sourcing_outside_the_repository_is_refused, test_a_parse_failure_records_the_location_and_not_the_line, test_a_repo_supplied_kconfig_functions_module_is_not_imported, test_a_single_conventional_candidate_is_accepted, test_a_sourced_file_is_parsed_and_choices_group_their_members, test_an_unambiguous_root_kconfig_is_found_and_stored_repo_relative, test_convention_refuses_among_several_candidates, test_kconfig_prose_must_be_ingested_after_the_markdown_ingest
Calls _conventional_kconfig, _declared_kconfig
Source · 28 lines
def discover_kconfig(
repo_root: Path | str | None, declaration: dict[str, Any] | None = None
) -> KconfigLocation:
"""Explicit, then convention, then a REFUSAL when convention is ambiguous —
the rule `preprocessor` follows too — because a wrong answer here looks like a
right one: a Kconfig belonging to
a vendored subsystem describes a configuration space the repo does not ship,
and every count taken from it looks legitimate.
`path` on the returned location is REPO-RELATIVE, and that is not only a
disclosure rule. kconfiglib resolves `source` paths against `$srctree`, so the
parse is driven from a relative path anyway and every filename it reports comes
back relative — one convention end to end rather than two that must be
reconciled per row.
@brief Discover the repo's top-level Kconfig with its provenance.
@return The located Kconfig and how it was found.
@version 2
"""
if repo_root is None:
return KconfigLocation(path=None)
root = Path(repo_root).expanduser().resolve()
declared = (declaration or {}).get(SECTION_KCONFIG)
if isinstance(declared, dict) and declared.get(KEY_ROOT):
return _declared_kconfig(root, str(declared[KEY_ROOT]))
return _conventional_kconfig(root)
Activity · 7 steps
Requirements
documented
int clew.kconfig.KconfigModel.documented(self)
How many symbols carry help text — the surface gh#18 exists for.
Source · 8 lines
def documented(self) -> int:
"""@brief Count symbols carrying a help block.
@return Number of symbols with help text.
@version 1
"""
return sum(1 for sym in self.symbols if sym.help)
Activity · 1 steps
Requirements
ensure_kconfig_tables
None clew.kconfig.ensure_kconfig_tables(sqlite3.Connection conn)
Idempotent creation of the kconfig_choices and kconfig_symbols tables.
Source · 48 lines
def ensure_kconfig_tables(conn: sqlite3.Connection) -> None:
"""`kconfig_gates` is created by `kconfig_gates.py`, next to the harvest that
fills it, for the same reason `lock_acquisitions` lives with the lock scan: the
two layers fail independently — a repo can have a parseable Kconfig and no C
sources, or gated C and an unparseable Kconfig — and a shared creator would make
one layer's absence look like the other's.
`choice_key` is a plain INTEGER rather than a foreign key into `kconfig_choices`,
because it is a SYNTHETIC per-build ordinal, not a durable identity. Declaring a
REFERENCES on it would suggest a stability across builds that the enumeration
order does not promise for a tree whose files changed.
@brief Create the Kconfig structure tables.
@version 1
"""
conn.execute(
"""
CREATE TABLE IF NOT EXISTS kconfig_choices (
key INTEGER PRIMARY KEY,
name TEXT NOT NULL,
prompt TEXT NOT NULL,
default_expr TEXT NOT NULL,
file_path TEXT NOT NULL,
line INTEGER NOT NULL
)
"""
)
conn.execute(
f"""
CREATE TABLE IF NOT EXISTS kconfig_symbols (
name TEXT NOT NULL,
type TEXT NOT NULL {check("kconfig_symbols", "type")},
prompt TEXT NOT NULL,
help TEXT NOT NULL,
default_expr TEXT NOT NULL,
choice_key INTEGER,
file_path TEXT NOT NULL,
line INTEGER NOT NULL,
UNIQUE(name)
)
"""
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_kconfig_symbols_choice ON kconfig_symbols(choice_key)"
)
conn.commit()
Activity · 4 steps
Requirements
found
bool clew.kconfig.KconfigModel.found(self)
Whether the repo has a top-level Kconfig at all.
Source · 11 lines
def found(self) -> bool:
"""NOT `bool(self.symbols)`. A Kconfig that was found and failed to parse is
a FINDING, and it is the finding a Zephyr app indexed outside its workspace
produces.
@brief Did discovery find a Kconfig?
@return True when a path was located.
@version 1
"""
return self.location.path is not None
Activity · 1 steps
Requirements
import_kconfig
KconfigModel clew.kconfig.import_kconfig(Path db_path, Path|str|None repo_root, dict[str, Any]|None declaration=None)
Discover, parse, store and index a repo's configuration space.
Called by _build_stages
Tested by 9 tests
test_a_gate_on_an_undeclared_symbol_is_kept, test_a_kconfig_that_cannot_be_parsed_is_recorded_rather_than_silent, test_a_limitation_documented_only_in_help_is_searchable, test_a_measured_zero_survives_the_build_signature, test_a_repo_with_no_kconfig_is_completely_unaffected, test_gate_counts_reach_the_symbol_rows, test_prompt_and_symbol_name_both_reach_the_prose_corpus, test_the_configured_variant_travels_beside_the_space, test_the_stored_tables_round_trip_through_the_query_layer
Calls describe_search, discover_kconfig, ingest_kconfig_prose, load_kconfig, store_kconfig
Source · 25 lines
def import_kconfig(
db_path: Path, repo_root: Path | str | None, declaration: dict[str, Any] | None = None
) -> KconfigModel:
"""The one entry point `cli._build_stages` calls. Returns the model rather than
only counts, because the caller's `write_build_signature` needs the provenance —
and because a stage that reports a number and discards the reason why it is that
number is the defect persisting the scope decision fixed.
Reachable with nothing but `repo_root` and the declaration, so the MCP server
gets it with no per-section plumbing: CLAUDE.md's rule is that a declaration
reachable only from an argument is not a declaration, and the MCP build passes
no override arguments.
@brief Run the whole Kconfig ingestion stage.
@return The parsed configuration space.
@version 2
"""
location = discover_kconfig(repo_root, declaration)
if location.path is None:
logger.info("kconfig: none found — searched %s", location.describe_search())
return KconfigModel(location=location)
model = load_kconfig(location, repo_root or ".")
store_kconfig(db_path, model)
ingest_kconfig_prose(db_path, model)
return model1 more lines, not shown
Activity · 8 steps
Requirements
ingest_kconfig_prose
int clew.kconfig.ingest_kconfig_prose(Path db_path, KconfigModel model)
Feed every symbol's prompt and help text into the FTS5 prose corpus.
Source · 49 lines
def ingest_kconfig_prose(db_path: Path, model: KconfigModel) -> int:
"""THE HIGHEST-VALUE PART OF gh#18 PER LINE, and it needs no new table. A `help`
block routinely carries the only statement of a known limitation in a whole
repository — a variant whose current limits are placeholders reused from a
sibling pending real measurements — and until this ran, `search_prose` could not
reach a word of it.
MUST RUN AFTER `prose.ingest_supplementary_docs`, which DROPs and recreates
`supplementary_docs` on every build. Running before it would insert these rows
and then delete them, and the observable result would be an empty search with no
error anywhere — the quietest possible failure.
The symbol NAME goes in the heading and is repeated in the content, because FTS5
ranks over the columns it is given and an engineer searching for a limitation
types words from the help text, while one auditing a symbol types its name. Both
have to hit.
@brief Insert Kconfig prompts and help blocks into the prose corpus.
@return Chunk count.
@version 1
"""
rows = [
(
sym.file_path or str(model.location.path),
f"CONFIG_{sym.name}" + (f" — {sym.prompt}" if sym.prompt else ""),
"\n".join(part for part in (f"CONFIG_{sym.name}", sym.prompt, sym.help) if part),
)
for sym in model.symbols
if sym.prompt or sym.help
]
if not rows:
return 0
conn = sqlite3.connect(str(db_path))
try:
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 (?, ?, ?)",
rows,
)
conn.commit()
finally:
conn.close()
logger.info("kconfig: %d prompt/help chunk(s) ingested into the prose corpus", len(rows))
return len(rows)
Activity · 10 steps
Requirements
load_kconfig
KconfigModel clew.kconfig.load_kconfig(KconfigLocation location, Path|str repo_root)
Parse a located Kconfig into the configuration space it declares.
Called by import_kconfig
Tested by 8 tests
test_a_kconfig_parse_is_given_a_minimal_environment, test_a_kconfig_sourcing_outside_the_repository_is_refused, test_a_parse_failure_records_the_location_and_not_the_line, test_a_repo_supplied_kconfig_functions_module_is_not_imported, test_a_sourced_file_is_parsed_and_choices_group_their_members, test_kconfig_prose_must_be_ingested_after_the_markdown_ingest, test_locations_are_repo_relative_and_point_at_the_declaring_file, test_types_defaults_and_conditions_survive_verbatim
Calls _model_from_kconf, _served_parse_error, _sourced_outside, list, parse_environment
Source · 55 lines
def load_kconfig(location: KconfigLocation, repo_root: Path | str) -> KconfigModel:
"""DEGRADES TO A RECORDED ERROR, never to an exception. A configuration space is
metadata about a repository; failing an index build over it would take a whole
doxygen run with it, and the parse can fail for a completely ordinary reason —
a Zephyr application's Kconfig `source`s the Zephyr tree's own, so it is
unparseable outside a west workspace.
kconfiglib's warnings are CAPTURED rather than printed (`warn_to_stderr=False`)
and reported at INFO with a count. They are genuinely informative — an undefined
symbol in a `select` is a real defect in the target — but they are the target's
business and not a reason to make our build look broken.
@brief Parse a repo's Kconfig, recording any failure instead of raising.
@return The parsed configuration space.
@version 2
"""
if location.path is None:
return KconfigModel(location=location)
root = Path(repo_root).expanduser().resolve()
refused: list[str] = []
try:
## `parse_environment` REPLACES the process environment for the parse rather than
## only setting `srctree` (1.1.0 audit, H3): a Kconfig expands `$(VAR)` from the
## environment into text this build then serves, runs `$(shell,…)` as a command, and
## imports whatever `KCONFIG_FUNCTIONS` names. One minimal environment closes all
## three; `clew/kconfig_env.py` carries the measurements.
with parse_environment(root) as refusals:
import kconfiglib
kconf = kconfiglib.Kconfig(str(location.path), warn_to_stderr=False)
## COPIED INSIDE THE BLOCK. The list is cleared when the context exits, and a
## parse that raises must still carry its refusals out — a refused expansion is a
## plausible CAUSE of the failure, so losing it on the error path loses the
## explanation exactly when it is needed.
refused = list(refusals)
except Exception as exc:
logger.warning("kconfig: %s could not be parsed (%s)", location.path, exc)
return KconfigModel(
location=location,
error=_served_parse_error(exc),
shell_refused=tuple(refused),
)
escaped = _sourced_outside(kconf, root)
if escaped:
return KconfigModel(
location=location,
error=(
f"refused: this Kconfig sources {len(escaped)} file(s) outside the "
f"repository ({', '.join(escaped)}), so no configuration space was indexed"
),
shell_refused=tuple(refused),
)
return _model_from_kconf(kconf, location, tuple(refused))
Activity · 16 steps
Requirements
store_kconfig
int clew.kconfig.store_kconfig(Path db_path, KconfigModel model)
Persist a parsed configuration space into the index.
Source · 39 lines
def store_kconfig(db_path: Path, model: KconfigModel) -> int:
"""CREATES THE TABLES EVEN WHEN THERE IS NOTHING TO PUT IN THEM, as long as a
Kconfig was FOUND. An empty table and an absent table say different things: the
first is "we looked and this repo declares nothing", the second is "this layer
never ran". A consumer distinguishing a correct negative from a detector failure
needs both, and this repo has recorded the wrong one three times.
A repo with NO Kconfig gets no tables at all, so its schema and its query results
are byte-identical to a build before this module existed.
@brief Write the Kconfig structure tables.
@return Symbol row count.
@version 1
"""
if not model.found:
return 0
conn = sqlite3.connect(str(db_path))
try:
ensure_kconfig_tables(conn)
conn.executemany(
"INSERT OR REPLACE INTO kconfig_choices"
"(key, name, prompt, default_expr, file_path, line) VALUES(?,?,?,?,?,?)",
[(c.key, c.name, c.prompt, c.default, c.file_path, c.line) for c in model.choices],
)
conn.executemany(
"INSERT OR REPLACE INTO kconfig_symbols"
"(name, type, prompt, help, default_expr, choice_key, file_path, line) "
"VALUES(?,?,?,?,?,?,?,?)",
[
(s.name, s.type, s.prompt, s.help, s.default, s.choice_key, s.file_path, s.line)
for s in model.symbols
],
)
conn.commit()
finally:
conn.close()
return len(model.symbols)