config.py

clew/guard/config.py

Configuration loading, defaults, and merging for the gate.

_config_path

str clew.guard.config._config_path(str parent, str key)

Build a dotted config path from parent path and key.

clew/guard/config.py:407

Source · 4 lines
def _config_path(parent: str, key: str) -> str:
    return f"{parent}.{key}" if parent else key

Activity · 1 steps
lines 408–408return f"{parent}.{key}" if parent else key

Flows

_exclude_errors

list[str] clew.guard.config._exclude_errors(dict[str, Any] user_config)

Refuse a 1.x regex-shaped validate.exclude entry, naming the two 2.0.0 forms.

clew/guard/config.py:479

Source · 16 lines
def _exclude_errors(user_config: dict[str, Any]) -> list[str]:
    validate = user_config.get("validate") if isinstance(user_config, dict) else None
    excludes = validate.get("exclude") if isinstance(validate, dict) else None
    if not isinstance(excludes, list):
        return []  # a wrong type is the schema's to report
    return [
        f"guard.validate.exclude entry {e!r} reads as a regex; since 2.0.0 entries are globs "
        f"(e.g. `tests/**`), and a regex is written with the `{EXCLUDE_REGEX_PREFIX}` prefix "
        f"(e.g. `{EXCLUDE_REGEX_PREFIX}{e}`)"
        for e in excludes
        if isinstance(e, str)
        and not e.startswith(EXCLUDE_REGEX_PREFIX)
        and (e.startswith("^") or e.endswith("$") or "\\" in e)
    ]

Activity · 5 steps
lines 480–480validate = user_config.get("validate") if isinstance(user_config, dict) else Nonelines 481–481excludes = validate.get("exclude") if isinstance(validate, dict) else Nonelines 482–482◇ if not isinstance(excludes, list)lines 483–483return []lines 484–492return [ f"guard.validate.exclude entry {e!r} reads as a regex; since 2.0.0 entries are globs " f"(e.g. `tests/**`), and a regex is written with the `{EXCLUDE_REGEX_PREFIX}` prefix " f"(e.g. `{EXCLUDE_REGEX_PREFIX}{e}`)" for e in excludes if isinstance(e, str) and not e.startswith(EXCLUDE_REGEX_PREFIX) and (e.startswith("^") or e.endswith("$") or "\\" in e) ]

Flows

_fresh_defaults

dict[str, Any] clew.guard.config._fresh_defaults()

Deep-copy the built-in defaults so callers cannot mutate module state.

clew/guard/config.py:642

Show on the map →

Called by load_config

Calls none

Source · 4 lines
def _fresh_defaults() -> dict[str, Any]:
    return copy.deepcopy(CONFIG_DEFAULTS)

Activity · 1 steps
lines 643–643return copy.deepcopy(CONFIG_DEFAULTS)

Requirements

REQ-DDB-GUARD-012

Flows

_log_declared_sections

None clew.guard.config._log_declared_sections(dict[str, Any] user_config)

Log which top-level sections the user declared versus which are defaulted.

clew/guard/config.py:802

Show on the map →

Called by load_config

Calls none

Source · 7 lines
def _log_declared_sections(user_config: dict[str, Any]) -> None:
    declared = sorted(str(k) for k in user_config)
    defaulted = sorted(k for k in CONFIG_SCHEMA if k not in user_config)
    logger.info("Config sections declared: %s", ", ".join(declared) or "none")
    logger.info("Config sections using defaults: %s", ", ".join(defaulted) or "none")

Activity · 4 steps
lines 803–803declared = sorted(str(k) for k in user_config)lines 804–804defaulted = sorted(k for k in CONFIG_SCHEMA if k not in user_config)lines 805–805logger.info("Config sections declared: %s", ", ".join(declared) or "none")lines 806–806logger.info("Config sections using defaults: %s", ", ".join(defaulted) or "none")

Requirements

REQ-DDB-GUARD-012

Flows

_moved_keys

tuple[list[str], dict[str, Any]] clew.guard.config._moved_keys(dict[str, Any] user_config)

Split out the keys that moved in 2.0.0, each with a pointer to its new home.

clew/guard/config.py:552

Source · 17 lines
def _moved_keys(user_config: dict[str, Any]) -> tuple[list[str], dict[str, Any]]:
    errors: list[str] = []
    rest = copy.deepcopy(user_config) if isinstance(user_config, dict) else user_config
    for dotted, where in MOVED_KEYS.items():
        *parents, leaf = dotted.split(".")
        node = rest
        for part in parents:
            node = node.get(part) if isinstance(node, dict) else None
        if isinstance(node, dict) and leaf in node:
            errors.append(f"guard.{dotted} moved in 2.0.0 to {where}")
            del node[leaf]
    gate = (rest.get("validate") or {}) if isinstance(rest, dict) else {}
    if isinstance(gate, dict) and gate.get("version_gate") == {}:
        del gate["version_gate"]
    return errors, rest

Activity · 14 steps
lines 553–553errors: list[str] = []lines 554–554rest = copy.deepcopy(user_config) if isinstance(user_config, dict) else user_configlines 555–555◇ for dotted, where in MOVED_KEYS.items()lines 556–556*parents, leaf = dotted.split(".")lines 557–557node = restlines 558–558◇ for part in parentslines 559–559node = node.get(part) if isinstance(node, dict) else Nonelines 560–560◇ if isinstance(node, dict) and leaf in nodelines 561–561errors.append(f"guard.{dotted} moved in 2.0.0 to {where}")lines 562–562del node[leaf]lines 563–563gate = (rest.get("validate") or {}) if isinstance(rest, dict) else {}lines 564–564◇ if isinstance(gate, dict) and gate.get("version_gate") == {}lines 565–565del gate["version_gate"]lines 566–566return errors, rest

Flows

_ratio_errors

list[str] clew.guard.config._ratio_errors(dict[str, Any] user_config)

Refuse a coverage.min_req_ratio that is not a number in (0, 1].

clew/guard/config.py:514

Source · 14 lines
def _ratio_errors(user_config: dict[str, Any]) -> list[str]:
    coverage = user_config.get("coverage") if isinstance(user_config, dict) else None
    if not isinstance(coverage, dict) or coverage.get("min_req_ratio") is None:
        return []
    value = coverage["min_req_ratio"]
    number = isinstance(value, int | float) and not isinstance(value, bool)
    if number and 0 < value <= 1:
        return []
    return [
        f"guard.coverage.min_req_ratio must be a number in (0, 1], the share of non-test "
        f"functions carrying @req among those carrying @req or an exemption; got {value!r}"
    ]

Activity · 8 steps
lines 515–515coverage = user_config.get("coverage") if isinstance(user_config, dict) else Nonelines 516–516◇ if not isinstance(coverage, dict) or coverage.get("min_req_ratio") is Nonelines 517–517return []lines 518–518value = coverage["min_req_ratio"]lines 519–519number = isinstance(value, int | float) and not isinstance(value, bool)lines 520–520◇ if number and 0 < value <= 1lines 521–521return []lines 522–525return [ f"guard.coverage.min_req_ratio must be a number in (0, 1], the share of non-test " f"functions carrying @req among those carrying @req or an exemption; got {value!r}" ]

Flows

_reason_errors

list[str] clew.guard.config._reason_errors(dict[str, Any] user_config)

Refuse an exemption_reason setting other than required or optional .

clew/guard/config.py:499

Source · 11 lines
def _reason_errors(user_config: dict[str, Any]) -> list[str]:
    validate = user_config.get("validate") if isinstance(user_config, dict) else None
    value = validate.get("exemption_reason") if isinstance(validate, dict) else None
    if value is None or value in EXEMPTION_REASON_SETTINGS:
        return []
    return [
        f"guard.validate.exemption_reason must be one of {', '.join(EXEMPTION_REASON_SETTINGS)}, "
        f"got {value!r}"
    ]

Activity · 5 steps
lines 500–500validate = user_config.get("validate") if isinstance(user_config, dict) else Nonelines 501–501value = validate.get("exemption_reason") if isinstance(validate, dict) else Nonelines 502–502◇ if value is None or value in EXEMPTION_REASON_SETTINGSlines 503–503return []lines 504–507return [ f"guard.validate.exemption_reason must be one of {', '.join(EXEMPTION_REASON_SETTINGS)}, " f"got {value!r}" ]

Flows

_shared_facts

dict[str, Any] clew.guard.config._shared_facts(Path config_path)

The facts the gate reads from the rest of .clew.yaml : the event vocabulary and sources.

clew/guard/config.py:736

Source · 23 lines
def _shared_facts(config_path: Path) -> dict[str, Any]:
    try:
        with open(config_path) as f:
            document = yaml.safe_load(f) or {}
    except (OSError, yaml.YAMLError):
        return {}
    if not isinstance(document, dict):
        return {}
    tags = document.get("event_tags")
    wiki = document.get("wiki") if isinstance(document.get("wiki"), dict) else {}
    owners = document.get("owners")
    tests = document.get("tests") if isinstance(document.get("tests"), dict) else {}
    return {
        ## 2.0.0 (PG3): the declared test paths, so the ratio floor leaves out the code the index
        ## calls test code; None means the index's built-in guesses apply.
        "test_paths": list(tests["paths"]) if isinstance(tests.get("paths"), list) else None,
        "event_tags": dict(tags) if isinstance(tags, dict) else None,
        "wiki_sources": bool(wiki.get("sources")),
        ## 2.0.0: the impact report's reviewers read the same `owners:` section the index does.
        "owners": dict(owners) if isinstance(owners, dict) else None,
    }

Activity · 12 steps
lines 737–737trylines 738–738with open(config_path) as flines 739–739document = yaml.safe_load(f) or {}lines 740–740except (OSError, yaml.YAMLError)lines 741–741return {}lines 742–742◇ if not isinstance(document, dict)lines 743–743return {}lines 744–744tags = document.get("event_tags")lines 745–745wiki = document.get("wiki") if isinstance(document.get("wiki"), dict) else {}lines 746–746owners = document.get("owners")lines 747–747tests = document.get("tests") if isinstance(document.get("tests"), dict) else {}lines 748–756return { ## 2.0.0 (PG3): the declared test paths, so the ratio floor leaves out the code the index ## calls test code; None means the index's built-in guesses apply. "test_paths": list(tests["paths"]) if isinstance(tests.get("paths"), list) else None, "event_tags": dict(tags) if isinstance(tags, dict) else None, "wiki_sources": bool(wiki.get("sources")), ## 2.0.0: the impact report's reviewers read the same `owners:` section the index does. "owners": dict(owners) if isinstance(owners, dict) else None, }

Flows

_suggest_key

str clew.guard.config._suggest_key(str key, dict schema)

Suggest the closest known schema key for a misspelled one.

clew/guard/config.py:430

Source · 5 lines
def _suggest_key(key: str, schema: dict) -> str:
    matches = difflib.get_close_matches(key, list(schema.keys()), n=1, cutoff=0.6)
    return f" — did you mean '{matches[0]}'?" if matches else ""

Activity · 2 steps
lines 431–431matches = difflib.get_close_matches(key, list(schema.keys()), n=1, cutoff=0.6)lines 432–432return f" — did you mean '{matches[0]}'?" if matches else ""

Flows

_validate_dict_node

list[str] clew.guard.config._validate_dict_node(dict user, dict schema, str path)

Validate dict keys against schema, recursing into sub-nodes.

clew/guard/config.py:415

Source · 11 lines
def _validate_dict_node(user: dict, schema: dict, path: str) -> list[str]:
    errors: list[str] = []
    for key in user:
        child_path = _config_path(path, key)
        if key not in schema:
            errors.append(f"Unknown config key: {child_path}{_suggest_key(key, schema)}")
        else:
            errors.extend(_validate_node(user[key], schema[key], child_path))
    return errors

Activity · 8 steps
lines 416–416errors: list[str] = []lines 417–417◇ for key in userlines 418–418child_path = _config_path(path, key)lines 419–419◇ if key not in schemalines 420–420errors.append(f"Unknown config key: {child_path}{_suggest_key(key, schema)}")lines 421–421elselines 422–422errors.extend(_validate_node(user[key], schema[key], child_path))lines 423–423return errors

Requirements

REQ-DDB-GUARD-012

Flows

_validate_map_of

list[str] clew.guard.config._validate_map_of(Any user, _MapOf schema, str path)

Validate a mapping of user-named entries against the schema every entry follows.

clew/guard/config.py:466

Source · 9 lines
def _validate_map_of(user: Any, schema: _MapOf, path: str) -> list[str]:
    if not isinstance(user, dict):
        return [f"{path}: expected dict, got {type(user).__name__}"]
    errors: list[str] = []
    for name, entry in user.items():
        errors.extend(_validate_node(entry, schema.schema, _config_path(path, str(name))))
    return errors

Activity · 6 steps
lines 467–467◇ if not isinstance(user, dict)lines 468–468return [f"{path}: expected dict, got {type(user).__name__}"]lines 469–469errors: list[str] = []lines 470–470◇ for name, entry in user.items()lines 471–471errors.extend(_validate_node(entry, schema.schema, _config_path(path, str(name))))lines 472–472return errors

Flows

_validate_node

list[str] clew.guard.config._validate_node(Any user, Any schema, str path)

Validate a single config node against its schema spec.

clew/guard/config.py:443

Source · 19 lines
def _validate_node(user: Any, schema: Any, path: str) -> list[str]:
    if isinstance(schema, _MapOf) and user is not None:
        return _validate_map_of(user, schema, path)
    unconstrained = schema is _OPEN_DICT or not isinstance(schema, type | dict)
    if unconstrained or user is None:
        return []
    if isinstance(schema, type):
        return (
            []
            if isinstance(user, schema)
            else [f"{path}: expected {schema.__name__}, got {type(user).__name__}"]
        )
    return (
        [f"{path}: expected dict, got {type(user).__name__}"]
        if not isinstance(user, dict)
        else _validate_dict_node(user, schema, path)
    )

Activity · 8 steps
lines 444–444◇ if isinstance(schema, _MapOf) and user is not Nonelines 445–445return _validate_map_of(user, schema, path)lines 446–446unconstrained = schema is _OPEN_DICT or not isinstance(schema, type | dict)lines 447–447◇ if unconstrained or user is Nonelines 448–448return []lines 449–449◇ if isinstance(schema, type)lines 450–454return ( [] if isinstance(user, schema) else [f"{path}: expected {schema.__name__}, got {type(user).__name__}"] )lines 455–459return ( [f"{path}: expected dict, got {type(user).__name__}"] if not isinstance(user, dict) else _validate_dict_node(user, schema, path) )

Requirements

REQ-DDB-GUARD-012

Flows

apply_opt_in_languages

dict[str, Any] clew.guard.config.apply_opt_in_languages(dict[str, Any] merged, dict[str, Any] user_config)

Fill a declared opt-in language (e.g.

clew/guard/config.py:790

Show on the map →

Called by _config, _rust_config, load_config

Calls deep_merge

Source · 9 lines
def apply_opt_in_languages(merged: dict[str, Any], user_config: dict[str, Any]) -> dict[str, Any]:
    declared = (user_config.get("validate") or {}).get("languages") or {}
    languages = merged.setdefault("validate", {}).setdefault("languages", {})
    for name, defaults in OPT_IN_LANGUAGE_DEFAULTS.items():
        if name in declared:
            languages[name] = deep_merge(copy.deepcopy(defaults), declared[name] or {})
    return merged

Activity · 6 steps
lines 791–791declared = (user_config.get("validate") or {}).get("languages") or {}lines 792–792languages = merged.setdefault("validate", {}).setdefault("languages", {})lines 793–793◇ for name, defaults in OPT_IN_LANGUAGE_DEFAULTS.items()lines 794–794◇ if name in declaredlines 795–795languages[name] = deep_merge(copy.deepcopy(defaults), declared[name] or {})lines 796–796return merged

Requirements

REQ-DDB-GUARD-024

Flows

compare_versions

int clew.guard.config.compare_versions(tuple[int,...] a, tuple[int,...] b)

Compare two version tuples, padding shorter one with zeros.

clew/guard/config.py:621

Source · 11 lines
def compare_versions(a: tuple[int, ...], b: tuple[int, ...]) -> int:
    max_len = max(len(a), len(b))
    a_padded = a + (0,) * (max_len - len(a))
    b_padded = b + (0,) * (max_len - len(b))
    if a_padded < b_padded:
        return -1
    if a_padded > b_padded:
        return 1
    return 0

Activity · 8 steps
lines 622–622max_len = max(len(a), len(b))lines 623–623a_padded = a + (0,) * (max_len - len(a))lines 624–624b_padded = b + (0,) * (max_len - len(b))lines 625–625◇ if a_padded < b_paddedlines 626–626return -1lines 627–627◇ if a_padded > b_paddedlines 628–628return 1lines 629–629return 0

Flows

deep_merge

dict[str, Any] clew.guard.config.deep_merge(dict[str, Any] base, dict[str, Any] override)

Recursively merge two dicts; override values win for non-dict leaves.

clew/guard/config.py:649

Show on the map →

Called by _config, _config, _config, _make_impact_config, _make_tag_config, _rust_config, apply_opt_in_languages, config, load_config, test_does_not_mutate_base, test_empty_base, test_empty_override

5 moretest_flat_override, test_nested_merge, test_override_adds_new_keys, test_override_replaces_dict_with_non_dict, test_override_replaces_non_dict_with_dict

Tested by

37 teststest_analyze_coverage_structure, test_c_file_missing_tags_fails, test_c_file_with_complete_block_passes, test_c_file_without_file_block_fails, test_check_can_be_disabled, test_coverage_message_lists_the_real_exemption_tags, test_coverage_treats_a_declaration_and_its_definition_as_one, test_current_reqs_kept, test_custom_configured_tags_are_included, test_declared_without_file_raises, test_disabled_by_config, test_equal_version_kept
25 moretest_excluded_path_is_absent_and_gate_skips_it, test_excluded_paths_are_absent, test_exposes_exclude_patterns, test_exposes_req_pattern, test_extra_tags_accepted, test_extra_tags_are_included, test_future_reqs_filtered, test_id_failing_configured_pattern_raises, test_include_guards_skipped, test_load_json, test_load_yaml, test_mapping_form_loads, test_missing_file_raises, test_missing_name_field_raises, test_nested_lookalike_path_agrees, test_non_default_version_tag_is_included, test_out_of_tree_catalog_rejected, test_private_keys_are_stripped, test_python_file_with_complete_block_passes, test_reports_the_patterns_that_produced_the_set, test_retired_tags_can_be_readmitted_via_extra_tags, test_the_refusal_survives_known_tags_warn_off, test_traversal_catalog_rejected, test_unknown_format_raises, test_wrong_yaml_shape_raises

Calls none

Source · 10 lines
def deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
    result = base.copy()
    for key, value in override.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = deep_merge(result[key], value)
        else:
            result[key] = value
    return result

Activity · 7 steps
lines 650–650result = base.copy()lines 651–651◇ for key, value in override.items()lines 652–652◇ if key in result and isinstance(result[key], dict) and isinstance(value, dict)lines 653–653result[key] = deep_merge(result[key], value)lines 654–654elselines 655–655result[key] = valuelines 656–656return result

Flows

exemption

str | None clew.guard.config.exemption(dict[str, Any] row, dict[str, Any] requirements)

Why a catalogue row is exempt from coverage, or None: its status, or a named field.

clew/guard/config.py:851

Source · 11 lines
def exemption(row: dict[str, Any], requirements: dict[str, Any]) -> str | None:
    field = requirements.get("status_field", "status")
    rules = [(field, requirements.get("exempt_status") or [])]
    rules += list((requirements.get("exempt_when") or {}).items())
    for name, values in rules:
        value = row.get(name)
        if value is not None and str(value) in {str(v) for v in values}:
            return f"{name}: {value}"
    return None

Activity · 8 steps
lines 852–852field = requirements.get("status_field", "status")lines 853–853rules = [(field, requirements.get("exempt_status") or [])]lines 854–854rules += list((requirements.get("exempt_when") or {}).items())lines 855–855◇ for name, values in ruleslines 856–856value = row.get(name)lines 857–857◇ if value is not None and str(value) in {str(v) for v in values}lines 858–858return f"{name}: {value}"lines 859–859return None

Requirements

REQ-DDB-GUARD-022

Flows

get_language_config

dict[str, Any] | None clew.guard.config.get_language_config(dict[str, Any] config, str file_path)

Match a file path to its language config by extension.

clew/guard/config.py:900

Source · 10 lines
def get_language_config(config: dict[str, Any], file_path: str) -> dict[str, Any] | None:
    ext = Path(file_path).suffix
    languages = get_validate(config).get("languages", {})

    for _lang_name, lang_config in languages.items():
        if ext in lang_config.get("extensions", []):
            return lang_config
    return None

Activity · 6 steps
lines 901–901ext = Path(file_path).suffixlines 902–902languages = get_validate(config).get("languages", {})lines 904–904◇ for _lang_name, lang_config in languages.items()lines 905–905◇ if ext in lang_config.get("extensions", [])lines 906–906return lang_configlines 907–907return None

Requirements

REQ-DDB-GUARD-013

Flows

get_requirements

dict[str, Any] clew.guard.config.get_requirements(dict[str, Any]|None config)

Access the requirements catalog section (the top-level requirements: ).

clew/guard/config.py:840

Source · 4 lines
def get_requirements(config: dict[str, Any] | None) -> dict[str, Any]:
    return (config or {}).get(REQUIREMENTS_ROOT_KEY) or {}

Activity · 1 steps
lines 841–841return (config or {}).get(REQUIREMENTS_ROOT_KEY) or {}

Flows

get_validate

dict[str, Any] clew.guard.config.get_validate(dict[str, Any] config)

Access the validate section of config.

clew/guard/config.py:812

Source · 4 lines
def get_validate(config: dict[str, Any]) -> dict[str, Any]:
    return config.get("validate", {})

Activity · 1 steps
lines 813–813return config.get("validate", {})

Flows

impact_base

str clew.guard.config.impact_base(dict[str, Any]|None config)

The ref the impact report diffs against ( guard.impact.base ).

clew/guard/config.py:833

Source · 4 lines
def impact_base(config: dict[str, Any] | None) -> str:
    return str(((config or {}).get("impact") or {}).get("base") or DEFAULT_IMPACT_BASE)

Activity · 1 steps
lines 834–834return str(((config or {}).get("impact") or {}).get("base") or DEFAULT_IMPACT_BASE)

Flows

load_config

dict[str, Any] clew.guard.config.load_config(Path|None config_path=None)

Load the guard: section of .clew.yaml and merge with built-in defaults.

clew/guard/config.py:698

Show on the map →

Called by _config, _excluded, _run, _unknown_tags, init_system, read_guard_config

Tested by

43 teststest_a_1x_regex_exclude_is_refused_with_a_pointer, test_a_guard_section_that_is_not_a_mapping_is_refused_by_the_gate, test_a_legacy_config_with_no_guard_section_is_refused, test_a_migrated_repo_with_the_leftover_is_refused_too, test_a_path_alone_is_the_file, test_a_requirement_implemented_by_a_dependency_at_its_pin_is_covered_via_it, test_an_invalid_section_degrades_the_index_and_is_refused_by_the_gate, test_an_old_location_is_refused_with_a_pointer, test_an_unknown_requirements_key_is_refused, test_bus_tags_moved_to_the_declaration, test_config_error_is_caught_by_except_exception, test_covering_tests_are_read_from_the_test_tree
31 moretest_custom_tags, test_declared_keys_win, test_declaring_rust_fills_its_defaults, test_emitted_config_loads, test_empty_config_file_returns_defaults, test_every_documented_presence_key_loads, test_exclude_patterns, test_full_config, test_guard_knows_the_tag_and_refuses_an_undeclared_id, test_guard_refuses_a_marker_naming_an_undeclared_mode, test_impact_section_override, test_language_dicts_are_deep_copied, test_mutating_a_loaded_config_does_not_touch_the_defaults, test_nested_sections_are_independent_objects, test_no_config_file_returns_defaults, test_no_legacy_file_means_no_warning, test_non_mapping_config_returns_defaults, test_off_by_default_nothing_changes, test_partial_validate_override, test_reports_declared_requirements, test_schema_leaves_round_trip_through_load_config, test_the_current_version_is_read_from_its_new_key, test_the_fixture_config_loads_under_the_current_schema, test_the_gate_and_the_index_read_the_same_top_level_section, test_the_gate_diffs_against_a_declared_base, test_the_gate_reads_the_same_section, test_the_rest_of_clew_yaml_is_not_the_gates, test_two_loads_are_independent, test_undeclared_rust_is_absent, test_unknown_key_raises_config_error, test_unreadable_yaml_raises_config_error

Calls _fresh_defaults, _log_declared_sections, _shared_facts, apply_opt_in_languages, deep_merge, read_guard_section, read_requirements_section, refuse_doxygen_guard_leftovers, validate_config_schema

Source · 32 lines
def load_config(config_path: Path | None = None) -> dict[str, Any]:
    if config_path is None:
        config_path = Path(CONFIG_FILE_NAME)
    ## THE HARD CUT, on every path (2.0.0, PG4): before any default is applied.
    refuse_doxygen_guard_leftovers(config_path.parent)

    if not config_path.exists():
        logger.info("No config file found at %s, using defaults", config_path)
        return _fresh_defaults()

    logger.info("Loading config from %s", config_path)
    shared = {
        REQUIREMENTS_ROOT_KEY: read_requirements_section(config_path),
        **_shared_facts(config_path),
    }
    user_config = read_guard_section(config_path)
    if user_config is None:
        logger.info("No %r section in %s, using defaults", CONFIG_SECTION, config_path)
        return {**_fresh_defaults(), **shared}

    errors = validate_config_schema(user_config)
    if errors:
        for err in errors:
            logger.error("Config error in %s: %s", config_path, err)
        raise ConfigError(f"Invalid config in {config_path}", errors)

    _log_declared_sections(user_config)
    merged = apply_opt_in_languages(deep_merge(_fresh_defaults(), user_config), user_config)
    merged.update(shared)
    return merged

Activity · 21 steps
lines 699–699◇ if config_path is Nonelines 700–700config_path = Path(CONFIG_FILE_NAME)lines 702–702refuse_doxygen_guard_leftovers(config_path.parent)lines 704–704◇ if not config_path.exists()lines 705–705logger.info("No config file found at %s, using defaults", config_path)lines 706–706return _fresh_defaults()lines 708–708logger.info("Loading config from %s", config_path)lines 709–712shared = { REQUIREMENTS_ROOT_KEY: read_requirements_section(config_path), **_shared_facts(config_path), }lines 713–713user_config = read_guard_section(config_path)lines 714–714◇ if user_config is Nonelines 715–715logger.info("No %r section in %s, using defaults", CONFIG_SECTION, config_path)lines 716–716return {**_fresh_defaults(), **shared}lines 718–718errors = validate_config_schema(user_config)lines 719–719◇ if errorslines 720–720◇ for err in errorslines 721–721logger.error("Config error in %s: %s", config_path, err)lines 722–722raise ConfigError(f"Invalid config in {config_path}", errors)lines 724–724_log_declared_sections(user_config)lines 725–725merged = apply_opt_in_languages(deep_merge(_fresh_defaults(), user_config), user_config)lines 726–726merged.update(shared)lines 727–727return merged

Requirements

REQ-DDB-GUARD-012

Flows

parse_content_for_file

list | None clew.guard.config.parse_content_for_file(str file_path, str content, dict[str, Any] config)

Parse functions out of arbitrary content using a file path's language config.

clew/guard/config.py:977

Source · 29 lines
def parse_content_for_file(
    file_path: str,
    content: str,
    config: dict[str, Any],
) -> list | None:
    from .parser import parse_functions
    from .ts_languages import language_for_file

    lang_config = get_language_config(config, file_path)
    if lang_config is None:
        return None

    settings = resolve_parse_settings(config, lang_config)
    lang_name = language_for_file(file_path, config)
    if lang_name is None:
        logger.warning(
            "%s matched language config but no tree-sitter grammar is available; skipping",
            file_path,
        )
        return None

    return parse_functions(
        content=content,
        exclude_names=lang_config.get("exclude_names", []),
        settings=settings,
        lang_name=lang_name,
    )

Activity · 11 steps
lines 982–982from .parser import parse_functionslines 983–983from .ts_languages import language_for_filelines 985–985lang_config = get_language_config(config, file_path)lines 986–986◇ if lang_config is Nonelines 987–987return Nonelines 989–989settings = resolve_parse_settings(config, lang_config)lines 990–990lang_name = language_for_file(file_path, config)lines 991–991◇ if lang_name is Nonelines 992–995logger.warning( "%s matched language config but no tree-sitter grammar is available; skipping", file_path, )lines 996–996return Nonelines 998–1003return parse_functions( content=content, exclude_names=lang_config.get("exclude_names", []), settings=settings, lang_name=lang_name, )

Requirements

REQ-DDB-GUARD-018

Flows

parse_source_file

list | None clew.guard.config.parse_source_file(str file_path, dict[str, Any] config)

Parse all functions from a source file using language-aware settings.

clew/guard/config.py:945

Source · 10 lines
def parse_source_file(
    file_path: str,
    config: dict[str, Any],
) -> list | None:
    result = parse_source_file_with_content(file_path, config)
    if result is None:
        return None
    return result[0]

Activity · 4 steps
lines 949–949result = parse_source_file_with_content(file_path, config)lines 950–950◇ if result is Nonelines 951–951return Nonelines 952–952return result[0]

Requirements

REQ-DDB-GUARD-018

Flows

parse_source_file_with_content

tuple[list, str] | None clew.guard.config.parse_source_file_with_content(str file_path, dict[str, Any] config)

Parse functions and return both the function list and file content.

clew/guard/config.py:959

Source · 11 lines
def parse_source_file_with_content(
    file_path: str,
    config: dict[str, Any],
) -> tuple[list, str] | None:
    content = Path(file_path).read_text(errors="replace")
    functions = parse_content_for_file(file_path, content, config)
    if functions is None:
        return None
    return functions, content

Activity · 5 steps
lines 963–963content = Path(file_path).read_text(errors="replace")lines 964–964functions = parse_content_for_file(file_path, content, config)lines 965–965◇ if functions is Nonelines 966–966return Nonelines 967–967return functions, content

Requirements

REQ-DDB-GUARD-018

Flows

parse_version

tuple[int, ...] clew.guard.config.parse_version(str version_str)

Parse a version string like "v1.8.2" into a comparable tuple.

clew/guard/config.py:600

Source · 18 lines
def parse_version(version_str: str) -> tuple[int, ...]:
    cleaned = version_str.strip().lstrip("vV")
    # Strip pre-release and build metadata (e.g., -rc1, +build123)
    cleaned = cleaned.split("-")[0].split("+")[0]
    try:
        return tuple(int(p) for p in cleaned.split("."))
    except ValueError as e:
        # Returning (0,) here used to make every requirement sort as "not yet
        # active", which silently disabled the whole @req coverage gate while the
        # run still reported success. A gate that cannot evaluate must not pass.
        logger.error("Could not parse version %r", version_str)
        raise ConfigError(
            f"Could not parse version {version_str!r}. If this came from "
            f"validate.current_version, either set a literal version or "
            f"ensure the auto: detector can resolve one."
        ) from e

Activity · 7 steps
lines 601–601cleaned = version_str.strip().lstrip("vV")lines 603–603cleaned = cleaned.split("-")[0].split("+")[0]lines 604–604trylines 605–605return tuple(int(p) for p in cleaned.split("."))lines 606–606except ValueError as elines 610–610logger.error("Could not parse version %r", version_str)lines 611–615raise ConfigError( f"Could not parse version {version_str!r}. If this came from " f"validate.current_version, either set a literal version or " f"ensure the auto: detector can resolve one." ) from e

Requirements

REQ-DDB-GUARD-014

Flows

read_guard_section

dict[str, Any] | None clew.guard.config.read_guard_section(Path config_path)

Read the raw guard: mapping out of a .clew.yaml .

clew/guard/config.py:767

Source · 18 lines
def read_guard_section(config_path: Path) -> dict[str, Any] | None:
    try:
        with open(config_path) as f:
            document = yaml.safe_load(f) or {}
    except (OSError, yaml.YAMLError) as e:
        logger.error("Could not read config file %s: %s", config_path, e)
        raise ConfigError(f"Could not read config file {config_path}: {e}") from e
    if not isinstance(document, dict):
        logger.warning("Config file %s is not a mapping, using defaults", config_path)
        return None
    section = document.get(CONFIG_SECTION)
    if section is None:
        return None
    if not isinstance(section, dict):
        raise ConfigError(f"{config_path}: `{CONFIG_SECTION}:` must be a mapping")
    return section

Activity · 15 steps
lines 768–768trylines 769–769with open(config_path) as flines 770–770document = yaml.safe_load(f) or {}lines 771–771except (OSError, yaml.YAMLError) as elines 772–772logger.error("Could not read config file %s: %s", config_path, e)lines 773–773raise ConfigError(f"Could not read config file {config_path}: {e}") from elines 774–774◇ if not isinstance(document, dict)lines 775–775logger.warning("Config file %s is not a mapping, using defaults", config_path)lines 776–776return Nonelines 777–777section = document.get(CONFIG_SECTION)lines 778–778◇ if section is Nonelines 779–779return Nonelines 780–780◇ if not isinstance(section, dict)lines 781–781raise ConfigError(f"{config_path}: `{CONFIG_SECTION}:` must be a mapping")lines 782–782return section

Requirements

REQ-DDB-GUARD-012

Flows

read_requirements_section

dict[str, Any] | None clew.guard.config.read_requirements_section(Path config_path)

Read and validate the top-level requirements: section of a .clew.yaml .

clew/guard/config.py:575

Source · 20 lines
def read_requirements_section(config_path: Path) -> dict[str, Any] | None:
    try:
        with open(config_path) as f:
            document = yaml.safe_load(f) or {}
    except (OSError, yaml.YAMLError) as e:
        raise ConfigError(f"Could not read config file {config_path}: {e}") from e
    raw = document.get(REQUIREMENTS_ROOT_KEY) if isinstance(document, dict) else None
    if raw is None:
        return None
    section = {"file": raw} if isinstance(raw, str) else raw
    errors = _validate_node(section, REQUIREMENTS_SCHEMA, REQUIREMENTS_ROOT_KEY)
    if not isinstance(section, dict):
        errors = [f"{REQUIREMENTS_ROOT_KEY}: expected a mapping or one path"]
    if errors:
        for err in errors:
            logger.error("Config error in %s: %s", config_path, err)
        raise ConfigError(f"Invalid config in {config_path}", errors)
    return dict(section)

Activity · 17 steps
lines 576–576trylines 577–577with open(config_path) as flines 578–578document = yaml.safe_load(f) or {}lines 579–579except (OSError, yaml.YAMLError) as elines 580–580raise ConfigError(f"Could not read config file {config_path}: {e}") from elines 581–581raw = document.get(REQUIREMENTS_ROOT_KEY) if isinstance(document, dict) else Nonelines 582–582◇ if raw is Nonelines 583–583return Nonelines 584–584section = {"file": raw} if isinstance(raw, str) else rawlines 585–585errors = _validate_node(section, REQUIREMENTS_SCHEMA, REQUIREMENTS_ROOT_KEY)lines 586–586◇ if not isinstance(section, dict)lines 587–587errors = [f"{REQUIREMENTS_ROOT_KEY}: expected a mapping or one path"]lines 588–588◇ if errorslines 589–589◇ for err in errorslines 590–590logger.error("Config error in %s: %s", config_path, err)lines 591–591raise ConfigError(f"Invalid config in {config_path}", errors)lines 592–592return dict(section)

Requirements

REQ-DDB-GUARD-012

Flows

refuse_doxygen_guard_leftovers

None clew.guard.config.refuse_doxygen_guard_leftovers(Path root)

Refuse to run while a doxygen-guard leftover is in the repository, naming it.

clew/guard/config.py:669

Show on the map →

Called by load_config

Calls none

Source · 19 lines
def refuse_doxygen_guard_leftovers(root: Path) -> None:
    problems = []
    if (root / LEGACY_CONFIG_NAME).is_file():
        problems.append(
            f"{root / LEGACY_CONFIG_NAME} is a doxygen-guard config: clew 2.0.0 does not read it. "
            'Move its contents under `guard:` in .clew.yaml (docs/GUARD.md, "Migrating from '
            'doxygen-guard") and delete it.'
        )
    hooks = root / ".pre-commit-config.yaml"
    text = hooks.read_text(encoding="utf-8", errors="replace") if hooks.is_file() else ""
    if _LEGACY_HOOK_ID.search(text):
        problems.append(
            f"{hooks} declares the `doxygen-guard` hook id: since 2.0.0 the hook is `clew-guard`, "
            "from the clew repository."
        )
    if problems:
        raise ConfigError("doxygen-guard leftovers (clew 2.0.0 is clew only)", problems)

Activity · 9 steps
lines 670–670problems = []lines 671–671◇ if (root / LEGACY_CONFIG_NAME).is_file()lines 672–676problems.append( f"{root / LEGACY_CONFIG_NAME} is a doxygen-guard config: clew 2.0.0 does not read it. " 'Move its contents under `guard:` in .clew.yaml (docs/GUARD.md, "Migrating from ' 'doxygen-guard") and delete it.' )lines 677–677hooks = root / ".pre-commit-config.yaml"lines 678–678text = hooks.read_text(encoding="utf-8", errors="replace") if hooks.is_file() else ""lines 679–679◇ if _LEGACY_HOOK_ID.search(text)lines 680–683problems.append( f"{hooks} declares the `doxygen-guard` hook id: since 2.0.0 the hook is `clew-guard`, " "from the clew repository." )lines 684–684◇ if problemslines 685–685raise ConfigError("doxygen-guard leftovers (clew 2.0.0 is clew only)", problems)

Requirements

REQ-DDB-GUARD-012

Flows

report_dir

str clew.guard.config.report_dir(dict[str, Any]|None config)

The directory the impact report is written to and read from.

clew/guard/config.py:826

Source · 4 lines
def report_dir(config: dict[str, Any] | None) -> str:
    return str(((config or {}).get("impact") or {}).get("report_dir") or DEFAULT_REPORT_DIR)

Activity · 1 steps
lines 827–827return str(((config or {}).get("impact") or {}).get("report_dir") or DEFAULT_REPORT_DIR)

Flows

resolve_contained_path

Path clew.guard.config.resolve_contained_path(str path, *str setting)

Resolve a config-supplied path and require it to stay inside the repo.

clew/guard/config.py:885

Source · 11 lines
def resolve_contained_path(path: str, *, setting: str) -> Path:
    root = Path.cwd().resolve()
    target = (root / path).resolve()
    if not target.is_relative_to(root):
        logger.error("%s resolves outside the repository: %s -> %s", setting, path, target)
        raise ConfigError(
            f"{setting} must stay inside the repository; {path!r} resolves to {target}"
        )
    return target

Activity · 6 steps
lines 886–886root = Path.cwd().resolve()lines 887–887target = (root / path).resolve()lines 888–888◇ if not target.is_relative_to(root)lines 889–889logger.error("%s resolves outside the repository: %s -> %s", setting, path, target)lines 890–892raise ConfigError( f"{setting} must stay inside the repository; {path!r} resolves to {target}" )lines 893–893return target

Requirements

REQ-DDB-GUARD-016

Flows

resolve_parse_settings

ParseSettings clew.guard.config.resolve_parse_settings(dict[str, Any] config, dict[str, Any] lang_config)

Resolve comment style and body style for a given language config.

clew/guard/config.py:1010

Source · 10 lines
def resolve_parse_settings(config: dict[str, Any], lang_config: dict[str, Any]) -> ParseSettings:
    from .parser import ParseSettings

    default_style = VALIDATE_DEFAULTS["comment_style"]
    global_style = get_validate(config).get("comment_style", {})
    lang_style = lang_config.get("comment_style", {})
    return ParseSettings(
        comment_start=lang_style.get("start", global_style.get("start", default_style["start"])),
        comment_end=lang_style.get("end", global_style.get("end", default_style["end"])),
    )

1 more lines, not shown

Activity · 5 steps
lines 1011–1011from .parser import ParseSettingslines 1013–1013default_style = VALIDATE_DEFAULTS["comment_style"]lines 1014–1014global_style = get_validate(config).get("comment_style", {})lines 1015–1015lang_style = lang_config.get("comment_style", {})lines 1016–1019return ParseSettings( comment_start=lang_style.get("start", global_style.get("start", default_style["start"])), comment_end=lang_style.get("end", global_style.get("end", default_style["end"])), )

Requirements

REQ-DDB-GUARD-013

Flows

unconfigured_language

str | None clew.guard.config.unconfigured_language(dict[str, Any] config, str file_path)

Name a language the gate ships but this config did not enable, for one file.

clew/guard/config.py:916

Source · 25 lines
def unconfigured_language(config: dict[str, Any], file_path: str) -> str | None:
    """WHY A SKIP IS SOMETIMES WORTH REPORTING AND USUALLY IS NOT (group A, 1.1.0 merge
    review). `rust`, `javascript` and `typescript` are opt-in: the published hook passes `.rs`
    files, and a repo that adopted the gate for its C must not start failing on its Rust the
    first time it bumps `rev:`. That decision is right and it was paid for in silence —
    `validate_file` logged "no matching language config" at DEBUG and returned clean, so a
    repository whose every `.rs` file was undocumented got `rc=0` and no output.

    A README or a lock file must stay silent, or the report is noise an owner scrolls past.
    The question that separates the two is not "is this source" — it is whether THE GATE SHIPS
    A LANGUAGE for this extension that this configuration did not enable. Nothing else can be
    something the gate failed to check.

    @brief The shipped-but-unconfigured language for a file, if any.
    @return The language name, or None.
    """
    ext = Path(file_path).suffix.lower()
    shipped = dict(VALIDATE_DEFAULTS["languages"])
    shipped.update(OPT_IN_LANGUAGE_DEFAULTS)
    for name, lang_config in shipped.items():
        if ext in {e.lower() for e in lang_config.get("extensions", [])}:
            return name
    return None

Activity · 7 steps
lines 932–932ext = Path(file_path).suffix.lower()lines 933–933shipped = dict(VALIDATE_DEFAULTS["languages"])lines 934–934shipped.update(OPT_IN_LANGUAGE_DEFAULTS)lines 935–935◇ for name, lang_config in shipped.items()lines 936–936◇ if ext in {e.lower() for e in lang_config.get("extensions", [])}lines 937–937return namelines 938–938return None

Requirements

REQ-DDB-GUARD-013

Flows

validate_config_schema

list[str] clew.guard.config.validate_config_schema(dict[str, Any] user_config)

Validate user config keys and types against CONFIG_SCHEMA.

clew/guard/config.py:537

Source · 11 lines
def validate_config_schema(user_config: dict[str, Any]) -> list[str]:
    moved, rest = _moved_keys(user_config)
    return (
        moved
        + _exclude_errors(rest)
        + _ratio_errors(rest)
        + _reason_errors(rest)
        + _validate_node(rest, CONFIG_SCHEMA, "")
    )

Activity · 2 steps
lines 538–538moved, rest = _moved_keys(user_config)lines 539–545return ( moved + _exclude_errors(rest) + _ratio_errors(rest) + _reason_errors(rest) + _validate_node(rest, CONFIG_SCHEMA, "") )

Requirements

REQ-DDB-GUARD-012

Flows

validate_output_path

Path clew.guard.config.validate_output_path(str path)

Reject output paths containing directory traversal or absolute components.

clew/guard/config.py:865

Source · 13 lines
def validate_output_path(path: str) -> Path:
    p = Path(path)
    if p.is_absolute():
        raise ConfigError(f"Output path '{path}' must be relative")
    if ".." in p.parts:
        raise ConfigError(f"Output path '{path}' contains directory traversal")
    if str(p).startswith("-"):
        # git add would parse a leading dash as an option.
        raise ConfigError(f"Output path '{path}' must not begin with '-'")
    resolve_contained_path(path, setting="output path")
    return p

Activity · 9 steps
lines 866–866p = Path(path)lines 867–867◇ if p.is_absolute()lines 868–868raise ConfigError(f"Output path '{path}' must be relative")lines 869–869◇ if ".." in p.partslines 870–870raise ConfigError(f"Output path '{path}' contains directory traversal")lines 871–871◇ if str(p).startswith("-")lines 873–873raise ConfigError(f"Output path '{path}' must not begin with '-'")lines 874–874resolve_contained_path(path, setting="output path")lines 875–875return p

Flows