export_command.py

clew/export_command.py

`clew export` — write an index's TIER-1 STATEMENTS back out as a declaration.

_parser

argparse.ArgumentParser clew.export_command._parser()

clew export 's argument parser.

clew/export_command.py:139

Show on the map →

Called by export_main

Calls none

Source · 18 lines
def _parser() -> argparse.ArgumentParser:
    """PS2 (2.0.0): a function of its own, so `clew.cli_surface` can pin the covered flags.

    @brief Build the parser.
    @return Parser.
    """
    parser = argparse.ArgumentParser(
        prog=f"clew {EXPORT_COMMAND}",
        description="Write an index's tier-1 statements out as a declaration document.",
    )
    parser.add_argument("--index", required=True, help="path to a built clew.db")
    parser.add_argument("--output", help="write here instead of stdout")
    parser.add_argument(
        "--force", action="store_true", help="overwrite --output if it already exists"
    )
    return parser

Activity · 5 steps
lines 145–148parser = argparse.ArgumentParser( prog=f"clew {EXPORT_COMMAND}", description="Write an index's tier-1 statements out as a declaration document.", )lines 149–149parser.add_argument("--index", required=True, help="path to a built clew.db")lines 150–150parser.add_argument("--output", help="write here instead of stdout")lines 151–153parser.add_argument( "--force", action="store_true", help="overwrite --output if it already exists" )lines 154–154return parser

Flows

export_main

int clew.export_command.export_main(list[str] argv)

clew export entry point.

clew/export_command.py:163

Source · 35 lines
def export_main(argv: list[str]) -> int:
    """WRITES TO STDOUT BY DEFAULT, and `--output` is opt-in. The common use is piping into the
    repo's own `.clew.yaml` under review, and a command that silently created that file
    would be a command that overwrites a curated declaration — the one file in this design a human
    is expected to have edited by hand.

    REFUSES AN OUTPUT PATH THAT EXISTS, for the same reason, unless `--force`. `init` prompts before
    touching a CLAUDE.md on the identical argument: a config can be regenerated, a curated document
    cannot.

    @brief Parse arguments and emit the export.
    @return Exit status.
    @version 2
    """
    args = _parser().parse_args(argv)

    db = Path(args.index).expanduser().resolve()
    if not db.is_file():
        logger.error("export: no index at %s", db)
        return 1
    text = render(stated_declaration(db), db)
    if not args.output:
        sys.stdout.write(text)
        return 0
    target = Path(args.output).expanduser().resolve()
    if target.exists() and not args.force:
        logger.error(
            "export: %s already exists — pass --force to overwrite it. A declaration is a "
            "curated file; regenerating one on top of hand-written content is not recoverable.",
            target,
        )
        return 1
    target.write_text(text, encoding="utf-8")
    logger.info("export: wrote %s", target)
    return 0

1 more lines, not shown

Activity · 16 steps
lines 177–177args = _parser().parse_args(argv)lines 179–179db = Path(args.index).expanduser().resolve()lines 180–180◇ if not db.is_file()lines 181–181logger.error("export: no index at %s", db)lines 182–182return 1lines 183–183text = render(stated_declaration(db), db)lines 184–184◇ if not args.outputlines 185–185sys.stdout.write(text)lines 186–186return 0lines 187–187target = Path(args.output).expanduser().resolve()lines 188–188◇ if target.exists() and not args.forcelines 189–193logger.error( "export: %s already exists — pass --force to overwrite it. A declaration is a " "curated file; regenerating one on top of hand-written content is not recoverable.", target, )lines 194–194return 1lines 195–195target.write_text(text, encoding="utf-8")lines 196–196logger.info("export: wrote %s", target)lines 197–197return 0

Requirements

REQ-DDB-CLI-001

Flows

render

str clew.export_command.render(dict[str, Any] declaration, Path db)

Render a declaration mapping as YAML, with a header saying where it came from.

clew/export_command.py:103

Show on the map →

Called by none

Calls none

Source · 32 lines
def render(declaration: dict[str, Any], db: Path) -> str:
    """THE HEADER IS NOT DECORATION. This file will be committed into a repository and read months
    later by someone who did not run the export, and the two questions they will have are "did a
    human write this or a tool" and "does it cover everything the build did". The second is the
    dangerous one: this document holds the TIER-1 statements only, so a reader who assumes it is
    the whole configuration will be wrong about every default. Saying so in the file is the only
    place that warning survives.

    An EMPTY declaration still renders the header and an explicit note, because a zero-byte file
    reads as a failed command. "This index recorded no statements" is a result.

    @brief Render the export document.
    @return YAML text.
    @version 1
    """
    import yaml

    head = (
        "# Generated by `clew export` — the TIER-1 STATEMENTS recorded in an index.\n"
        f"# source index: {db.name}\n"
        "#\n"
        "# This is NOT the build's full configuration. It holds only what a caller STATED; the\n"
        "# built-in defaults are deliberately absent, so that improving a default still reaches\n"
        "# this repository instead of being shadowed by a value nobody remembers committing.\n"
        "#\n"
        "# Re-apply with: clew --repo-root <repo> --declare <this file>\n"
    )
    if not declaration:
        return head + "#\n# This index recorded NO tier-1 statements — nothing was stated.\n"
    return head + yaml.safe_dump(declaration, sort_keys=True, default_flow_style=False)

Activity · 5 steps
lines 118–118import yamllines 120–129head = ( "# Generated by `clew export` — the TIER-1 STATEMENTS recorded in an index.\n" f"# source index: {db.name}\n" "#\n" "# This is NOT the build's full configuration. It holds only what a caller STATED; the\n" "# built-in defaults are deliberately absent, so that improving a default still reaches\n" "# this repository instead of being shadowed by a value nobody remembers committing.\n" "#\n" "# Re-apply with: clew --repo-root <repo> --declare <this file>\n" )lines 130–130◇ if not declarationlines 131–131return head + "#\n# This index recorded NO tier-1 statements — nothing was stated.\n"lines 132–132return head + yaml.safe_dump(declaration, sort_keys=True, default_flow_style=False)

Requirements

REQ-DDB-CONFIG-001

stated_declaration

dict[str, Any] clew.export_command.stated_declaration(Path db)

The declaration mapping an index's recorded tier-1 statements reproduce.

clew/export_command.py:58

Source · 39 lines
def stated_declaration(db: Path) -> dict[str, Any]:
    """READ THROUGH THE SAME HELPERS THE REPLAY USES — `stated_options`, `recorded_explicit`,
    `recorded_document` — rather than querying `build_meta` directly. A second reader of the same
    rows is a second notion of what a statement IS, and the two would eventually disagree about a
    withdrawal: `{}` removes the record, and code that looked for the row rather than asking these
    helpers would export a stale value the replay has already dropped.

    A LIST OPTION AND A DOCUMENT OPTION ARE ASKED FOR SEPARATELY because the stored forms differ —
    `.explicit` holds a comma-joined list, a document holds canonical JSON or a path — and
    guessing from the string's shape would misread a one-element list as a scalar.

    @brief Reconstruct the declaration from an index's records.
    @return The stated mapping.
    @version 1
    """
    from .buildoptions import INLINE_LIST_OPTIONS

    ## THE PREFIX MUST COME OFF, and getting this wrong is why the first version of this function
    ## raised on its own control. Every `tiers` reader takes a section whose keys have already had
    ## `options.` stripped — `_options_meta` does that — so a raw `build_meta` read hands them keys
    ## like `options.predefined.tier`, `stated_options` reports the option as `options.predefined`,
    ## the `INLINE_LIST_OPTIONS` membership test misses, and the list is then decoded as a JSON
    ## document. It failed loudly here only because a comma-joined list is not valid JSON; an
    ## option whose stored value happened to parse would have exported silently wrong.
    section = meta_section(db, OPTIONS_META_PREFIX)

    out: dict[str, Any] = {}
    for option in stated_options(section):
        if option in INLINE_LIST_OPTIONS:
            values = recorded_explicit(section, option)
            if values:
                out[option] = list(values)
            continue
        document = recorded_document(section, option)
        if document is not None:
            out[option] = document
    return out

Activity · 13 steps
lines 73–73from .buildoptions import INLINE_LIST_OPTIONSlines 82–82section = meta_section(db, OPTIONS_META_PREFIX)lines 84–84out: dict[str, Any] = {}lines 85–85◇ for option in stated_options(section)lines 86–86◇ if option in INLINE_LIST_OPTIONSlines 87–87values = recorded_explicit(section, option)lines 88–88◇ if valueslines 89–89out[option] = list(values)lines 90–90continuelines 91–91document = recorded_document(section, option)lines 92–92◇ if document is not Nonelines 93–93out[option] = documentlines 94–94return out

Requirements

REQ-DDB-CONFIG-001

Flows