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])

clew/wiki/config.py:629

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 out
Activity · 5 steps
lines 631–631out = {}lines 632–632◇ for name, rules in (raw if isinstance(raw, dict) else {}).items()lines 633–633problems += _unknown(rules or {}, _AUDIENCE, f"wiki.audiences.{name}")lines 634–638out[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")), )lines 639–639return out

Flows

_comments

_comments(raw: Any, problems: list[str])

clew/wiki/config.py:483

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
lines 490–490◇ if raw is Nonelines 491–491return ("hook",)lines 492–492◇ if not isinstance(raw, dict) or set(raw) - {"deliver"}lines 493–493extra = sorted(set(raw) - {"deliver"}) if isinstance(raw, dict) else rawlines 494–494problems.append(f"`wiki.comments` takes only `deliver`; got {extra!r}")lines 495–495return ("hook",)lines 496–496routes = raw.get("deliver", ["hook"])lines 497–497◇ if not isinstance(routes, list) or not all(isinstance(r, str) for r in routes)lines 498–498problems.append("`wiki.comments.deliver` must be a list of " + ", ".join(COMMENT_DELIVERY))lines 499–499return ("hook",)lines 500–500unknown = [r for r in routes if r not in COMMENT_DELIVERY]lines 501–501◇ if unknownlines 502–504problems.append( f"`wiki.comments.deliver` names {unknown!r}; the routes are {', '.join(COMMENT_DELIVERY)}" )lines 505–505return tuple(dict.fromkeys(r for r in routes if r in COMMENT_DELIVERY))

Flows

_declared_report

_declared_report(path: Path)

clew/wiki/config.py:739

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 None
Activity · 10 steps
lines 746–746from ..guard.config import REPORT_JSON, read_guard_sectionlines 747–747from ..guard.errors import ConfigErrorlines 749–749◇ if not path.is_file()lines 750–750return Nonelines 751–751trylines 752–752guard = read_guard_section(path) or {}lines 753–753except ConfigErrorlines 754–754return Nonelines 755–755declared = (guard.get("impact") or {}).get("report_dir") if isinstance(guard, dict) else Nonelines 756–756return str(Path(str(declared)) / REPORT_JSON) if declared else None

Flows

_doc_kinds

_doc_kinds(raw: Any, problems: list[str])

clew/wiki/config.py:1327

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
lines 1329–1329◇ if not isinstance(raw, dict)lines 1330–1330problems.append("`wiki.doc_kinds` must map a path glob to a kind")lines 1331–1331return ()lines 1332–1332out = []lines 1333–1333◇ for glob, kind in raw.items()lines 1334–1334◇ if kind not in DOC_KINDSlines 1335–1335problems.append(f"`wiki.doc_kinds.{glob}` must be one of {', '.join(DOC_KINDS)}")lines 1336–1336continuelines 1337–1337out.append((str(glob), str(kind)))lines 1338–1338return tuple(out)

Flows

_doc_tags

_doc_tags(path: Path)

clew/wiki/config.py:1245

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
lines 1247–1247validate = (_top_level(path, "guard").get("validate") or {}) if path else {}lines 1248–1248tags = validate.get("extra_tags") if isinstance(validate, dict) else Nonelines 1249–1249return tuple(str(t).lstrip("@") for t in tags) if isinstance(tags, list) else ()

Flows

_ears

_ears(raw: Any, problems: list[str])

clew/wiki/config.py:1221

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
lines 1228–1228◇ if raw is Nonelines 1229–1229return Falselines 1230–1233◇ if (lines 1235–1235problems.append("`wiki.check` must be {ears: true|false}; `wiki.check.ears` is a boolean")lines 1236–1236return Falselines 1237–1237return bool(raw.get("ears", False))

Flows

_infer_depth

_infer_depth(tests: dict[str, Any])

clew/wiki/config.py:1121

Show on the map →

Called by _inputs

Calls none

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
lines 1123–1123raw = tests.get("infer_depth")lines 1124–1124return None if raw is None else int(raw)

Flows

_inputs

_inputs(tests: dict[str, Any], problems: list[str])

clew/wiki/config.py:1078

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
lines 1085–1085from .imports import RESULT_FORMATSlines 1087–1087results = _entries(tests, "results", _RESULT, ("format", "path"), _result, problems)lines 1088–1092problems += [ f"`tests.results`: format {fmt!r} is not known ({', '.join(RESULT_FORMATS)})" for fmt, _path in results if fmt not in RESULT_FORMATS ]lines 1093–1093layers = tests.get("layers")lines 1094–1094◇ if layers is not None and not isinstance(layers, dict)lines 1095–1095problems.append("`tests.layers` must map a layer name to path globs")lines 1096–1096layers = Nonelines 1097–1097gcov = tests.get("gcov") or ()lines 1098–1113return 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), )

Flows

_issues

_issues(raw: Any, problems: list[str])

clew/wiki/config.py:1190

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), project
Activity · 13 steps
lines 1197–1197◇ if raw is None or raw is Falselines 1198–1198return Nonelines 1199–1199trackers = [k for k in raw if k in ("github", "ado")] if isinstance(raw, dict) else []lines 1200–1200◇ if not isinstance(raw, dict) or set(raw) - {"github", "ado", "fetch"} or len(trackers) > 1lines 1201–1204problems.append( "`wiki.issues` must be {github: owner/repo} or {ado: org/project}, optionally with " "`fetch: true`, or false" )lines 1205–1205return Nonelines 1206–1206◇ if not trackerslines 1207–1207return Nonelines 1208–1208provider, project = trackers[0], raw[trackers[0]]lines 1209–1209◇ if not isinstance(project, str) or project.count("/") != 1lines 1210–1210problems.append(f"`wiki.issues.{provider}` must name `<owner-or-org>/<repo-or-project>`")lines 1211–1211return Nonelines 1212–1212return str(provider), project

Flows

_one_of

_one_of(raw: dict, key: str, allowed: tuple[str, ...], problems: list[str])

clew/wiki/config.py:1281

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
lines 1283–1283value = raw.get(key)lines 1284–1284◇ if value is Nonelines 1285–1285return allowed[0]lines 1286–1286◇ if value not in allowedlines 1287–1287problems.append(f"`wiki.{key}` must be one of {', '.join(allowed)}, got {value!r}")lines 1288–1288return allowed[0]lines 1289–1289return str(value)

Flows

_overlaid

_overlaid(raw: dict[str, Any], problems: list[str])

clew/wiki/config.py:580

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), problems
Activity · 17 steps
lines 587–587import yamllines 589–589path = _OVERLAY.get()lines 590–590◇ if path is Nonelines 591–591return raw, problemslines 592–592trylines 593–593data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}lines 594–594except (OSError, yaml.YAMLError) as exclines 595–595return raw, [*problems, f"--wiki-config {path} could not be read: {exc}"]lines 596–596◇ if not isinstance(data, dict)lines 597–597return raw, [*problems, f"--wiki-config {path} must be a mapping with a `wiki:` section"]lines 598–598extra = sorted(set(data) - {"wiki"})lines 599–599◇ if extralines 600–600problems = [*problems, f"--wiki-config {path} layers `wiki:` only; it also names {extra}"]lines 601–601section = data.get("wiki") or {}lines 602–602◇ if not isinstance(section, dict)lines 603–603return raw, [*problems, f"--wiki-config {path}: `wiki:` must be a mapping"]lines 604–604return _merge(raw, section), problems

Flows

_pinned_catalogs

_pinned_catalogs(requirements: dict[str, Any])

clew/wiki/config.py:764

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
lines 772–781return 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) )

Flows

_positive

_positive(raw: dict, key: str, default: int, problems: list[str])

clew/wiki/config.py:1260

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 value
Activity · 5 steps
lines 1262–1262value = raw.get(key, default)lines 1263–1263◇ if isinstance(value, bool) or not isinstance(value, int) or value < 1lines 1264–1264problems.append(f"`wiki.{key}` must be a whole number of 1 or more, got {value!r}")lines 1265–1265return defaultlines 1266–1266return value

Flows

_read_section

_read_section(path: Path)

clew/wiki/config.py:533

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
lines 535–535import yamllines 537–537raw: Any = {}lines 538–538◇ if path.is_file()lines 539–539trylines 540–540raw = (yaml.safe_load(path.read_text(encoding="utf-8")) or {}).get("wiki") or {}lines 541–541except (yaml.YAMLError, AttributeError) as exclines 542–542return {}, [f"{path.name} could not be read as YAML: {exc}"]lines 543–543◇ if not isinstance(raw, dict)lines 544–544return {}, ["`wiki:` must be a mapping"]lines 545–545return raw, []

Flows

_renamed

_renamed(mapping: Any, where: str)

clew/wiki/config.py:825

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
lines 827–827◇ if not isinstance(mapping, dict)lines 828–828return []lines 829–835return [ 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 ]

Flows

_requirements_section

_requirements_section(path: Path, problems: list[str])

clew/wiki/config.py:696

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
lines 702–702from ..guard.config import read_requirements_sectionlines 703–703from ..guard.errors import ConfigErrorlines 705–705◇ if not path.is_file()lines 706–706return {}lines 707–707trylines 708–708return read_requirements_section(path) or {}lines 709–709except ConfigError as exclines 710–710problems.extend(f"`requirements`: {p}" for p in (exc.problems or [exc.message]))lines 711–711return {}

Flows

_sbom

_sbom(raw: Any, problems: list[str])

clew/wiki/config.py:1298

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 out
Activity · 14 steps
lines 1305–1305◇ if raw is Nonelines 1306–1306return {}lines 1307–1307out: dict[str, tuple[str, ...]] = {}lines 1308–1308keys = {"files": "sbom_files", "accepted": "sbom_accepted"}lines 1309–1309◇ if not isinstance(raw, dict) or set(raw) - set(keys)lines 1310–1310problems.append("`wiki.sbom` must be {files: [globs], accepted: [licence ids]}")lines 1311–1311return {}lines 1312–1312◇ for key, attr in keys.items()lines 1313–1313◇ if key in rawlines 1314–1314◇ if isinstance(raw[key], list) and all(isinstance(v, str) for v in raw[key])lines 1315–1315out[attr] = tuple(raw[key])lines 1316–1316elselines 1317–1317problems.append(f"`wiki.sbom.{key}` must be a list of strings")lines 1318–1318return out

Flows

_strings

_strings(
    mapping: dict[str, Any], key: str, default: tuple[str, ...], where: str, problems: list[str]
)

clew/wiki/config.py:847

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
lines 858–858◇ if key not in mappinglines 859–859return tuple(default)lines 860–860value = mapping[key]lines 861–861◇ if value is Nonelines 862–862return ()lines 863–863◇ if isinstance(value, str)lines 864–864return (value,)lines 865–865◇ if isinstance(value, list) and all(isinstance(v, (str, int, float)) for v in value)lines 866–866return tuple(str(v) for v in value)lines 867–867problems.append(f"`{where}.{key}` must be a list of strings (or one string)")lines 868–868return tuple(default)

Flows

_theme

_theme(raw: Any, problems: list[str])

clew/wiki/config.py:1144

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
lines 1150–1150problems += _unknown(raw, _THEME, "wiki.theme")lines 1151–1151◇ if not isinstance(raw, dict)lines 1152–1152return ThemeSpec()lines 1153–1153palette = raw.get("palette") or {}lines 1154–1154◇ if not isinstance(palette, dict)lines 1155–1155problems.append("`wiki.theme.palette` must map a token to a colour")lines 1156–1156palette = {}lines 1157–1163problems += [ 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 ]lines 1164–1168problems += [ 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 ";{}<>") ]lines 1169–1169css = raw.get("css") or ()lines 1170–1180return 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)), )

Flows

_top_level

_top_level(path: Path, key: str)

clew/wiki/config.py:720

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
lines 722–722import yamllines 724–724◇ if not path.is_file()lines 725–725return {}lines 726–726trylines 727–727doc = yaml.safe_load(path.read_text(encoding="utf-8")) or {}lines 728–728except yaml.YAMLErrorlines 729–729return {}lines 730–730value = doc.get(key) if isinstance(doc, dict) else Nonelines 731–731return value if isinstance(value, dict) else {}

Flows

_tuning

_tuning(raw: dict[str, Any], tests: dict[str, Any], problems: list[str])

clew/wiki/config.py:992

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 out
Activity · 8 steps
lines 999–999out = {k: _count(raw, k, d, "wiki", problems) for k, d in TUNING_DEFAULTS.items()}lines 1000–1000web = raw.get("web") or {}lines 1001–1001problems += _unknown(web, _WEB, "wiki.web")lines 1002–1004out["web_max_ring"] = _count( web if isinstance(web, dict) else {}, "max_ring", 8, "wiki.web", problems )lines 1005–1005out["max_report_mb"] = _count(tests, "max_report_mb", DEFAULT_MAX_REPORT_MB, "tests", problems)lines 1006–1006python = raw.get("trace_python")lines 1007–1007out["trace_python"] = str(python) if python else Nonelines 1008–1008return out

Flows

_unknown

_unknown(mapping: Any, allowed: set[str], where: str)

clew/wiki/config.py:807

Show on the map →

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
lines 809–809◇ if not isinstance(mapping, dict)lines 810–810return [f"`{where}` must be a mapping"]lines 811–815return [ f"`{where}.{key}` is not a known key (allowed: {', '.join(sorted(allowed))})" for key in mapping if key not in allowed ]

Flows

load_wiki_config

load_wiki_config(
    repo_root: Path, config_path: Path | None = None
)

clew/wiki/config.py:407

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
Activity · 13 steps
lines 417–417raw, problems = _read_section(Path(config_path or Path(repo_root) / ".clew.yaml"))lines 419–419raw, problems = _overlaid(raw, problems)lines 420–420◇ if problemslines 421–421return WikiConfig(), problemslines 422–424problems = _renamed(raw, "wiki") + _unknown( {k: v for k, v in raw.items() if k not in _RENAMED and k not in _MOVED}, _TOP, "wiki" )lines 425–427requirements = _requirements_section( Path(config_path or Path(repo_root) / ".clew.yaml"), problems )lines 428–428flows = tuple(_flow(f, i, problems) for i, f in enumerate(raw.get("flows") or []))lines 429–429tests = _top_level(Path(config_path or Path(repo_root) / ".clew.yaml"), "tests")lines 430–430problems += _unknown(tests, set(TESTS_KEYS), "tests")lines 431–431links = raw.get("links") or {}lines 432–432problems += _unknown(links, _LINKS, "wiki.links")lines 433–469config = 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), )lines 470–470return config, problems

Flows