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.
Source · 4 lines
def _config_path(parent: str, key: str) -> str:
return f"{parent}.{key}" if parent else key
Activity · 1 steps
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.
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
Flows
_fresh_defaults
dict[str, Any] clew.guard.config._fresh_defaults()
Deep-copy the built-in defaults so callers cannot mutate module state.
Source · 4 lines
def _fresh_defaults() -> dict[str, Any]:
return copy.deepcopy(CONFIG_DEFAULTS)
Activity · 1 steps
Requirements
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.
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
Requirements
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.
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
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].
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
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 .
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
Flows
_suggest_key
str clew.guard.config._suggest_key(str key, dict schema)
Suggest the closest known schema key for a misspelled one.
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
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.
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
Requirements
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.
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
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.
Called by _checked_requirements, _validate_dict_node, _validate_map_of, read_requirements_section, validate_config_schema
Tested by
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
Requirements
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.
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
Requirements
Flows
compare_versions
int clew.guard.config.compare_versions(tuple[int,...] a, tuple[int,...] b)
Compare two version tuples, padding shorter one with zeros.
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
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.
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 more
test_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 tests
test_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 more
test_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
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.
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
Requirements
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.
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
Requirements
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: ).
Called by _coverage_gate, _declared_catalog_field, _effective_requirements, _exempt, _get_requirements_config, _has_version_gate, _validate_files, check_req_coverage, covered_via, exempt_by_status, filter_requirements_by_version, load_external_requirements
Tested by
Calls none
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
Flows
get_validate
dict[str, Any] clew.guard.config.get_validate(dict[str, Any] config)
Access the validate section of config.
Called by _bus_tags, _detect_current_version, _has_version_gate, _validate_requirements, build_effective_contract, build_files_contract, check_bus_tags, check_duplicate_tags, check_exemption_reasons, check_file_presence, check_presence, check_req_exists
Calls none
Source · 4 lines
def get_validate(config: dict[str, Any]) -> dict[str, Any]:
return config.get("validate", {})
Activity · 1 steps
Flows
impact_base
str clew.guard.config.impact_base(dict[str, Any]|None config)
The ref the impact report diffs against ( guard.impact.base ).
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
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.
Called by _config, _excluded, _run, _unknown_tags, init_system, read_guard_config
Tested by 43 tests
test_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 more
test_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
Requirements
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.
Called by parse_source_file_with_content, validate_file
Tested by
Calls get_language_config, language_for_file, parse_functions, resolve_parse_settings
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
Requirements
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.
Called by _extract_changed_functions, _file_tests, validate_file
Tested by
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
Requirements
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.
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
Requirements
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.
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
Requirements
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 .
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
Requirements
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 .
Called by _requirements_section, load_config, read_guard_config
Calls _validate_node
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
Requirements
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.
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
Requirements
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.
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
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.
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
Requirements
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.
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
Requirements
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.
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
Requirements
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.
Called by load_config
Tested by 23 tests
test_a_well_formed_tag_and_language_pass, test_an_unknown_setting_is_refused, test_an_x_key_is_an_unknown_key, test_empty_config_passes, test_every_default_key_is_permitted_by_the_schema, test_multiple_errors, test_no_suggestion_when_nothing_is_close, test_non_dict_where_dict_expected, test_null_section_is_accepted_by_the_schema, test_open_dict_allows_custom_languages, test_open_dict_allows_custom_tags, test_removed_trace_section_rejected 11 more
test_stale_test_mapping_rejected, test_suggests_close_nested_key, test_suggests_close_top_level_key, test_tag_and_language_entries_are_checked, test_the_bus_section_is_part_of_the_validated_schema, test_unknown_nested_key, test_unknown_top_level_key, test_valid_output_dir, test_version_gate_accepted, test_wrong_type_bool, test_wrong_type_string
Calls _exclude_errors, _moved_keys, _ratio_errors, _reason_errors, _validate_node
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
Requirements
Flows
validate_output_path
Path clew.guard.config.validate_output_path(str path)
Reject output paths containing directory traversal or absolute components.
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