impact.py¶
clew/guard/impact.py
Change-impact analysis from git diff.
_cell
str clew.guard.impact._cell(str text)
Make one table cell out of repo-controlled text.
Source · 5 lines
def _cell(text: str) -> str:
collapsed = text.replace("\r", " ").replace("\n", " ").replace("\t", " ")
return collapsed.replace("|", "\\|")
Activity · 2 steps
Flows
_collect_changed_lines
set[int] clew.guard.impact._collect_changed_lines(str file_path, bool staged, str|None diff_range, RunCommand|None run_command)
Collect all changed lines for a file from branch diff and/or staged changes.
Source · 19 lines
def _collect_changed_lines(
file_path: str,
staged: bool,
diff_range: str | None,
run_command: RunCommand | None,
) -> set[int]:
changed: set[int] = set()
diff_output = _get_file_diff(file_path, staged, diff_range, run_command)
if diff_output:
changed.update(parse_changed_lines(diff_output))
if diff_range and not staged:
staged_output = _get_file_diff(
file_path, staged=True, diff_range=None, run_command=run_command
)
if staged_output:
changed.update(parse_changed_lines(staged_output))
return changed
Activity · 9 steps
Flows
_extract_changed_functions
list[ChangedFunction] clew.guard.impact._extract_changed_functions(str file_path, dict[str, Any] config, set[int] changed_lines)
Find changed functions in a single file given changed line numbers.
Source · 33 lines
def _extract_changed_functions(
file_path: str,
config: dict[str, Any],
changed_lines: set[int],
) -> list[ChangedFunction]:
functions = parse_source_file(file_path, config)
if functions is None:
return []
result: list[ChangedFunction] = []
for func in functions:
start = func.doxygen.start_line if func.doxygen else func.def_line
func_lines = set(range(start, func.body_end + 1))
if not func_lines & changed_lines:
continue
reqs = func.doxygen.tags.get("req", []) if func.doxygen else []
version = None
if func.doxygen and "version" in func.doxygen.tags:
version = func.doxygen.tags["version"][0]
result.append(
ChangedFunction(
name=func.name,
file_path=file_path,
reqs=reqs,
new_version=version,
qualified=func.qualified,
)
)
return result
Activity · 15 steps
Requirements
Flows
_get_file_diff
str | None clew.guard.impact._get_file_diff(str file_path, bool staged, str|None diff_range, RunCommand|None run_command)
Get raw diff output for a single file.
Source · 15 lines
def _get_file_diff(
file_path: str,
staged: bool,
diff_range: str | None,
run_command: RunCommand | None,
) -> str | None:
# git.run_git owns the failure contract and returns None; no local except tuple to
# drift onto a narrower set.
if staged:
return get_staged_diff(file_path, run_command)
if diff_range:
return get_diff(file_path, diff_range, run_command)
return None
Activity · 5 steps
Flows
_get_requirements_config
tuple[str, str, str, str] | None clew.guard.impact._get_requirements_config(dict[str, Any] config)
Extract requirements config, raising if a declared catalog is unusable.
Source · 34 lines
def _get_requirements_config(
config: dict[str, Any],
) -> tuple[str, str, str, str] | None:
req_config = get_requirements(config)
if not req_config:
logger.info("No requirements section declared; catalog features are off")
return None
req_file = req_config.get("file")
if not req_file:
# GH #68: a repository whose catalogue its consumer owns names only `external`.
if req_config.get("external"):
return None
raise RequirementsError(
"impact.requirements is declared but neither impact.requirements.file nor "
"impact.requirements.external is"
)
# Containment before open(): the catalog path is repo-controlled, and its rows are
# echoed back in validation errors. Without this, pointing it at any readable file
# turned the error channel into a file-disclosure primitive.
resolve_contained_path(req_file, setting="impact.requirements.file")
if not Path(req_file).exists():
raise RequirementsError(f"Requirements catalog not found: {req_file}")
fmt = req_config.get("format", REQUIREMENTS_FORMAT_DEFAULT)
logger.info("Requirements catalog: %s (format=%s)", req_file, fmt)
return (
req_file,
fmt,
req_config.get("id_column", REQUIREMENTS_ID_COLUMN_DEFAULT),
req_config.get("name_column", REQUIREMENTS_NAME_COLUMN_DEFAULT),
)
Activity · 15 steps
Requirements
Flows
_load_csv_full
dict[str, dict[str, str]] clew.guard.impact._load_csv_full(str path, str id_col)
Parse CSV file into req_id -> full row mapping.
Source · 18 lines
def _load_csv_full(path: str, id_col: str) -> dict[str, dict[str, str]]:
reqs: dict[str, dict[str, str]] = {}
with open(path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
if reader.fieldnames is not None and id_col not in reader.fieldnames:
raise RequirementsError(
f"Requirements catalog {path}: id_column {id_col!r} is not in the header "
f"({', '.join(reader.fieldnames)})"
)
for row in reader:
# A row shorter than the header yields None values (csv restval), which
# used to raise AttributeError on .strip().
req_id = (row.get(id_col) or "").strip()
if req_id:
reqs[req_id] = {k: (v or "").strip() for k, v in row.items()}
return reqs
Activity · 10 steps
Requirements
_load_yaml_full
dict[str, dict[str, str]] clew.guard.impact._load_yaml_full(str path, str id_col)
Parse a YAML catalog into req_id -> full row mapping.
Source · 18 lines
def _load_yaml_full(path: str, id_col: str) -> dict[str, dict[str, str]]:
try:
with open(path) as f:
data = yaml.safe_load(f)
except (OSError, yaml.YAMLError) as e:
raise RequirementsError(f"Could not read requirements catalog {path}: {e}") from e
if isinstance(data, dict) and REQUIREMENTS_ROOT_KEY in data:
return _rows_from_mapping(data[REQUIREMENTS_ROOT_KEY], path)
if isinstance(data, list):
logger.info("%s uses the flat list form; the mapping form is preferred", path)
return _rows_from_list(data, id_col)
raise RequirementsError(
f"Requirements catalog {path} must be a mapping with a top-level "
f"'{REQUIREMENTS_ROOT_KEY}:' key, or a list of rows"
)
Activity · 11 steps
Requirements
_markdown_row
str clew.guard.impact._markdown_row(ImpactEntry entry, bool owned, bool tested)
One requirement's table row.
Source · 12 lines
def _markdown_row(entry: ImpactEntry, owned: bool, tested: bool) -> str:
name = _cell(entry.req_name or "\u2014")
func_names = ", ".join(
_cell(f.name) + (f" (via {_cell(' → '.join(f.via))})" if f.via else "")
for f in entry.functions
)
dash = chr(0x2014)
who = f" {', '.join(_cell(r) for r in entry.reviewers or []) or dash} |" if owned else ""
tests = f" {', '.join(_cell(t.name) for t in entry.tests or []) or dash} |" if tested else ""
return f"| {_cell(entry.req_id)} | {name} | {func_names} |{who}{tests}"
Activity · 6 steps
Flows
_place_untagged
None clew.guard.impact._place_untagged(ChangedFunction cf, Any reach, dict[str, list[ChangedFunction]] req_funcs, Any extras)
File an untagged change under the requirements its callers reach, else as unmapped.
Source · 27 lines
def _place_untagged(
cf: ChangedFunction, reach: Any, req_funcs: dict[str, list[ChangedFunction]], extras: Any
) -> None:
from .reach import NO_CALLER, NO_INDEX, TEST_CODE
if reach.is_test(cf.file_path):
extras.unmapped.append({"name": cf.name, "file": cf.file_path, "reason": TEST_CODE})
return
## ONE FUNCTION, TWO PLACES (2.2, clew#76): a declaration whose definition carries `@req`
## (or the reverse) is linked by those requirements directly, as coverage counts it (PG2).
own = reach.own_reqs(cf)
if own:
for req_id in own:
req_funcs.setdefault(req_id, []).append(
ChangedFunction(cf.name, cf.file_path, [req_id], cf.old_version, cf.new_version)
)
return
reached = reach.via(cf)
for req_id, chain in reached:
req_funcs.setdefault(req_id, []).append(
ChangedFunction(cf.name, cf.file_path, [], cf.old_version, cf.new_version, chain)
)
if not reached:
reason = NO_INDEX if reach.db is None else NO_CALLER
extras.unmapped.append({"name": cf.name, "file": cf.file_path, "reason": reason})
Activity · 15 steps
Flows
_raw_entries
list[tuple[str, dict[str, Any]]] clew.guard.impact._raw_entries(Any data, str id_col)
A catalogue's entries as (id, raw fields), in either catalogue shape.
Source · 9 lines
def _raw_entries(data: Any, id_col: str) -> list[tuple[str, dict[str, Any]]]:
if isinstance(data, dict) and isinstance(data.get(REQUIREMENTS_ROOT_KEY), dict):
node = data[REQUIREMENTS_ROOT_KEY]
return [(str(k), v) for k, v in node.items() if isinstance(v, dict)]
if isinstance(data, list):
return [(str(r[id_col]), r) for r in data if isinstance(r, dict) and r.get(id_col)]
return []
Activity · 6 steps
Flows
_reviewers
list[str] | None clew.guard.impact._reviewers(OwnerResolver|None owners, list[ChangedFunction] funcs)
The owners of a requirement's changed files, first-seen order, each once.
Source · 10 lines
def _reviewers(owners: OwnerResolver | None, funcs: list[ChangedFunction]) -> list[str] | None:
if owners is None or not owners.has_sources():
return None
names: dict[str, None] = {}
for cf in funcs:
for owner, *_rest in owners.owners_of(cf.file_path):
names.setdefault(owner, None)
return list(names)
Activity · 7 steps
Flows
_rows_from_list
dict[str, dict[str, str]] clew.guard.impact._rows_from_list(list data, str id_col)
Convert a list of flat row mappings into req_id -> row form.
Source · 4 lines
def _rows_from_list(data: list, id_col: str) -> dict[str, dict[str, str]]:
return {str(row[id_col]): row for row in data if isinstance(row, dict) and row.get(id_col)}
Activity · 1 steps
Requirements
_rows_from_mapping
dict[str, dict[str, str]] clew.guard.impact._rows_from_mapping(Any node, str path)
Convert a requirements mapping node into id -> row form.
Source · 17 lines
def _rows_from_mapping(node: Any, path: str) -> dict[str, dict[str, str]]:
if not isinstance(node, dict):
raise RequirementsError(
f"Requirements catalog {path}: '{REQUIREMENTS_ROOT_KEY}' must be a mapping "
f"keyed by requirement ID, got {type(node).__name__}"
)
rows: dict[str, dict[str, str]] = {}
for req_id, fields in node.items():
if not isinstance(fields, dict):
raise RequirementsError(
f"Requirements catalog {path}: {req_id} must be a mapping of fields, "
f"got {type(fields).__name__}"
)
rows[str(req_id)] = {k: str(v) for k, v in fields.items()}
return rows
Activity · 8 steps
Requirements
_summarise_id
str clew.guard.impact._summarise_id(str req_id)
Render a catalog key for an error message, truncated and single-line.
Source · 7 lines
def _summarise_id(req_id: str) -> str:
flat = " ".join(str(req_id).split())
if len(flat) > _MAX_ID_CHARS:
flat = flat[:_MAX_ID_CHARS] + "..."
return repr(flat)
Activity · 4 steps
Requirements
Flows
_unmapped_markdown
str clew.guard.impact._unmapped_markdown(ImpactExtras|None extras)
The unmapped sections: changes and files that reach no requirement.
Source · 16 lines
def _unmapped_markdown(extras: ImpactExtras | None) -> str:
if extras is None:
return ""
lines: list[str] = []
if extras.unmapped:
lines += ["", "### Changes that reach no requirement", ""]
lines += [
f"- `{_cell(u['name'])}` ({_cell(u['file'])}): {_cell(u['reason'])}"
for u in extras.unmapped
]
if extras.unmapped_files:
lines += ["", "### Changed files with no changed function", ""]
lines += [f"- {_cell(f)}" for f in extras.unmapped_files]
return "\n".join(lines) + ("\n" if lines else "")
Activity · 10 steps
Flows
_validate_requirements
None clew.guard.impact._validate_requirements(dict[str, dict[str, str]] reqs, str path, dict[str, Any] config, str name_col)
Enforce the name field and the configured ID pattern across a catalog.
Source · 27 lines
def _validate_requirements(
reqs: dict[str, dict[str, str]],
path: str,
config: dict[str, Any],
name_col: str,
) -> None:
id_pattern = get_validate(config).get("tags", {}).get("req", {}).get("pattern")
problems: list[str] = []
for req_id, row in reqs.items():
shown = _summarise_id(req_id)
if id_pattern and not re.fullmatch(id_pattern, req_id):
problems.append(f"{shown}: does not match validate.tags.req.pattern '{id_pattern}'")
if not str(row.get(name_col, "")).strip():
problems.append(f"{shown}: missing required field '{name_col}'")
if not problems:
return
reported = problems[:_MAX_REPORTED_PROBLEMS]
if len(problems) > len(reported):
reported.append(f"... and {len(problems) - len(reported)} more problem(s)")
for p in reported:
logger.error("Requirements catalog error in %s: %s", path, p)
raise RequirementsError(f"Invalid requirements catalog {path}", reported)
Activity · 16 steps
Requirements
Flows
build_impact_report
list[ImpactEntry] clew.guard.impact.build_impact_report(list[ChangedFunction] changed_functions, dict[str, Any] config, OwnerResolver|None owners=None)
Group changed functions by requirement for the impact report.
Source · 8 lines
def build_impact_report(
changed_functions: list[ChangedFunction],
config: dict[str, Any],
owners: OwnerResolver | None = None,
) -> list[ImpactEntry]:
return build_report(changed_functions, config, owners)[0]
Activity · 1 steps
Requirements
build_report
tuple[list[ImpactEntry], ImpactExtras | None] clew.guard.impact.build_report(list[ChangedFunction] changed_functions, dict[str, Any] config, OwnerResolver|None owners=None, Any reach=None, list[str]|None unmapped_files=None)
Group changes by requirement, and with a reach step, add tests, via and unmapped.
Called by build_impact_report, impact_report
Tested by
Source · 29 lines
def build_report(
changed_functions: list[ChangedFunction],
config: dict[str, Any],
owners: OwnerResolver | None = None,
reach: Any = None,
unmapped_files: list[str] | None = None,
) -> tuple[list[ImpactEntry], ImpactExtras | None]:
req_names = load_requirements(config)
extras = ImpactExtras(unmapped_files=list(unmapped_files or [])) if reach else None
req_funcs: dict[str, list[ChangedFunction]] = {}
for cf in changed_functions:
for req in cf.reqs:
req_funcs.setdefault(req, []).append(cf)
if not cf.reqs and reach is not None:
_place_untagged(cf, reach, req_funcs, extras)
tests = reach.tests_for(set(req_funcs), set(req_names)) if reach else {}
entries = [
ImpactEntry(
req_id=req_id,
req_name=req_names.get(req_id),
functions=funcs,
reviewers=_reviewers(owners, funcs),
tests=list(tests.get(req_id, [])) if reach else None,
)
for req_id, funcs in sorted(req_funcs.items())
]
return entries, extras
Activity · 11 steps
Requirements
Flows
collect_changed_functions
list[ChangedFunction] clew.guard.impact.collect_changed_functions(list[str] file_paths, dict[str, Any] config, str|None diff_range=None, bool staged=False, RunCommand|None run_command=None)
Parse source files and cross-reference with git diff to find changed functions.
Source · 10 lines
def collect_changed_functions(
file_paths: list[str],
config: dict[str, Any],
diff_range: str | None = None,
staged: bool = False,
run_command: RunCommand | None = None,
) -> list[ChangedFunction]:
return collect_changes(file_paths, config, diff_range, staged, run_command)[0]
Activity · 1 steps
Requirements
collect_changes
tuple[list[ChangedFunction], list[str]] clew.guard.impact.collect_changes(list[str] file_paths, dict[str, Any] config, str|None diff_range=None, bool staged=False, RunCommand|None run_command=None)
The changed functions, and the changed files that hold none of them.
Called by collect_changed_functions, impact_report
Tested by
Source · 27 lines
def collect_changes(
file_paths: list[str],
config: dict[str, Any],
diff_range: str | None = None,
staged: bool = False,
run_command: RunCommand | None = None,
) -> tuple[list[ChangedFunction], list[str]]:
changed_funcs: list[ChangedFunction] = []
unmapped_files: list[str] = []
for file_path in file_paths:
## A REGULAR FILE OR NOTHING IS OPENED (2.2, clew#75): a submodule bump names the gitlink,
## which exists as a DIRECTORY, so `exists()` let it through to be parsed as source and
## IsADirectoryError ended the report. Deleted files and gitlinks alike are unmapped.
if not Path(file_path).is_file():
logger.warning("Not a regular file (deleted, or a submodule): %s", file_path)
unmapped_files.append(file_path)
continue
changed_lines = _collect_changed_lines(file_path, staged, diff_range, run_command)
found = (
_extract_changed_functions(file_path, config, changed_lines) if changed_lines else []
)
changed_funcs.extend(found)
if changed_lines and not found:
unmapped_files.append(file_path)
return changed_funcs, unmapped_files
Activity · 13 steps
Requirements
Flows
filter_requirements_by_version
dict[str, dict[str, str]] clew.guard.impact.filter_requirements_by_version(dict[str, dict[str, str]] reqs, dict[str, Any] config)
Filter requirements to those active at the configured current version.
Called by _has_active_requirements
Tested by
Calls _summarise_id, compare_versions, get_requirements, get_validate, parse_version
Source · 38 lines
def filter_requirements_by_version(
reqs: dict[str, dict[str, str]],
config: dict[str, Any],
) -> dict[str, dict[str, str]]:
from .config import compare_versions, parse_version
validate = get_validate(config)
current_str = validate.get("_current_version_resolved") or validate.get("current_version")
version_field = get_requirements(config).get("version_field")
if not current_str or not version_field:
return reqs
# A missing field used to default to "v0.0.0", so a typo'd version_field — or rows
# that simply omit it — silently made EVERY requirement active. The gate then
# appeared to work while enforcing nothing.
missing = sorted(
rid for rid, row in reqs.items() if not str(row.get(version_field, "")).strip()
)
if missing:
problems = [_summarise_id(rid) for rid in missing[:_MAX_REPORTED_PROBLEMS]]
if len(missing) > len(problems):
problems.append(f"... and {len(missing) - len(problems)} more")
logger.error("version_field %r missing on %d requirement(s)", version_field, len(missing))
raise RequirementsError(
f"requirements.version_field is {version_field!r} but these "
f"requirements do not declare it",
problems,
)
current = parse_version(current_str)
return {
rid: row
for rid, row in reqs.items()
if compare_versions(parse_version(row[version_field]), current) <= 0
}
Activity · 15 steps
Requirements
Flows
format_json
str clew.guard.impact.format_json(list[ImpactEntry] entries, ImpactExtras|None extras=None)
Render impact entries as a versioned JSON object.
Source · 29 lines
def format_json(entries: list[ImpactEntry], extras: ImpactExtras | None = None) -> str:
rows = [
{
"req_id": entry.req_id,
"req_name": entry.req_name,
"functions": [
{
"name": f.name,
"file": f.file_path,
"version": f.new_version,
**({"via": f.via} if f.via is not None else {}),
}
for f in entry.functions
],
**({"reviewers": entry.reviewers} if entry.reviewers is not None else {}),
**(
{"tests": [{"name": t.name, "file": t.file} for t in entry.tests]}
if entry.tests is not None
else {}
),
}
for entry in entries
]
data: dict[str, Any] = {"schema_version": IMPACT_SCHEMA_VERSION, "entries": rows}
if extras is not None:
data.update(unmapped=extras.unmapped, unmapped_files=extras.unmapped_files)
return json.dumps(data, indent=2) + "\n"
Activity · 5 steps
Requirements
Flows
format_markdown
str clew.guard.impact.format_markdown(list[ImpactEntry] entries, ImpactExtras|None extras=None)
Render impact entries as a markdown table with summary.
Source · 23 lines
def format_markdown(entries: list[ImpactEntry], extras: ImpactExtras | None = None) -> str:
if not entries:
return ("No requirements affected.\n" + _unmapped_markdown(extras)).rstrip("\n") + "\n"
## A Reviewers column only when the repository names owners: see `_reviewers`. A Tests column
## only when the report read them.
owned = any(e.reviewers is not None for e in entries)
tested = any(e.tests is not None for e in entries)
head = "| REQ | Name | Functions Changed |" + (" Reviewers |" if owned else "")
rule = "|-----|------|-------------------|" + ("-----------|" if owned else "")
lines = ["## Change Impact Report", "", head + (" Tests |" if tested else "")]
lines.append(rule + ("-------|" if tested else ""))
total_funcs = 0
for entry in entries:
total_funcs += len(entry.functions)
lines.append(_markdown_row(entry, owned, tested))
lines.append("")
lines.append(
f"**Total: {len(entries)} requirement(s) affected, {total_funcs} function(s) changed**"
)
return "\n".join(lines) + "\n" + _unmapped_markdown(extras)
Activity · 15 steps
Requirements
Flows
format_report
str clew.guard.impact.format_report(list[ImpactEntry] entries, str fmt="markdown", ImpactExtras|None extras=None)
Dispatch to the appropriate formatter based on config.
Source · 8 lines
def format_report(
entries: list[ImpactEntry], fmt: str = "markdown", extras: ImpactExtras | None = None
) -> str:
if fmt == "text":
return format_text(entries)
return (format_json if fmt == "json" else format_markdown)(entries, extras)
Activity · 3 steps
Flows
format_text
str clew.guard.impact.format_text(list[ImpactEntry] entries)
Render impact entries as human-readable text.
Source · 7 lines
def format_text(entries: list[ImpactEntry]) -> str:
if not entries:
return "No requirements affected.\n"
req_ids = [e.req_id for e in entries]
return f"REQs affected: {', '.join(req_ids)}\n"
Activity · 4 steps
Requirements
impact_entries
list[ImpactEntry] clew.guard.impact.impact_entries(list[str] file_paths, dict[str, Any] config, bool staged=False, str|None diff_range=None, RunCommand|None run_command=None)
Collect the changed functions and map them to the requirements they implement.
Source · 10 lines
def impact_entries(
file_paths: list[str],
config: dict[str, Any],
staged: bool = False,
diff_range: str | None = None,
run_command: RunCommand | None = None,
) -> list[ImpactEntry]:
return impact_report(file_paths, config, staged, diff_range, run_command)[0]
Activity · 1 steps
Requirements
impact_report
tuple[list[ImpactEntry], ImpactExtras | None] clew.guard.impact.impact_report(list[str] file_paths, dict[str, Any] config, bool staged=False, str|None diff_range=None, RunCommand|None run_command=None)
The full report: entries with covering tests and via , and the unmapped lists.
Called by _run_impact_command, impact_entries, run_impact, run_precommit
Calls build_report, collect_changes, find_index, get_changed_files
Source · 19 lines
def impact_report(
file_paths: list[str],
config: dict[str, Any],
staged: bool = False,
diff_range: str | None = None,
run_command: RunCommand | None = None,
) -> tuple[list[ImpactEntry], ImpactExtras | None]:
from ..indexlocate import find_index
from .reach import Reach
if not file_paths and (staged or diff_range):
from .git import get_changed_files
file_paths = get_changed_files(diff_range, staged, run_command) or []
changed, unmapped_files = collect_changes(file_paths, config, diff_range, staged, run_command)
root = Path.cwd()
owners = OwnerResolver.from_repo(root, config.get("owners"))
reach = Reach(find_index(root), repo_root=root, config=config)
return build_report(changed, config, owners, reach, unmapped_files)1 more lines, not shown
Activity · 10 steps
Requirements
Flows
load_external_requirements
dict[str, dict[str, str]] clew.guard.impact.load_external_requirements(dict[str, Any] config, list[str]|None unchecked=None)
The requirement ids of the external catalogues this repository names (GH #68).
Source · 34 lines
def load_external_requirements(
config: dict[str, Any], unchecked: list[str] | None = None
) -> dict[str, dict[str, str]]:
"""The consumer's catalogue, read where it is pinned: each entry is a path or {repo, rev,
path} relative to the repository, through the reader the wiki uses. An unreadable one or a
URL is an error naming it, never an empty catalogue that would pass every tag.
A PARENT (`parent: true`, #73 item 3, owner Q/A 2026-11-24) is the one exception: a module's
gate runs where the product's clone may not be, so an unreadable parent is recorded in
`unchecked` (by name) and its links are reported unchecked, never refused. The product's own
gate, where the clone is, still checks them."""
from ..requirements import read_catalog_at
req_config = get_requirements(config)
out: dict[str, dict[str, str]] = {}
for source in req_config.get("external") or []:
try:
out.update(read_catalog_at(Path.cwd(), source))
except ValueError as exc:
if isinstance(source, dict) and source.get("parent") is True and unchecked is not None:
name = str(source.get("name") or Path(str(source.get("repo", "parent"))).name)
logger.warning(
"parent catalogue %s is not readable here (%s); its links are unchecked",
name,
exc,
)
unchecked.append(name)
continue
raise RequirementsError(f"impact.requirements.external: {exc}") from exc
if out:
logger.info("Loaded %d requirement(s) from external catalogues", len(out))
return out
Activity · 16 steps
Requirements
Flows
load_failure_mode_ids
set[str] clew.guard.impact.load_failure_mode_ids(dict[str, Any] config)
Every failure-mode id the local catalogue declares.
Source · 18 lines
def load_failure_mode_ids(config: dict[str, Any]) -> set[str]:
from ..failuremodes import modes_of
req_info = _get_requirements_config(config)
if req_info is None or req_info[1] == "csv":
return set()
path, fmt, id_col, _name = req_info
try:
with open(path) as f:
data = json.load(f) if fmt == "json" else yaml.safe_load(f)
entries = _raw_entries(data, id_col)
return {m.mode_id for rid, fields in entries for m in modes_of(rid, fields)}
except ValueError as e:
raise RequirementsError(f"Requirements catalog {path}: {e}") from e
except (OSError, yaml.YAMLError) as e:
raise RequirementsError(f"Could not read requirements catalog {path}: {e}") from e
Activity · 14 steps
Requirements
Flows
load_requirements
dict[str, str] clew.guard.impact.load_requirements(dict[str, Any] config)
Load requirement id -> name mapping (convenience wrapper).
Called by build_report
Tested by 18 tests
test_csv_missing_id_column_names_the_problem, test_csv_short_row_does_not_crash, test_declared_without_file_raises, test_id_failing_configured_pattern_raises, test_json_list_with_non_dict_element_does_not_crash, test_json_object_instead_of_list_raises, test_load_csv, test_load_json, test_load_yaml, test_malformed_json_raises_requirements_error, test_mapping_form_loads, test_missing_file_raises
Source · 9 lines
def load_requirements(config: dict[str, Any]) -> dict[str, str]:
req_info = _get_requirements_config(config)
if req_info is None:
return {}
name_col = req_info[3]
full = load_requirements_full(config)
return {rid: row.get(name_col, "") for rid, row in full.items()}
Activity · 6 steps
Requirements
Flows
load_requirements_full
dict[str, dict[str, str]] clew.guard.impact.load_requirements_full(dict[str, Any] config)
Load full requirement rows from the configured catalog.
Called by _has_active_requirements, _validate_files, analyze_coverage, load_requirements
Tested by
Source · 36 lines
def load_requirements_full(config: dict[str, Any]) -> dict[str, dict[str, str]]:
req_info = _get_requirements_config(config)
if req_info is None:
return {}
path, fmt, id_col, name_col = req_info
loaders = {
"csv": _load_csv_full,
"json": _load_json_full,
"yaml": _load_yaml_full,
}
loader = loaders.get(fmt)
if not loader:
raise RequirementsError(
f"Unknown requirements format '{fmt}' for {path}; "
f"expected one of {', '.join(sorted(loaders))}"
)
try:
reqs = loader(path, id_col)
except RequirementsError:
raise
except (OSError, UnicodeDecodeError, ValueError, AttributeError, KeyError) as e:
# One wrapper for all three loaders: previously only the YAML path wrapped its
# failures, so a malformed CSV or JSON catalog escaped the GuardError boundary
# as a raw traceback for the same class of user error.
raise RequirementsError(f"Could not parse requirements catalog {path}: {e}") from e
if not reqs:
raise RequirementsError(f"Requirements catalog {path} declared no requirements")
_validate_requirements(reqs, path, config, name_col)
logger.info("Loaded %d requirement(s) from %s", len(reqs), path)
return reqs
# A malformed catalog should tell you what is wrong without echoing the file back.
# Reported problems are capped and each key is truncated, so the error channel cannot
# be used to read a file the caller pointed the catalog setting at.Activity · 19 steps
Requirements
Flows
run_impact
str clew.guard.impact.run_impact(list[str] file_paths, dict[str, Any] config, bool staged=False, str|None diff_range=None, RunCommand|None run_command=None, str fmt="markdown")
Orchestrate diff analysis, requirement mapping, and report generation.
Source · 12 lines
def run_impact(
file_paths: list[str],
config: dict[str, Any],
staged: bool = False,
diff_range: str | None = None,
run_command: RunCommand | None = None,
fmt: str = "markdown",
) -> str:
entries, extras = impact_report(file_paths, config, staged, diff_range, run_command)
return format_report(entries, fmt, extras)