main.py

clew/guard/main.py

CLI entry point for clew guard.

_add_config_parser

None clew.guard.main._add_config_parser(argparse._SubParsersAction subparsers)

Add the config subcommand exposing the machine-readable consumer contract.

clew/guard/main.py:153

Source · 15 lines
def _add_config_parser(subparsers: argparse._SubParsersAction) -> None:
    p = subparsers.add_parser("config", help="Emit the consumer contract as JSON")
    group = p.add_mutually_exclusive_group()
    group.add_argument(
        "--schema",
        action="store_true",
        help="Emit the config schema, defaults and catalog constants",
    )
    group.add_argument(
        "--effective",
        action="store_true",
        help="Emit the merged config actually in force and what it resolved to",
    )

Activity · 4 steps
lines 154–154p = subparsers.add_parser("config", help="Emit the consumer contract as JSON")lines 155–155group = p.add_mutually_exclusive_group()lines 156–160group.add_argument( "--schema", action="store_true", help="Emit the config schema, defaults and catalog constants", )lines 161–165group.add_argument( "--effective", action="store_true", help="Emit the merged config actually in force and what it resolved to", )

Flows

_add_coverage_parser

None clew.guard.main._add_coverage_parser(argparse._SubParsersAction subparsers)

Add the coverage subcommand to the parser.

clew/guard/main.py:142

Source · 8 lines
def _add_coverage_parser(subparsers: argparse._SubParsersAction) -> None:
    p = subparsers.add_parser("coverage", help="Report requirement coverage gaps")
    p.add_argument("source_dirs", nargs="*", default=["."], help="Source directories to scan")
    p.add_argument(
        "--format", dest="output_format", default="text", choices=["text", "json", "markdown"]
    )

Activity · 3 steps
lines 143–143p = subparsers.add_parser("coverage", help="Report requirement coverage gaps")lines 144–144p.add_argument("source_dirs", nargs="*", default=["."], help="Source directories to scan")lines 145–147p.add_argument( "--format", dest="output_format", default="text", choices=["text", "json", "markdown"] )

Flows

_add_doxyfile_parser

None clew.guard.main._add_doxyfile_parser(argparse._SubParsersAction subparsers)

Add the doxyfile subcommand emitting a Doxyfile fragment.

clew/guard/main.py:171

Source · 7 lines
def _add_doxyfile_parser(subparsers: argparse._SubParsersAction) -> None:
    subparsers.add_parser(
        "doxyfile",
        help="Emit Doxyfile settings that make this tool's tags valid doxygen",
    )

Activity · 1 steps
lines 172–175subparsers.add_parser( "doxyfile", help="Emit Doxyfile settings that make this tool's tags valid doxygen", )

Flows

_add_files_parser

None clew.guard.main._add_files_parser(argparse._SubParsersAction subparsers)

Add the files subcommand exposing the exact post-exclude file set.

clew/guard/main.py:181

Source · 5 lines
def _add_files_parser(subparsers: argparse._SubParsersAction) -> None:
    p = subparsers.add_parser("files", help="Emit the file set the gate walks, as JSON")
    p.add_argument("source_dirs", nargs="*", default=["."], help="Source directories to scan")

Activity · 2 steps
lines 182–182p = subparsers.add_parser("files", help="Emit the file set the gate walks, as JSON")lines 183–183p.add_argument("source_dirs", nargs="*", default=["."], help="Source directories to scan")

Flows

_add_impact_parser

None clew.guard.main._add_impact_parser(argparse._SubParsersAction subparsers)

Add the impact subcommand to the parser.

clew/guard/main.py:123

Source · 16 lines
def _add_impact_parser(subparsers: argparse._SubParsersAction) -> None:
    p = subparsers.add_parser("impact", help="Change-impact analysis from git diff")
    group = p.add_mutually_exclusive_group()
    group.add_argument("--staged", action="store_true", help="Analyze staged changes")
    group.add_argument("--range", dest="diff_range", help="Git revision range (e.g., HEAD~3..HEAD)")
    p.add_argument("files", nargs="*", help="Files to analyze")
    p.add_argument(
        "--write",
        action="store_true",
        help="Write impact.md and impact.json into guard.impact.report_dir instead of printing",
    )
    p.add_argument(
        "--format", dest="output_format", default="markdown", choices=["markdown", "json", "text"]
    )

Activity · 7 steps
lines 124–124p = subparsers.add_parser("impact", help="Change-impact analysis from git diff")lines 125–125group = p.add_mutually_exclusive_group()lines 126–126group.add_argument("--staged", action="store_true", help="Analyze staged changes")lines 127–127group.add_argument("--range", dest="diff_range", help="Git revision range (e.g., HEAD~3..HEAD)")lines 128–128p.add_argument("files", nargs="*", help="Files to analyze")lines 129–133p.add_argument( "--write", action="store_true", help="Write impact.md and impact.json into guard.impact.report_dir instead of printing", )lines 134–136p.add_argument( "--format", dest="output_format", default="markdown", choices=["markdown", "json", "text"] )

Flows

_add_validate_parser

None clew.guard.main._add_validate_parser(argparse._SubParsersAction subparsers)

Add the validate subcommand to the parser.

clew/guard/main.py:105

Source · 14 lines
def _add_validate_parser(subparsers: argparse._SubParsersAction) -> None:
    p = subparsers.add_parser("validate", help="Validate doxygen comments (pre-commit gate)")
    p.add_argument("files", nargs="*", help="Files to validate (passed by pre-commit)")
    p.add_argument("--no-git", action="store_true", help="Skip git-based staleness checks")
    p.add_argument("--exclude", action="append", default=[], help="Exclude patterns (repeatable)")
    p.add_argument(
        "--format",
        dest="output_format",
        default="text",
        choices=list(FORMATS),
        help="text (stderr, the default) or a machine format on stdout: sarif, gitlab, github",
    )

Activity · 5 steps
lines 106–106p = subparsers.add_parser("validate", help="Validate doxygen comments (pre-commit gate)")lines 107–107p.add_argument("files", nargs="*", help="Files to validate (passed by pre-commit)")lines 108–108p.add_argument("--no-git", action="store_true", help="Skip git-based staleness checks")lines 109–109p.add_argument("--exclude", action="append", default=[], help="Exclude patterns (repeatable)")lines 110–116p.add_argument( "--format", dest="output_format", default="text", choices=list(FORMATS), help="text (stderr, the default) or a machine format on stdout: sarif, gitlab, github", )

Flows

_check_retired_subcommand

int | None clew.guard.main._check_retired_subcommand(list[str] raw_argv)

Reject retired subcommands loudly instead of treating them as file paths.

clew/guard/main.py:556

Source · 10 lines
def _check_retired_subcommand(raw_argv: list[str]) -> int | None:
    first = _first_positional(raw_argv)
    reason = _RETIRED_SUBCOMMANDS.get(first) if first else None
    if reason is None:
        return None
    logger.error("Retired subcommand invoked: %s", first)
    print(f"clew guard: the '{first}' subcommand was removed — {reason}", file=sys.stderr)
    return 1

Activity · 7 steps
lines 557–557first = _first_positional(raw_argv)lines 558–558reason = _RETIRED_SUBCOMMANDS.get(first) if first else Nonelines 559–559◇ if reason is Nonelines 560–560return Nonelines 561–561logger.error("Retired subcommand invoked: %s", first)lines 562–562print(f"clew guard: the '{first}' subcommand was removed — {reason}", file=sys.stderr)lines 563–563return 1

Requirements

REQ-DDB-GUARD-013

Flows

_coverage_gate

int clew.guard.main._coverage_gate(dict[str, Any] config)

Run the coverage gate for the pre-commit hook.

clew/guard/main.py:508

Source · 15 lines
def _coverage_gate(config: dict[str, Any]) -> int:
    from .coverage import analyze_coverage, coverage_gaps, format_coverage_text, traceability_line

    floor = (config.get("coverage") or {}).get("min_req_ratio")
    if not get_requirements(config) and floor is None:
        return 0
    report = analyze_coverage(["."], config)
    failed = coverage_gaps(report)
    print(
        format_coverage_text(report) if failed else traceability_line(report["traceability"]),
        file=sys.stderr,
    )
    return 1 if failed else 0

Activity · 8 steps
lines 509–509from .coverage import analyze_coverage, coverage_gaps, format_coverage_text, traceability_linelines 511–511floor = (config.get("coverage") or {}).get("min_req_ratio")lines 512–512◇ if not get_requirements(config) and floor is Nonelines 513–513return 0lines 514–514report = analyze_coverage(["."], config)lines 515–515failed = coverage_gaps(report)lines 516–519print( format_coverage_text(report) if failed else traceability_line(report["traceability"]), file=sys.stderr, )lines 520–520return 1 if failed else 0

Requirements

REQ-DDB-GUARD-022

Flows

_detect_current_version

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

Resolve the current project version from config, git tag, or CMake.

clew/guard/main.py:424

Source · 9 lines
def _detect_current_version(config: dict[str, Any]) -> str | None:
    version_str = get_validate(config).get("current_version")
    if not version_str:
        return None
    detectors = {"auto:git": _detect_git_version, "auto:cmake": _detect_cmake_version}
    detector = detectors.get(version_str)
    return detector() if detector else version_str

Activity · 6 steps
lines 425–425version_str = get_validate(config).get("current_version")lines 426–426◇ if not version_strlines 427–427return Nonelines 428–428detectors = {"auto:git": _detect_git_version, "auto:cmake": _detect_cmake_version}lines 429–429detector = detectors.get(version_str)lines 430–430return detector() if detector else version_str

Flows

_dispatch_subcommand

int clew.guard.main._dispatch_subcommand(argparse.Namespace args, dict[str, Any] config)

Dispatch an explicit subcommand to its handler.

clew/guard/main.py:691

Source · 15 lines
def _dispatch_subcommand(args: argparse.Namespace, config: dict[str, Any]) -> int:
    handlers = {
        "validate": lambda: run_validate(args, config),
        "impact": lambda: _run_impact_command(args, config),
        "coverage": lambda: _run_coverage_command(args, config),
        "config": lambda: _run_config_command(args, config),
        "files": lambda: _run_files_command(args, config),
        "doxyfile": lambda: _run_doxyfile_command(args, config),
    }
    handler = handlers.get(args.command)
    if handler:
        return handler()
    return 1

Activity · 5 steps
lines 692–699handlers = { "validate": lambda: run_validate(args, config), "impact": lambda: _run_impact_command(args, config), "coverage": lambda: _run_coverage_command(args, config), "config": lambda: _run_config_command(args, config), "files": lambda: _run_files_command(args, config), "doxyfile": lambda: _run_doxyfile_command(args, config), }lines 700–700handler = handlers.get(args.command)lines 701–701◇ if handlerlines 702–702return handler()lines 703–703return 1

Flows

_first_positional

str | None clew.guard.main._first_positional(list[str] raw_argv)

Return the first positional arg, ignoring flags and their values.

clew/guard/main.py:537

Source · 15 lines
def _first_positional(raw_argv: list[str]) -> str | None:
    skip_next = False
    for arg in raw_argv:
        if skip_next:
            skip_next = False
            continue
        if arg in _FLAGS_WITH_VALUE:
            skip_next = True
            continue
        if arg.startswith("-"):
            continue
        return arg
    return None

Activity · 12 steps
lines 538–538skip_next = Falselines 539–539◇ for arg in raw_argvlines 540–540◇ if skip_nextlines 541–541skip_next = Falselines 542–542continuelines 543–543◇ if arg in _FLAGS_WITH_VALUElines 544–544skip_next = Truelines 545–545continuelines 546–546◇ if arg.startswith("-")lines 547–547continuelines 548–548return arglines 549–549return None

Flows

_has_subcommand

bool clew.guard.main._has_subcommand(list[str] raw_argv)

Detect whether the first positional arg is a known subcommand.

clew/guard/main.py:529

Source · 4 lines
def _has_subcommand(raw_argv: list[str]) -> bool:
    return _first_positional(raw_argv) in _SUBCOMMANDS

Activity · 1 steps
lines 530–530return _first_positional(raw_argv) in _SUBCOMMANDS

Flows

_parse_precommit_args

tuple[Path | None, list[str], bool] clew.guard.main._parse_precommit_args(list[str] raw_argv)

Parse pre-commit mode args (no subcommand) into components.

clew/guard/main.py:569

Show on the map →

Called by _run

Calls none

Source · 22 lines
def _parse_precommit_args(
    raw_argv: list[str],
) -> tuple[Path | None, list[str], bool]:
    config_path = None
    file_paths: list[str] = []
    verbose = False
    i = 0
    while i < len(raw_argv):
        if raw_argv[i] == "--config" and i + 1 < len(raw_argv):
            config_path = Path(raw_argv[i + 1])
            i += 2
        elif raw_argv[i] in ("-v", "--verbose"):
            verbose = True
            i += 1
        elif raw_argv[i].startswith("-"):
            i += 1
        else:
            file_paths.append(raw_argv[i])
            i += 1
    return config_path, file_paths, verbose

Activity · 17 steps
lines 572–572config_path = Nonelines 573–573file_paths: list[str] = []lines 574–574verbose = Falselines 575–575i = 0lines 576–576◇ while i < len(raw_argv)lines 577–577◇ if raw_argv[i] == "--config" and i + 1 < len(raw_argv)lines 578–578config_path = Path(raw_argv[i + 1])lines 579–579i += 2lines 580–580◇ elif raw_argv[i] in ("-v", "--verbose")lines 581–581verbose = Truelines 582–582i += 1lines 583–583◇ elif raw_argv[i].startswith("-")lines 584–584i += 1lines 585–585elselines 586–586file_paths.append(raw_argv[i])lines 587–587i += 1lines 588–588return config_path, file_paths, verbose

Flows

_report_skips

None clew.guard.main._report_skips(list[str] skipped)

Report, on the default surface, the files the gate did not check.

clew/guard/main.py:288

Source · 8 lines
def _report_skips(skipped: list[str]) -> None:
    if not skipped:
        return
    counts = Counter(skipped)
    detail = ", ".join(f"{count} {reason}" for reason, count in sorted(counts.items()))
    print(f"clew guard: {len(skipped)} file(s) not checked ({detail})", file=sys.stderr)

Activity · 5 steps
lines 289–289◇ if not skippedlines 290–290returnlines 291–291counts = Counter(skipped)lines 292–292detail = ", ".join(f"{count} {reason}" for reason, count in sorted(counts.items()))lines 293–293print(f"clew guard: {len(skipped)} file(s) not checked ({detail})", file=sys.stderr)

Flows

_report_violations

int clew.guard.main._report_violations(list[Violation] violations, str output_format="text")

Print violations and return exit code.

clew/guard/main.py:349

Source · 11 lines
def _report_violations(violations: list[Violation], output_format: str = "text") -> int:
    if output_format != "text":
        sys.stdout.write(render(violations, output_format))
    else:
        for v in violations:
            print(v, file=sys.stderr)
    if violations:
        print(f"\nclew guard: {len(violations)} violation(s) found", file=sys.stderr)
    return 1 if violations else 0

Activity · 8 steps
lines 350–350◇ if output_format != "text"lines 351–351sys.stdout.write(render(violations, output_format))lines 352–352elselines 353–353◇ for v in violationslines 354–354print(v, file=sys.stderr)lines 355–355◇ if violationslines 356–356print(f"\nclew guard: {len(violations)} violation(s) found", file=sys.stderr)lines 357–357return 1 if violations else 0

Flows

_run

int clew.guard.main._run(list[str] raw_argv)

Load config and dispatch, letting GuardError propagate to the CLI boundary.

clew/guard/main.py:728

Source · 15 lines
def _run(raw_argv: list[str]) -> int:
    if not _has_subcommand(raw_argv) and _HELP_FLAGS.intersection(raw_argv):
        build_parser().print_help()
        return 0
    if not _has_subcommand(raw_argv):
        config_path, file_paths, verbose = _parse_precommit_args(raw_argv)
        _setup_logging(verbose)
        return run_precommit(file_paths, load_config(config_path))

    parser = build_parser()
    args = parser.parse_args(raw_argv)
    _setup_logging(args.verbose)
    return _dispatch_subcommand(args, load_config(args.config))

Activity · 11 steps
lines 729–729◇ if not _has_subcommand(raw_argv) and _HELP_FLAGS.intersection(raw_argv)lines 730–730build_parser().print_help()lines 731–731return 0lines 732–732◇ if not _has_subcommand(raw_argv)lines 733–733config_path, file_paths, verbose = _parse_precommit_args(raw_argv)lines 734–734_setup_logging(verbose)lines 735–735return run_precommit(file_paths, load_config(config_path))lines 737–737parser = build_parser()lines 738–738args = parser.parse_args(raw_argv)lines 739–739_setup_logging(args.verbose)lines 740–740return _dispatch_subcommand(args, load_config(args.config))

Flows

_run_config_command

int clew.guard.main._run_config_command(argparse.Namespace args, dict[str, Any] config)

Emit the consumer contract as JSON.

clew/guard/main.py:654

Source · 12 lines
def _run_config_command(args: argparse.Namespace, config: dict[str, Any]) -> int:
    from .contract import (
        build_effective_contract,
        build_schema_contract,
        render,
    )

    payload = build_schema_contract() if args.schema else build_effective_contract(config)
    print(render(payload))
    return 0

Activity · 4 steps
lines 655–659from .contract import ( build_effective_contract, build_schema_contract, render, )lines 661–661payload = build_schema_contract() if args.schema else build_effective_contract(config)lines 662–662print(render(payload))lines 663–663return 0

Requirements

REQ-DDB-GUARD-015

Flows

_run_coverage_command

int clew.guard.main._run_coverage_command(argparse.Namespace args, dict[str, Any] config)

Run the coverage subcommand.

clew/guard/main.py:644

Source · 6 lines
def _run_coverage_command(args: argparse.Namespace, config: dict[str, Any]) -> int:
    from .coverage import run_coverage

    return run_coverage(args.source_dirs, config, args.output_format)

Activity · 2 steps
lines 645–645from .coverage import run_coveragelines 647–647return run_coverage(args.source_dirs, config, args.output_format)

Flows

_run_doxyfile_command

int clew.guard.main._run_doxyfile_command(argparse.Namespace _args, dict[str, Any] config)

Emit the Doxyfile fragment for the current config.

clew/guard/main.py:681

Source · 7 lines
def _run_doxyfile_command(_args: argparse.Namespace, config: dict[str, Any]) -> int:
    from .doxyfile import build_fragment

    print(build_fragment(config), end="")
    return 0

Activity · 3 steps
lines 682–682from .doxyfile import build_fragmentlines 684–684print(build_fragment(config), end="")lines 685–685return 0

Requirements

REQ-DDB-GUARD-017

Flows

_run_files_command

int clew.guard.main._run_files_command(argparse.Namespace args, dict[str, Any] config)

Emit the exact post-exclude file set the gate walks, as JSON.

clew/guard/main.py:670

Source · 7 lines
def _run_files_command(args: argparse.Namespace, config: dict[str, Any]) -> int:
    from .contract import build_files_contract, render

    print(render(build_files_contract(args.source_dirs, config)))
    return 0

Activity · 3 steps
lines 671–671from .contract import build_files_contract, renderlines 673–673print(render(build_files_contract(args.source_dirs, config)))lines 674–674return 0

Requirements

REQ-DDB-GUARD-015

Flows

_run_impact_command

int clew.guard.main._run_impact_command(argparse.Namespace args, dict[str, Any] config)

Execute the impact subcommand.

clew/guard/main.py:597

Source · 16 lines
def _run_impact_command(args: argparse.Namespace, config: dict[str, Any]) -> int:
    file_paths = args.files or []
    entries, extras = impact_report(
        file_paths=file_paths,
        config=config,
        staged=args.staged,
        diff_range=args.diff_range,
    )
    if args.write:
        for written in _write_report(entries, report_dir(config), extras):
            print(f"Wrote report: {written.resolve()}")
    else:
        print(format_report(entries, args.output_format, extras))
    return 0

Activity · 8 steps
lines 598–598file_paths = args.files or []lines 599–604entries, extras = impact_report( file_paths=file_paths, config=config, staged=args.staged, diff_range=args.diff_range, )lines 605–605◇ if args.writelines 606–606◇ for written in _write_report(entries, report_dir(config), extras)lines 607–607print(f"Wrote report: {written.resolve()}")lines 608–608elselines 609–609print(format_report(entries, args.output_format, extras))lines 610–610return 0

Requirements

REQ-DDB-GUARD-010

Flows

_setup_logging

None clew.guard.main._setup_logging(bool verbose)

Configure logging based on verbosity flag.

clew/guard/main.py:636

Show on the map →

Called by _run

Calls none

Source · 5 lines
def _setup_logging(verbose: bool) -> None:
    level = logging.DEBUG if verbose else logging.WARNING
    logging.basicConfig(level=level, format="%(levelname)s: %(message)s")

Activity · 2 steps
lines 637–637level = logging.DEBUG if verbose else logging.WARNINGlines 638–638logging.basicConfig(level=level, format="%(levelname)s: %(message)s")

Flows

_validate_files

list[Violation] clew.guard.main._validate_files(list[str] file_paths, dict[str, Any] config, bool no_git=False)

Validate a list of files and report violations.

clew/guard/main.py:306

Source · 38 lines
def _validate_files(
    file_paths: list[str],
    config: dict[str, Any],
    no_git: bool = False,
) -> list[Violation]:
    from .impact import load_external_requirements, load_failure_mode_ids, load_requirements_full

    # THE LOCAL CATALOGUE AND EVERY EXTERNAL ONE (GH #68). The set is passed even when EMPTY —
    # catalogues were looked for and none exists — so the check reports each tag as uncheckable
    # rather than passing it; None is reserved for "no catalogue information supplied".
    local = load_requirements_full(config)
    ## #73 item 3 (2.1): a parent catalogue not cloned here is recorded, not refused.
    unchecked: list[str] = []
    req_ids = set(local) | set(load_external_requirements(config, unchecked))
    # GH #68: every `satisfies` link of the local catalogue must land in some catalogue.
    catalog_file = get_requirements(config).get("file", "")
    violations: list[Violation] = check_satisfies(local, req_ids, catalog_file, unchecked)
    ## 2.2: the failure modes the local catalogue declares, for `@fails_when`.
    mode_ids = load_failure_mode_ids(config)
    skipped: list[str] = []
    for file_path in file_paths:
        if not Path(file_path).exists():
            logger.warning("File not found: %s", file_path)
            continue
        violations.extend(
            validate_file(
                file_path,
                config,
                no_git=no_git,
                req_ids=req_ids,
                skipped=skipped,
                mode_ids=mode_ids,
            )
        )
    _report_skips(skipped)
    return violations

Activity · 15 steps
lines 311–311from .impact import load_external_requirements, load_failure_mode_ids, load_requirements_fulllines 316–316local = load_requirements_full(config)lines 318–318unchecked: list[str] = []lines 319–319req_ids = set(local) | set(load_external_requirements(config, unchecked))lines 321–321catalog_file = get_requirements(config).get("file", "")lines 322–322violations: list[Violation] = check_satisfies(local, req_ids, catalog_file, unchecked)lines 324–324mode_ids = load_failure_mode_ids(config)lines 325–325skipped: list[str] = []lines 326–326◇ for file_path in file_pathslines 327–327◇ if not Path(file_path).exists()lines 328–328logger.warning("File not found: %s", file_path)lines 329–329continuelines 330–339violations.extend( validate_file( file_path, config, no_git=no_git, req_ids=req_ids, skipped=skipped, mode_ids=mode_ids, ) )lines 340–340_report_skips(skipped)lines 341–341return violations

Flows

_write_report

list[Path] clew.guard.main._write_report(list[Any] entries, str base_dir, Any extras=None)

Write the impact report's markdown and JSON into the report directory.

clew/guard/main.py:622

Source · 11 lines
def _write_report(entries: list[Any], base_dir: str, extras: Any = None) -> list[Path]:
    out = Path(base_dir)
    md_path, json_path = out / REPORT_MARKDOWN, out / REPORT_JSON
    validate_output_path(str(md_path))
    validate_output_path(str(json_path))
    out.mkdir(parents=True, exist_ok=True)
    md_path.write_text(format_markdown(entries, extras))
    json_path.write_text(format_json(entries, extras))
    return [md_path, json_path]

Activity · 8 steps
lines 623–623out = Path(base_dir)lines 624–624md_path, json_path = out / REPORT_MARKDOWN, out / REPORT_JSONlines 625–625validate_output_path(str(md_path))lines 626–626validate_output_path(str(json_path))lines 627–627out.mkdir(parents=True, exist_ok=True)lines 628–628md_path.write_text(format_markdown(entries, extras))lines 629–629json_path.write_text(format_json(entries, extras))lines 630–630return [md_path, json_path]

Flows

build_parser

argparse.ArgumentParser clew.guard.main.build_parser()

Create argparse parser with validate/impact/coverage subcommands.

clew/guard/main.py:77

Source · 24 lines
def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="clew guard",
        description="Validate doxygen comments for presence, version staleness, and custom tags",
    )
    parser.add_argument(
        "--config",
        type=Path,
        default=None,
        help="Path to the .clew.yaml whose `guard:` section configures the gate "
        "(default: .clew.yaml in cwd)",
    )
    parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")

    subparsers = parser.add_subparsers(dest="command")
    _add_validate_parser(subparsers)
    _add_impact_parser(subparsers)
    _add_coverage_parser(subparsers)
    _add_config_parser(subparsers)
    _add_files_parser(subparsers)
    _add_doxyfile_parser(subparsers)
    return parser

Activity · 11 steps
lines 78–81parser = argparse.ArgumentParser( prog="clew guard", description="Validate doxygen comments for presence, version staleness, and custom tags", )lines 82–88parser.add_argument( "--config", type=Path, default=None, help="Path to the .clew.yaml whose `guard:` section configures the gate " "(default: .clew.yaml in cwd)", )lines 89–89parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")lines 91–91subparsers = parser.add_subparsers(dest="command")lines 92–92_add_validate_parser(subparsers)lines 93–93_add_impact_parser(subparsers)lines 94–94_add_coverage_parser(subparsers)lines 95–95_add_config_parser(subparsers)lines 96–96_add_files_parser(subparsers)lines 97–97_add_doxyfile_parser(subparsers)lines 98–98return parser

Flows

main

int clew.guard.main.main(list[str]|None argv=None)

Parse arguments and dispatch to the appropriate subcommand.

clew/guard/main.py:709

Source · 14 lines
def main(argv: list[str] | None = None) -> int:
    raw_argv = list(argv if argv is not None else sys.argv[1:])

    retired = _check_retired_subcommand(raw_argv)
    if retired is not None:
        return retired

    try:
        return _run(raw_argv)
    except GuardError as e:
        print(f"clew guard: {e.details()}", file=sys.stderr)
        return 1

Activity · 9 steps
lines 710–710raw_argv = list(argv if argv is not None else sys.argv[1:])lines 712–712retired = _check_retired_subcommand(raw_argv)lines 713–713◇ if retired is not Nonelines 714–714return retiredlines 716–716trylines 717–717return _run(raw_argv)lines 718–718except GuardError as elines 719–719print(f"clew guard: {e.details()}", file=sys.stderr)lines 720–720return 1

Flows

resolve_version_gate

None clew.guard.main.resolve_version_gate(dict[str, Any] config)

Resolve the version gate in place, failing if it is declared but unresolvable.

clew/guard/main.py:437

Source · 23 lines
def resolve_version_gate(config: dict[str, Any]) -> None:
    declared = get_validate(config).get("current_version")
    if not declared:
        logger.info("No version gate declared; all catalogued requirements are active")
        return

    resolved = _detect_current_version(config)
    if not resolved:
        # Previously this just skipped, leaving current_version as the literal
        # "auto:git". parse_version then failed, every requirement filtered out as
        # not-yet-active, and the @req coverage gate silently disabled itself while
        # reporting success — worst on shallow CI clones with no tags.
        logger.error("Version gate %r declared but could not be resolved", declared)
        raise ConfigError(
            f"validate.current_version is {declared!r} but no version "
            f"could be resolved. On a shallow or tagless clone, fetch tags "
            f"(git fetch --tags) or set a literal version."
        )

    logger.info("Version gate resolved: %s -> %s", declared, resolved)
    config.setdefault("validate", {})["_current_version_resolved"] = resolved

Activity · 10 steps
lines 438–438declared = get_validate(config).get("current_version")lines 439–439◇ if not declaredlines 440–440logger.info("No version gate declared; all catalogued requirements are active")lines 441–441returnlines 443–443resolved = _detect_current_version(config)lines 444–444◇ if not resolvedlines 449–449logger.error("Version gate %r declared but could not be resolved", declared)lines 450–454raise ConfigError( f"validate.current_version is {declared!r} but no version " f"could be resolved. On a shallow or tagless clone, fetch tags " f"(git fetch --tags) or set a literal version." )lines 456–456logger.info("Version gate resolved: %s -> %s", declared, resolved)lines 457–457config.setdefault("validate", {})["_current_version_resolved"] = resolved

Requirements

REQ-DDB-GUARD-014

Flows

run_precommit

int clew.guard.main.run_precommit(list[str] file_paths, dict[str, Any] config)

Run all configured checks in pre-commit mode (no subcommand).

clew/guard/main.py:468

Source · 33 lines
def run_precommit(file_paths: list[str], config: dict[str, Any]) -> int:
    logger.info("Pre-commit mode: %d file(s)", len(file_paths))
    logger.info("Config: impact.report_dir=%s", report_dir(config))

    resolve_version_gate(config)

    rc = _report_violations(_validate_files(file_paths, config))

    base_dir = report_dir(config)
    validate_output_path(base_dir)

    if get_requirements(config):
        ## THE HOOK WRITES THE SUBCOMMAND'S REPORT (2.2; entropic, after clew#74): it built the
        ## 2.0.0 entries alone, so its impact.json had no covering tests, `via` or unmapped lists.
        diff_range = get_branch_diff_range(impact_base(config))
        entries, extras = impact_report(
            file_paths, config, staged=not diff_range, diff_range=diff_range or None
        )
        ## THE FULL WRITE PATH IS VALIDATED, not just `output_dir` (1.1.0 audit, M5). The
        ## check above covers `out/`; the writes land in `out/impact/`, so a committed
        ## `out/impact -> ../../elsewhere` passed it, `mkdir(exist_ok=True)` followed the
        ## symlink, and the gate wrote the report outside the repository and `git add`ed it —
        ## as the committing user, configured by the branch under review. Same validation the
        ## sibling in `_run_impact_command` already applies to its `output.file`.
        git_add([str(p) for p in _write_report(entries, base_dir, extras)])
        print(format_markdown(entries, extras), file=sys.stderr)

    ## COVERAGE IS PART OF THE HOOK (2.0.0, PG3, owner): uncovered catalog entries, `req` tag naming
    ## no entry, and a ratio below the declared floor fail the commit, so coverage is never a
    ## separate manual step. Run over the repository (pre-commit's working directory).
    return max(rc, _coverage_gate(config))

Activity · 12 steps
lines 469–469logger.info("Pre-commit mode: %d file(s)", len(file_paths))lines 470–470logger.info("Config: impact.report_dir=%s", report_dir(config))lines 472–472resolve_version_gate(config)lines 474–474rc = _report_violations(_validate_files(file_paths, config))lines 476–476base_dir = report_dir(config)lines 477–477validate_output_path(base_dir)lines 479–479◇ if get_requirements(config)lines 482–482diff_range = get_branch_diff_range(impact_base(config))lines 483–485entries, extras = impact_report( file_paths, config, staged=not diff_range, diff_range=diff_range or None )lines 492–492git_add([str(p) for p in _write_report(entries, base_dir, extras)])lines 493–493print(format_markdown(entries, extras), file=sys.stderr)lines 498–498return max(rc, _coverage_gate(config))

Requirements

REQ-DDB-GUARD-001

Flows

run_validate

int clew.guard.main.run_validate(argparse.Namespace args, dict[str, Any] config)

Run validation checks on all specified files and report violations.

clew/guard/main.py:365

Source · 20 lines
def run_validate(args: argparse.Namespace, config: dict[str, Any]) -> int:
    files = args.files or []
    if not files:
        logger.warning("No files specified for validation")
        # Still a document in a machine format: an empty log, not a missing one.
        return _report_violations([], getattr(args, "output_format", "text"))
    # Resolve here too: this path previously skipped resolution entirely, so the
    # documented `doxygen-guard validate` invocation ran with no @req coverage gate.
    resolve_version_gate(config)
    cli_excludes = getattr(args, "exclude", [])
    if cli_excludes:
        validate = config.setdefault("validate", {})
        existing = validate.get("exclude", [])
        validate["exclude"] = existing + cli_excludes
    return _report_violations(
        _validate_files(files, config, no_git=args.no_git),
        getattr(args, "output_format", "text"),
    )

Activity · 11 steps
lines 366–366files = args.files or []lines 367–367◇ if not fileslines 368–368logger.warning("No files specified for validation")lines 370–370return _report_violations([], getattr(args, "output_format", "text"))lines 373–373resolve_version_gate(config)lines 374–374cli_excludes = getattr(args, "exclude", [])lines 375–375◇ if cli_excludeslines 376–376validate = config.setdefault("validate", {})lines 377–377existing = validate.get("exclude", [])lines 378–378validate["exclude"] = existing + cli_excludeslines 379–382return _report_violations( _validate_files(files, config, no_git=args.no_git), getattr(args, "output_format", "text"), )

Requirements

REQ-DDB-GUARD-001

Flows

validate_file

list[Violation] clew.guard.main.validate_file(str file_path, dict[str, Any] config, bool no_git=False, set[str]|None req_ids=None, list[str]|None skipped=None, set[str]|None mode_ids=None)

Orchestrate presence, staleness, and tag checks for one file.

clew/guard/main.py:201

Show on the map →

Called by _check, _excluded, _undocumented, _validate_files

Tested by

34 teststest_a_broken_toolchain_file_is_reported_not_fatal, test_all_checks_run, test_binary_named_as_source_is_skipped, test_clew_specific_ignores_apply_to_the_gate, test_decorative_triggers_presence_violation, test_docstring_satisfies_req_tag, test_docstring_tags_satisfy_presence, test_documented_file_no_violations, test_excluded_file, test_excluded_path_is_absent_and_gate_skips_it, test_fixture_violations, test_fully_documented_python
22 moretest_inner_doc_satisfies_the_file_block_without_at_file, test_javascript_extensions, test_missing_file_block_suggests_inner_doc, test_nested_lookalike_path_agrees, test_no_false_positives, test_no_false_positives_with_attributes, test_only_definitions_checked, test_opt_in, test_presence_message_c_style_for_c_file, test_presence_message_includes_return_for_non_void, test_presence_message_omits_return_for_void, test_presence_message_python_style, test_require_return_bites_only_on_valued_annotations, test_return_is_not_required_for_rust, test_return_requirement_can_be_turned_back_on, test_rust_is_opt_in, test_toolchain_ignore_paths_skip_validation, test_tsx_file_uses_typescript_config, test_unknown_extension_skipped, test_validate_file_python, test_violations, test_without_toolchain_files_everything_is_checked

Calls check_bus_tags, check_duplicate_tags, check_exemption_reasons, check_fails_when_exists, check_fails_when_markers, check_file_presence, check_presence, check_removed_tags, check_req_coverage, check_req_exists, check_return_presence, check_tags

9 morecheck_unknown_tags, check_version_staleness, excluded_by, gate_exclusion, get_file_at_revision, get_validate, parse_content_for_file, parse_source_file, unconfigured_language

Source · 79 lines
def validate_file(
    file_path: str,
    config: dict[str, Any],
    no_git: bool = False,
    req_ids: set[str] | None = None,
    skipped: list[str] | None = None,
    mode_ids: set[str] | None = None,
) -> list[Violation]:
    validate = get_validate(config)
    pattern = excluded_by(file_path, validate.get("exclude", []))
    if pattern is not None:
        ## COUNTED (2.0.0, PG6): a declared exclusion is a file the gate did not check, and the
        ## report says so every run. It returned silently, so an excluded file vanished.
        logger.info("Skipping %s — matches exclude pattern '%s'", file_path, pattern)
        if skipped is not None:
            skipped.append("excluded by validate.exclude")
        return []
    skip = gate_exclusion(file_path)
    if skip is not None:
        logger.info("Skipping %s — %s", file_path, skip)
        if skipped is not None:
            skipped.append(skip)
        return []

    functions = parse_source_file(file_path, config)
    if functions is None:
        logger.debug("Skipping %s — no matching language config", file_path)
        ## REPORTED ONLY WHEN THE GATE SHIPS A LANGUAGE FOR IT (group A, 1.1.0 merge review).
        ## `rust`, `javascript` and `typescript` are opt-in, so a repository with `.rs` files
        ## and no `rust:` in its `guard:` section was checked by nothing and told so by
        ## nothing. A README is not something the gate failed to check, which is why this asks
        ## `unconfigured_language` rather than reporting every unmatched extension.
        unconfigured = unconfigured_language(config, file_path)
        if unconfigured is not None and skipped is not None:
            skipped.append(f"no `{unconfigured}` language configured — the gate ships one")
        return []

    violations: list[Violation] = []
    content: str | None = None
    try:
        content = Path(file_path).read_text(errors="replace")
        violations.extend(check_file_presence(file_path, content, config))
    except OSError:
        pass
    violations.extend(check_presence(functions, file_path, config, content))
    if content is not None:
        violations.extend(check_return_presence(functions, file_path, config, content))
    violations.extend(check_tags(functions, file_path, config))
    violations.extend(check_req_coverage(functions, file_path, config))
    if content is not None:
        violations.extend(check_bus_tags(functions, file_path, config, content.splitlines()))
    for func in functions:
        violations.extend(check_unknown_tags(func, file_path, config))
        violations.extend(check_removed_tags(func, file_path, config))
        violations.extend(check_exemption_reasons(func, file_path, config))
        violations.extend(check_duplicate_tags(func, file_path, config))
        violations.extend(check_req_exists(func, file_path, config, req_ids))
        violations.extend(check_fails_when_exists(func, file_path, config, mode_ids))
        if content is not None:
            violations.extend(
                check_fails_when_markers(func, file_path, content.splitlines(), mode_ids)
            )

    if not no_git and content is not None:
        head_content = get_file_at_revision(file_path)
        head_functions = (
            parse_content_for_file(file_path, head_content, config)
            if head_content is not None
            else None
        )
        violations.extend(
            check_version_staleness(
                functions, file_path, config, content, head_functions, head_content
            )
        )

    return violations

Activity · 48 steps
lines 209–209validate = get_validate(config)lines 210–210pattern = excluded_by(file_path, validate.get("exclude", []))lines 211–211◇ if pattern is not Nonelines 214–214logger.info("Skipping %s — matches exclude pattern '%s'", file_path, pattern)lines 215–215◇ if skipped is not Nonelines 216–216skipped.append("excluded by validate.exclude")lines 217–217return []lines 218–218skip = gate_exclusion(file_path)lines 219–219◇ if skip is not Nonelines 220–220logger.info("Skipping %s — %s", file_path, skip)lines 221–221◇ if skipped is not Nonelines 222–222skipped.append(skip)lines 223–223return []lines 225–225functions = parse_source_file(file_path, config)lines 226–226◇ if functions is Nonelines 227–227logger.debug("Skipping %s — no matching language config", file_path)lines 233–233unconfigured = unconfigured_language(config, file_path)lines 234–234◇ if unconfigured is not None and skipped is not Nonelines 235–235skipped.append(f"no `{unconfigured}` language configured — the gate ships one")lines 236–236return []lines 238–238violations: list[Violation] = []lines 239–239content: str | None = Nonelines 240–240trylines 241–241content = Path(file_path).read_text(errors="replace")lines 242–242violations.extend(check_file_presence(file_path, content, config))lines 243–243except OSErrorlines 244–244passlines 245–245violations.extend(check_presence(functions, file_path, config, content))lines 246–246◇ if content is not Nonelines 247–247violations.extend(check_return_presence(functions, file_path, config, content))lines 248–248violations.extend(check_tags(functions, file_path, config))lines 249–249violations.extend(check_req_coverage(functions, file_path, config))lines 250–250◇ if content is not Nonelines 251–251violations.extend(check_bus_tags(functions, file_path, config, content.splitlines()))lines 252–252◇ for func in functionslines 253–253violations.extend(check_unknown_tags(func, file_path, config))lines 254–254violations.extend(check_removed_tags(func, file_path, config))lines 255–255violations.extend(check_exemption_reasons(func, file_path, config))lines 256–256violations.extend(check_duplicate_tags(func, file_path, config))lines 257–257violations.extend(check_req_exists(func, file_path, config, req_ids))lines 258–258violations.extend(check_fails_when_exists(func, file_path, config, mode_ids))lines 259–259◇ if content is not Nonelines 260–262violations.extend( check_fails_when_markers(func, file_path, content.splitlines(), mode_ids) )lines 264–264◇ if not no_git and content is not Nonelines 265–265head_content = get_file_at_revision(file_path)lines 266–270head_functions = ( parse_content_for_file(file_path, head_content, config) if head_content is not None else None )lines 271–275violations.extend( check_version_staleness( functions, file_path, config, content, head_functions, head_content ) )lines 277–277return violations

Requirements

REQ-DDB-GUARD-001

Flows