API reference

Most of the public API is covered in Reference. The symbols below round out the surface for tool authors and contributors.

codegen CLI

Codegen CLI entry point.

The CLI is target-agnostic: every piece of framework-specific behavior comes from a Target discovered via the codegen.targets entry-point group. The codegen CLI loads the config, runs the generic pipeline against the target’s registry/assembler/env, and writes files to disk.

clean_cmd(config, out=PosixPath('.'), target_name=None)[source]

Delete the output directory.

Removes out and its contents. The current working directory is never deleted. --config is parsed so the CLI surfaces config errors consistently, but its contents do not influence what is removed.

Return type:

None

cli_main()[source]

Run the CLI, converting CLIError cleanly.

Any CLIError raised inside a command is rendered as {prefix}: {message} on stderr and exits with code 1. Other exceptions propagate with a traceback, because they indicate a bug rather than bad user input.

Return type:

None

diff_cmd(config, out=PosixPath('.'), target_name=None, shadowed=False, check=False, navigator=False, patch=False, name_only=False, unchanged=False, context=3)[source]

Preview what an apply (generate) would change on disk.

Generates in memory and compares the result to the files already in out, writing nothing. By default it previews every pending change, flagging each as one a plain generate will apply or one that is shadowed – a modified skip file (e.g. be_root’s bootstrap scaffold) that a normal run leaves alone, so its proposed content silently drifts from disk until you run --force. Pass --shadowed to see only that hidden drift.

Renders as a report (default), a raw patch (--patch), a name list (--name-only), or an interactive navigator (--navigate).

Return type:

None

generate_cmd(config, out=PosixPath('.'), target_name=None, clean=False, dry_run=False, force=False, force_paths=None, paths=None)[source]

Generate files from a config via the selected target.

Return type:

None

main()[source]

Run the generic code-generation CLI.

Return type:

None

targets_list_cmd()[source]

List every target registered under codegen.targets.

Each line is formatted as <name> (<language>) so users can see at a glance which target to pass to --target.

Return type:

None

validate_cmd(config, target_name=None)[source]

Validate a config file without generating anything.

Parses and schema-checks --config using the selected target, then exits. Useful as a pre-commit check or for editor integrations that want fast feedback without running the full pipeline.

Return type:

None

be target

be_root target

The schema (be_root.config.RootConfig) is documented in Reference. The wiring lives here:

fe target

The schema (fe.config.ProjectConfig) is documented in Reference. The wiring lives here:

fe_root target

The schema (fe_root.config.RootConfig) is documented in Reference. The wiring lives here:

codegen.config

Load and validate target config files.

Supports .json files directly and .jsonnet files via codegen.jsonnet, which adds prefix-based stdlib imports so targets can ship their own libsonnet helpers under a registered prefix (e.g. import 'be/auth/jwt.libsonnet').

class CodegenConfig(**data)[source]

Base class for target-level config schemas.

Targets registering with codegen should subclass this so their config model carries the codegen-recognized meta fields. Today that is just package_prefix; more may be added as codegen grows. Target-specific fields (auth, databases, apps, routes, whatever) are declared by the subclass.

package_prefix

Dotted prefix prepended to the dotted import path of every GeneratedFile (and used as the on-disk directory prefix). Empty string disables the prefix. Targets that generate Python (or another language with package semantics) should override the default to something sensible (be uses "_generated").

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ExtensibleConfig(**data)[source]

Base for config nodes whose extra keys feed an op’s options.

Targets that dispatch ops by a field value (name, type, …) and pass every other key through to the op’s own Options model can subclass this to inherit extra="allow" plus the options accessor instead of re-spelling them per config class. be uses it for be.config.schema.OperationConfig and be.config.schema.ModifierConfig; other targets that need the same dispatch shape can do the same.

model_config: ClassVar[ConfigDict] = {'extra': 'allow'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property options: dict[str, Any]

Op-specific options (every key not declared on the model).

load_config(path, schema, stdlibs=None)[source]

Load and validate a config file against schema.

Parameters:
Return type:

CodegenConfig

Returns:

Validated model instance of schema.

Raises:

ConfigError – If the file is missing, has an unsupported extension, fails to parse, or fails schema validation.

codegen.jsonnet

Thin wrapper around _jsonnet with prefix-based stdlib imports.

Jsonnet delegates import resolution to a host-supplied callback. This module provides a callback that interprets the first path segment of an import as a registered stdlib prefix: given {"be": Path(".../jsonnet")}, an import like 'be/auth/jwt.libsonnet' resolves under that directory. Imports without a matching prefix fall through to the normal relative-to-importer resolution, so user configs can still import './shared.libsonnet' freely.

The only public entry points are evaluate() (file in, JSON string out) and make_import_callback() (the bare callback, exposed for callers that want to build their own evaluator).

evaluate(path, stdlibs=None)[source]

Evaluate a Jsonnet file to a JSON string.

Parameters:
  • path (Path) – Path to the .jsonnet file.

  • stdlibs (Mapping[str, Path] | None) – Optional mapping of jsonnet import prefix to stdlib directory. {"be": Path(".../jsonnet")} makes import 'be/...' resolve under that directory.

Return type:

str

Returns:

JSON string produced by the Jsonnet evaluator.

Raises:
make_import_callback(stdlibs)[source]

Build a jsonnet import callback that honours stdlibs.

Imports whose first path segment matches a registered prefix are resolved from the associated stdlib directory; all other imports are resolved relative to the importing file.

Parameters:

stdlibs (Mapping[str, Path]) – Mapping of import prefix to stdlib directory.

Return type:

Callable[[str, str], tuple[str, bytes]]

Returns:

Callable with the _jsonnet import-callback signature (importing_dir, import_path) -> (resolved_path, bytes).

codegen.pipeline

Generic build pipeline: config in, files out.

Runs the Engine over the full config tree in a single pass, then assembles the build store into files using codegen’s shared registry and generic assembler. Reads package_prefix directly from the config and does not inspect any target-specific field.

generate(config, target)[source]

Generate all files for a validated config.

Engine runs the hierarchical engine once over the full config tree, then codegen’s generic assembler turns the resulting build store into files.

Operation discovery is target-scoped: load_registry() walks the target’s operations_entry_point group at build time and assembles a fresh registry from the classes declared there. Targets installed side-by-side never see each other’s ops.

Parameters:
  • config (CodegenConfig) – Validated config model.

  • target (Target) – The selected target; its template_dir builds the Jinja environment, and its operations_entry_point drives the per-build registry.

Return type:

list[GeneratedFile]

Returns:

Flat list of generated files.

Raises:

GenerationError – If config semantics are invalid (e.g. a resource references an unknown operation, or an operation’s options fail introspection).

codegen.assembler

Assembler: combine fragments into output files.

Each dispatched render gets a RenderCtx with store and instance_id set to the current entry. Renderers yield a FileFragment (declaring the output file and its wrapper template) plus one or more SnippetFragment contributions into the file’s slot lists. This module folds them: files with the same path merge via |, snippets render (either from value or their template), and each file’s wrapper is rendered once with every slot’s items in order.

assemble(store, registry, ctx)[source]

Turn a build store into rendered output files.

Walks every item in the store, dispatches to the registry to collect file/snippet fragments, then renders one file per declared shell with its snippets folded in.

Parameters:
  • store (BuildStore) – The build store from the engine’s build phase.

  • registry (RenderRegistry) – Render registry with all renderers registered.

  • ctx (RenderCtx) – Render context – env, config, package prefix.

Return type:

list[GeneratedFile]

Returns:

Flat list of GeneratedFile objects ready for output.

codegen.banner

Centralized autogenerated-file banner.

Every generated file gets a header banner the engine prepends at render time – one consistent wording across all targets and languages, with the overwrite-vs-scaffold note derived from the file’s actual if_exists policy rather than retyped by hand in each template.

Comment syntax is resolved per file extension (a single target emits several file types – a Python target also writes justfile/.toml/.ini), so the lookup keys on the file name/extension rather than the target’s language identifier. Codegen ships sensible defaults for the languages it knows; third parties extend or override them by registering a provider under the codegen.comment_styles entry-point group – a Callable[[], dict[str, CommentStyle]] named for the language.

class CommentStyle(line=None, block=None, fill='#')[source]

How to wrap banner text in a given file type’s comments.

The banner is boxed: a top and bottom rule of the fill character frame the text so it reads as a distinct “autogenerated” block. Exactly one of line / block is set:

  • line – a line-comment prefix ("#", "//"). Text lines are f"{line} {text}"; the rule is fill repeated (e.g. a solid row of # or /).

  • block(open, cont, close) for block comments. The banner is open on its own line, a fill rule, the text lines as f"{cont}{text}", another rule, then close (e.g. ("/*", " * ", " */") with fill="*" for CSS).

A file type with no registered style gets no banner at all (e.g. JSON, which has no comment form).

render(lines)[source]

Render lines of banner text, boxed in this comment syntax.

Return type:

str

comment_style_for(path)[source]

Resolve the comment style for path, or None if unknown.

Tries the full file name first (so justfile / .env.example match), then the bare extension.

Return type:

CommentStyle | None

render_banner(*, target_name, path, if_exists)[source]

Render the autogenerated banner for path, or "".

Returns the empty string when path’s file type has no registered comment style (so the caller prepends nothing). The wording is derived from if_exists: "overwrite" files are clobbered every run; "skip" files are one-shot scaffolds preserved on re-run.

Return type:

str

be.operations