config.py¶
clew/wiki/config.py
The `wiki:` section of `.clew.yaml`: what the site holds, validated by name.
_audiences
_audiences(raw: Any, problems: list[str])
Source · 11 lines
def _audiences(raw: Any, problems: list[str]) -> dict[str, Audience]:
"""@brief Parse audiences. @return Rules by name."""
out = {}
for name, rules in (raw if isinstance(raw, dict) else {}).items():
problems += _unknown(rules or {}, _AUDIENCE, f"wiki.audiences.{name}")
out[str(name)] = Audience(
exclude_bodies=bool((rules or {}).get("exclude_bodies")),
exclude_requirement_text=bool((rules or {}).get("exclude_requirement_text")),
exclude_owners=bool((rules or {}).get("exclude_owners")),
)
return outActivity · 5 steps
Flows
_comments
_comments(raw: Any, problems: list[str])
Source · 23 lines
def _comments(raw: Any, problems: list[str]) -> tuple[str, ...]:
"""A CLOSED VOCABULARY, refused by name: a route outside `COMMENT_DELIVERY`, a key other than
`deliver`, or a string where the list belongs (F5) is a problem, never a silent default.
@brief Comment delivery.
@return Routes.
"""
if raw is None:
return ("hook",)
if not isinstance(raw, dict) or set(raw) - {"deliver"}:
extra = sorted(set(raw) - {"deliver"}) if isinstance(raw, dict) else raw
problems.append(f"`wiki.comments` takes only `deliver`; got {extra!r}")
return ("hook",)
routes = raw.get("deliver", ["hook"])
if not isinstance(routes, list) or not all(isinstance(r, str) for r in routes):
problems.append("`wiki.comments.deliver` must be a list of " + ", ".join(COMMENT_DELIVERY))
return ("hook",)
unknown = [r for r in routes if r not in COMMENT_DELIVERY]
if unknown:
problems.append(
f"`wiki.comments.deliver` names {unknown!r}; the routes are {', '.join(COMMENT_DELIVERY)}"
)
return tuple(dict.fromkeys(r for r in routes if r in COMMENT_DELIVERY))Activity · 14 steps
Flows
_declared_report
_declared_report(path: Path)
Source · 18 lines
def _declared_report(path: Path) -> str | None:
"""AN OUT-OF-TREE CONFIG (`clew wiki build --config FILE`) carries its own `guard:` section, so
the report directory is read from that file rather than from the repository's (R5-CFG F9).
@brief Read `guard.impact.report_dir` from this file.
@return Path string or None.
"""
from ..guard.config import REPORT_JSON, read_guard_section
from ..guard.errors import ConfigError
if not path.is_file():
return None
try:
guard = read_guard_section(path) or {}
except ConfigError:
return None
declared = (guard.get("impact") or {}).get("report_dir") if isinstance(guard, dict) else None
return str(Path(str(declared)) / REPORT_JSON) if declared else NoneActivity · 10 steps
Flows
_doc_kinds
_doc_kinds(raw: Any, problems: list[str])
Source · 12 lines
def _doc_kinds(raw: Any, problems: list[str]) -> tuple[tuple[str, str], ...]:
"""@brief Parse kinds. @return Pairs."""
if not isinstance(raw, dict):
problems.append("`wiki.doc_kinds` must map a path glob to a kind")
return ()
out = []
for glob, kind in raw.items():
if kind not in DOC_KINDS:
problems.append(f"`wiki.doc_kinds.{glob}` must be one of {', '.join(DOC_KINDS)}")
continue
out.append((str(glob), str(kind)))
return tuple(out)Activity · 10 steps
Flows
_doc_tags
_doc_tags(path: Path)
Source · 5 lines
def _doc_tags(path: Path) -> tuple[str, ...]:
"""@brief Read the declared tags. @return Names."""
validate = (_top_level(path, "guard").get("validate") or {}) if path else {}
tags = validate.get("extra_tags") if isinstance(validate, dict) else None
return tuple(str(t).lstrip("@") for t in tags) if isinstance(tags, list) else ()Activity · 3 steps
Flows
_ears
_ears(raw: Any, problems: list[str])
Source · 17 lines
def _ears(raw: Any, problems: list[str]) -> bool:
"""A BOOLEAN, REFUSED OTHERWISE: `ears: 'yes'` is a problem rather than a truthy string, so a
typo cannot turn the badge on or off silently.
@brief Parse `check.ears`.
@return On or off.
"""
if raw is None:
return False
if (
not isinstance(raw, dict)
or set(raw) - {"ears"}
or not isinstance(raw.get("ears", False), bool)
):
problems.append("`wiki.check` must be {ears: true|false}; `wiki.check.ears` is a boolean")
return False
return bool(raw.get("ears", False))Activity · 6 steps
Flows
_infer_depth
_infer_depth(tests: dict[str, Any])
Source · 4 lines
def _infer_depth(tests: dict[str, Any]) -> int | None:
"""@brief Read the cap. @return Depth or None."""
raw = tests.get("infer_depth")
return None if raw is None else int(raw)Activity · 2 steps
Flows
_inputs
_inputs(tests: dict[str, Any], problems: list[str])
Source · 36 lines
def _inputs(tests: dict[str, Any], problems: list[str]) -> EvidenceInputs:
"""A RESULT FORMAT IS DECLARED, so an entry without one is a problem, never a sniffed guess.
@brief Parse imports.
@return Inputs.
@version 5
"""
from .imports import RESULT_FORMATS
results = _entries(tests, "results", _RESULT, ("format", "path"), _result, problems)
problems += [
f"`tests.results`: format {fmt!r} is not known ({', '.join(RESULT_FORMATS)})"
for fmt, _path in results
if fmt not in RESULT_FORMATS
]
layers = tests.get("layers")
if layers is not None and not isinstance(layers, dict):
problems.append("`tests.layers` must map a layer name to path globs")
layers = None
gcov = tests.get("gcov") or ()
return EvidenceInputs(
results=results,
gcov=(str(gcov),) if isinstance(gcov, str) else tuple(str(g) for g in gcov),
mapping=str(tests["mapping"]) if tests.get("mapping") else None,
features=_strings(tests, "features", (), "tests", problems),
layers=None
if layers is None
else tuple((str(k), tuple(str(g) for g in v or ())) for k, v in layers.items()),
min_layers=int(tests["min_layers"]) if tests.get("min_layers") is not None else None,
evidence_fields=tuple(str(f) for f in tests["evidence_fields"] or ())
if "evidence_fields" in tests
else EvidenceInputs.evidence_fields,
infer_depth=_infer_depth(tests),
contexts=str(tests["contexts"]) if tests.get("contexts") else None,
traces=_strings(tests, "traces", (), "tests", problems),
)Activity · 9 steps
Flows
_issues
_issues(raw: Any, problems: list[str])
Source · 23 lines
def _issues(raw: Any, problems: list[str]) -> tuple[str, str] | None:
"""`fetch` MAY STAND ALONE (the tracker then comes from the origin remote) or beside one
tracker; two trackers, or an unknown key, is a problem.
@brief Parse the tracker.
@return Target or None.
"""
if raw is None or raw is False:
return None
trackers = [k for k in raw if k in ("github", "ado")] if isinstance(raw, dict) else []
if not isinstance(raw, dict) or set(raw) - {"github", "ado", "fetch"} or len(trackers) > 1:
problems.append(
"`wiki.issues` must be {github: owner/repo} or {ado: org/project}, optionally with "
"`fetch: true`, or false"
)
return None
if not trackers:
return None
provider, project = trackers[0], raw[trackers[0]]
if not isinstance(project, str) or project.count("/") != 1:
problems.append(f"`wiki.issues.{provider}` must name `<owner-or-org>/<repo-or-project>`")
return None
return str(provider), projectActivity · 13 steps
Flows
_one_of
_one_of(raw: dict, key: str, allowed: tuple[str, ...], problems: list[str])
Source · 9 lines
def _one_of(raw: dict, key: str, allowed: tuple[str, ...], problems: list[str]) -> str:
"""@brief Enumerated value, refused by name. @return Value."""
value = raw.get(key)
if value is None:
return allowed[0]
if value not in allowed:
problems.append(f"`wiki.{key}` must be one of {', '.join(allowed)}, got {value!r}")
return allowed[0]
return str(value)Activity · 7 steps
Flows
_overlaid
_overlaid(raw: dict[str, Any], problems: list[str])
Source · 25 lines
def _overlaid(raw: dict[str, Any], problems: list[str]) -> tuple[dict[str, Any], list[str]]:
"""LAYERS `wiki:` ONLY: an overlay naming `requirements:` or `tests:` is refused by name, since
those stay the repository's. Mappings merge key by key; lists and values are replaced.
@brief Overlay.
@return Pair.
"""
import yaml
path = _OVERLAY.get()
if path is None:
return raw, problems
try:
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
except (OSError, yaml.YAMLError) as exc:
return raw, [*problems, f"--wiki-config {path} could not be read: {exc}"]
if not isinstance(data, dict):
return raw, [*problems, f"--wiki-config {path} must be a mapping with a `wiki:` section"]
extra = sorted(set(data) - {"wiki"})
if extra:
problems = [*problems, f"--wiki-config {path} layers `wiki:` only; it also names {extra}"]
section = data.get("wiki") or {}
if not isinstance(section, dict):
return raw, [*problems, f"--wiki-config {path}: `wiki:` must be a mapping"]
return _merge(raw, section), problemsActivity · 17 steps
Flows
_pinned_catalogs
_pinned_catalogs(requirements: dict[str, Any])
Source · 18 lines
def _pinned_catalogs(requirements: dict[str, Any]) -> tuple[CatalogSpec, ...]:
"""ONE SHAPE (R5-CFG F6): `{repo, rev, path, name?}` replaced `wiki.catalogs`'
`{name, repo, pin, catalog}`. A path-only entry is this repository's own file and adds no
sub-catalogue; a missing `name` is the checkout's directory name.
@brief Pinned catalogues.
@return Specs.
"""
return tuple(
CatalogSpec(
name=str(e.get("name") or Path(str(e["repo"])).name),
repo=str(e["repo"]),
pin=str(e["rev"]),
catalog=str(e["path"]),
)
for e in requirements.get("external") or []
if isinstance(e, dict) and {"repo", "rev", "path"} <= set(e)
)Activity · 1 steps
Flows
_positive
_positive(raw: dict, key: str, default: int, problems: list[str])
Source · 7 lines
def _positive(raw: dict, key: str, default: int, problems: list[str]) -> int:
"""@brief Positive int. @return Value."""
value = raw.get(key, default)
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
problems.append(f"`wiki.{key}` must be a whole number of 1 or more, got {value!r}")
return default
return valueActivity · 5 steps
Flows
_read_section
_read_section(path: Path)
Source · 13 lines
def _read_section(path: Path) -> tuple[dict[str, Any], list[str]]:
"""@brief Read YAML. @return Section and problems."""
import yaml
raw: Any = {}
if path.is_file():
try:
raw = (yaml.safe_load(path.read_text(encoding="utf-8")) or {}).get("wiki") or {}
except (yaml.YAMLError, AttributeError) as exc:
return {}, [f"{path.name} could not be read as YAML: {exc}"]
if not isinstance(raw, dict):
return {}, ["`wiki:` must be a mapping"]
return raw, []Activity · 10 steps
Flows
_renamed
_renamed(mapping: Any, where: str)
Source · 11 lines
def _renamed(mapping: Any, where: str) -> list[str]:
"""@brief Point a renamed or moved key at its new home. @return Problems."""
if not isinstance(mapping, dict):
return []
return [
f"`{where}.{old}` was renamed `{new}` in 2.0.0 — it holds a depth, not a list of entry points"
for old, new in _RENAMED.items()
if old in mapping
] + [
f"`{where}.{old}` moved in 2.0.0 to {new}" for old, new in _MOVED.items() if old in mapping
]Activity · 3 steps
Flows
_requirements_section
_requirements_section(path: Path, problems: list[str])
Source · 16 lines
def _requirements_section(path: Path, problems: list[str]) -> dict[str, Any]:
"""THE GATE'S OWN READER, so the wiki can never accept a catalog section the gate refuses.
@brief Read `requirements:`.
@return Section or {}.
"""
from ..guard.config import read_requirements_section
from ..guard.errors import ConfigError
if not path.is_file():
return {}
try:
return read_requirements_section(path) or {}
except ConfigError as exc:
problems.extend(f"`requirements`: {p}" for p in (exc.problems or [exc.message]))
return {}Activity · 9 steps
Flows
_sbom
_sbom(raw: Any, problems: list[str])
Source · 21 lines
def _sbom(raw: Any, problems: list[str]) -> dict[str, tuple[str, ...]]:
"""LISTS, REFUSED OTHERWISE, and an unknown key is named: `files: sbom.json` (a string) would
otherwise be iterated as characters.
@brief Parse `sbom`.
@return Overrides.
"""
if raw is None:
return {}
out: dict[str, tuple[str, ...]] = {}
keys = {"files": "sbom_files", "accepted": "sbom_accepted"}
if not isinstance(raw, dict) or set(raw) - set(keys):
problems.append("`wiki.sbom` must be {files: [globs], accepted: [licence ids]}")
return {}
for key, attr in keys.items():
if key in raw:
if isinstance(raw[key], list) and all(isinstance(v, str) for v in raw[key]):
out[attr] = tuple(raw[key])
else:
problems.append(f"`wiki.sbom.{key}` must be a list of strings")
return outActivity · 14 steps
Flows
_strings
_strings(
mapping: dict[str, Any], key: str, default: tuple[str, ...], where: str, problems: list[str]
)Source · 22 lines
def _strings(
mapping: dict[str, Any], key: str, default: tuple[str, ...], where: str, problems: list[str]
) -> tuple[str, ...]:
"""ONE RULE FOR EVERY LIST KEY (R5-CFG F5 / W9). Absent takes the default; `[]` (or null) is
an explicit "none"; one string is a one-item list, the precedent `gcov` and `theme.css` set;
anything else is a problem. Before, nine list keys iterated a string into its characters and
`docs: []` silently became the default docs.
@brief Read a string-list key.
@return Strings.
"""
if key not in mapping:
return tuple(default)
value = mapping[key]
if value is None:
return ()
if isinstance(value, str):
return (value,)
if isinstance(value, list) and all(isinstance(v, (str, int, float)) for v in value):
return tuple(str(v) for v in value)
problems.append(f"`{where}.{key}` must be a list of strings (or one string)")
return tuple(default)Activity · 11 steps
Flows
_theme
_theme(raw: Any, problems: list[str])
Source · 37 lines
def _theme(raw: Any, problems: list[str]) -> ThemeSpec:
"""A PALETTE TOKEN THE THEME DOES NOT DEFINE is a problem: it would be a silent no-op.
@brief Parse the theme.
@return Spec.
"""
problems += _unknown(raw, _THEME, "wiki.theme")
if not isinstance(raw, dict):
return ThemeSpec()
palette = raw.get("palette") or {}
if not isinstance(palette, dict):
problems.append("`wiki.theme.palette` must map a token to a colour")
palette = {}
problems += [
f"`wiki.theme.palette`: token {k!r} was renamed {_PALETTE_RENAMED[k]!r} in 2.0.0"
if k in _PALETTE_RENAMED
else f"`wiki.theme.palette`: token {k!r} is not a theme token ({', '.join(THEME_TOKENS)})"
for k in palette
if k not in PALETTE
]
problems += [
f"`wiki.theme.palette.{k}`: {v!r} is not a colour value"
for k, v in palette.items()
if any(c in str(v) for c in ";{}<>")
]
css = raw.get("css") or ()
return ThemeSpec(
name=str(raw.get("name") or "clew"),
palette=tuple(
(PALETTE[k], str(v))
for k, v in palette.items()
if k in PALETTE and not any(c in str(v) for c in ";{}<>")
),
css=(str(css),) if isinstance(css, str) else tuple(str(c) for c in css),
logo=str(raw["logo"]) if raw.get("logo") else None,
fonts=bool(raw.get("fonts", True)),
)Activity · 11 steps
Flows
_top_level
_top_level(path: Path, key: str)
Source · 12 lines
def _top_level(path: Path, key: str) -> dict[str, Any]:
"""@brief Read one top-level section. @return Mapping."""
import yaml
if not path.is_file():
return {}
try:
doc = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
except yaml.YAMLError:
return {}
value = doc.get(key) if isinstance(doc, dict) else None
return value if isinstance(value, dict) else {}Activity · 9 steps
Flows
_tuning
_tuning(raw: dict[str, Any], tests: dict[str, Any], problems: list[str])
Source · 17 lines
def _tuning(raw: dict[str, Any], tests: dict[str, Any], problems: list[str]) -> dict[str, Any]:
"""ONE RULE (R5-CFG, 2.0.0): absent is the former constant; anything but an integer of at least
1 is a problem and the default stands — never a silent 0 that would draw nothing.
@brief Read tuning keys.
@return Keyword arguments.
"""
out = {k: _count(raw, k, d, "wiki", problems) for k, d in TUNING_DEFAULTS.items()}
web = raw.get("web") or {}
problems += _unknown(web, _WEB, "wiki.web")
out["web_max_ring"] = _count(
web if isinstance(web, dict) else {}, "max_ring", 8, "wiki.web", problems
)
out["max_report_mb"] = _count(tests, "max_report_mb", DEFAULT_MAX_REPORT_MB, "tests", problems)
python = raw.get("trace_python")
out["trace_python"] = str(python) if python else None
return outActivity · 8 steps
Flows
_unknown
_unknown(mapping: Any, allowed: set[str], where: str)
Called by _audiences, _entries, _example, _flow, _scenario_item, _theme, _tuning, load_wiki_config
Calls none
Source · 9 lines
def _unknown(mapping: Any, allowed: set[str], where: str) -> list[str]:
"""@brief Name unknown keys. @return Problems."""
if not isinstance(mapping, dict):
return [f"`{where}` must be a mapping"]
return [
f"`{where}.{key}` is not a known key (allowed: {', '.join(sorted(allowed))})"
for key in mapping
if key not in allowed
]Activity · 3 steps
Flows
load_wiki_config
load_wiki_config(
repo_root: Path, config_path: Path | None = None
)Called by _build_site, _comment_routes, _config, _config, _config, _ears_notes, _load, _load, _trace, build_markdown, build_wiki, check_wiki 1 more
trace_test
Tested by 18 tests
test_a_flow_spec_animates_by_default_and_can_opt_out, test_a_malformed_sbom_section_is_refused_by_name, test_a_sub_catalog_is_read_at_its_pin, test_an_overlay_carrying_other_sections_is_refused_by_name, test_an_unknown_doc_kind_is_a_problem, test_body_lines_is_a_setting_and_a_cut_body_links_its_source, test_clew_documents_itself_with_its_own_wiki, test_components_are_declared_in_the_wiki_section, test_external_and_needs_reach_the_wiki_from_the_requirements_section, test_sources_load_nodes_from_toml_mappings_and_yaml_lists, test_test_pages_defaults_to_linked_and_refuses_an_unknown_value, test_the_overlay_merges_over_the_repositorys_wiki_section
Calls _audiences, _comments, _declared_report, _doc_kinds, _doc_tags, _ears, _inputs, _issues, _one_of, _overlaid, _pinned_catalogs, _positive 9 more
_read_section, _renamed, _requirements_section, _sbom, _strings, _theme, _top_level, _tuning, _unknown
Source · 64 lines
def load_wiki_config(
repo_root: Path, config_path: Path | None = None
) -> tuple[WikiConfig, list[str]]:
"""A MISSING SECTION IS A VALID ONE: defaults (the README and docs/ prose, no flows) apply, so a
repository can build a site before it has written a line of configuration.
@brief Load the section.
@return Config and problems.
@version 15
"""
raw, problems = _read_section(Path(config_path or Path(repo_root) / ".clew.yaml"))
## #73 item 5 (2.1): an organisation's `--wiki-config` merged over this repository's section.
raw, problems = _overlaid(raw, problems)
if problems:
return WikiConfig(), problems
problems = _renamed(raw, "wiki") + _unknown(
{k: v for k, v in raw.items() if k not in _RENAMED and k not in _MOVED}, _TOP, "wiki"
)
requirements = _requirements_section(
Path(config_path or Path(repo_root) / ".clew.yaml"), problems
)
flows = tuple(_flow(f, i, problems) for i, f in enumerate(raw.get("flows") or []))
tests = _top_level(Path(config_path or Path(repo_root) / ".clew.yaml"), "tests")
problems += _unknown(tests, set(TESTS_KEYS), "tests")
links = raw.get("links") or {}
problems += _unknown(links, _LINKS, "wiki.links")
config = WikiConfig(
title=str(raw.get("title") or "Wiki"),
docs=_strings(raw, "docs", DEFAULT_DOCS, "wiki", problems),
docs_declared="docs" in raw,
flows=tuple(f for f in flows if f is not None),
junit=_strings(tests, "junit", (), "tests", problems),
coverage=str(tests["coverage"]) if tests.get("coverage") else None,
target_only=_strings(tests, "target_only", (), "tests", problems),
link_template=str(links.get("template") or ""),
audiences=_audiences(raw.get("audiences") or {}, problems),
mutations=str(tests["mutations"]) if tests.get("mutations") else None,
sources=_entries(raw, "sources", _SOURCE, ("name", "path"), _source, problems),
catalogs=_pinned_catalogs(requirements),
rules=_entries(raw, "rules", _RULE, ("id",), _rule, problems),
inputs=_inputs(tests, problems),
theme=_theme(raw.get("theme") or {}, problems),
roadmap=str(raw["roadmap"]) if raw.get("roadmap") else None,
impact=_declared_report(Path(config_path or Path(repo_root) / ".clew.yaml")),
entry_point_depth=int(raw.get("entry_point_depth", 2)),
components=_components(raw.get("components") or {}, problems),
issues=_issues(raw.get("issues"), problems),
issues_enabled=raw.get("issues") is not False,
issues_fetch=isinstance(raw.get("issues"), dict) and bool(raw["issues"].get("fetch")),
ears=_ears(raw.get("check"), problems),
**_sbom(raw.get("sbom"), problems),
test_pages=_one_of(raw, "test_pages", TEST_PAGES, problems),
api=_strings(raw, "api", (), "wiki", problems),
body_lines=_positive(raw, "body_lines", 120, problems),
test_slices=_positive(raw, "test_slices", 1, problems),
comments_deliver=_comments(raw.get("comments"), problems),
doc_tags=_doc_tags(Path(config_path or Path(repo_root) / ".clew.yaml")),
tooling=_strings(raw, "tooling", DEFAULT_TOOLING, "wiki", problems),
needs=str(requirements["needs"]) if requirements.get("needs") else None,
adrs=_strings(raw, "adrs", DEFAULT_ADRS, "wiki", problems),
doc_kinds=_doc_kinds(raw.get("doc_kinds") or {}, problems),
**_tuning(raw, tests, problems),
)
return config, problems