Skip to content

confingy.cli.serialize#

serialize #

Serialize command for confingy CLI.

This module provides functionality to serialize Python configuration objects to JSON.

serialize #

serialize(
    file_spec: Annotated[
        str,
        Argument(
            help="File path or dotted module path with optional variable name (e.g. path/to/file.py, path.to.module, path/to/file.py::var_name). If the resolved variable is a function, it is called automatically. Defaults to loading 'config'."
        ),
    ],
    output: Annotated[
        str | None,
        Option(
            help="Output JSON file path (optional, prints to stdout if not provided)"
        ),
    ] = None,
) -> None

Serialize a configuration object to JSON.

Source code in src/confingy/cli/serialize.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def serialize(
    file_spec: Annotated[
        str,
        typer.Argument(
            help="File path or dotted module path with optional variable name "
            "(e.g. path/to/file.py, path.to.module, path/to/file.py::var_name). "
            "If the resolved variable is a function, it is called automatically. "
            "Defaults to loading 'config'."
        ),
    ],
    output: Annotated[
        str | None,
        typer.Option(
            help="Output JSON file path (optional, prints to stdout if not provided)"
        ),
    ] = None,
) -> None:
    """
    Serialize a configuration object to JSON.
    """
    try:
        config = load_variable_from_file(file_spec)
        if inspect.isfunction(config):
            config = config()
        serialized = serialize_fingy(config)
        json_output = json.dumps(serialized)

        if output:
            with open(output, "w") as f:
                f.write(json_output)
            typer.echo(f"Configuration serialized to {output}")
        else:
            # Print to stdout
            typer.echo(json_output)
    except Exception as e:
        typer.echo(f"Error: {e}", err=True)
        raise e