Skip to content

API Reference

envlit.cli

Command-line interface for envlit. Provides shell script generation commands.

DynamicFlagCommand

Bases: Command

Custom Click command that dynamically adds flag options based on config file.

This allows flags like --cuda, --backend to be recognized from the config.

parse_args(ctx, args)

Override parse_args to add dynamic options before argument parsing.

cli()

envlit: Environment Orchestration Engine

doctor(shell)

Check envlit installation and configuration.

Verifies that envlit is properly set up in your shell.

find_config_file(profile=None, search_dir=None)

Find the configuration file for a given profile.

Search order: 1. If profile is specified: - .envlit/.yaml - .envlit/.yml 2. If no profile specified: - .envlit/default.yaml - .envlit/default.yml

Parameters:

Name Type Description Default
profile str | None

Optional profile name (e.g., "dev", "prod")

None
search_dir Path | None

Directory to search in (defaults to current directory)

None

Returns:

Type Description
Path | None

Path to config file if found, None otherwise

init(shell, alias_load, alias_unload)

Generate shell initialization code for envlit.

 Add this to your .bashrc or .zshrc (recommended): eval "\((envlit init)" # or with options: eval "\)(envlit init --shell zsh)" eval "$(envlit init --alias-load myload --alias-unload myunload)"

The generated code creates shell functions that wrap envlit commands.

internal_track_cli(phase)

Internal command for state tracking (not for direct user use).

Called by generated shell scripts as 'envlit-internal-track '.

load(profile, config, **kwargs)

Generate shell script to load environment configuration.

 For daily use with aliases (recommended): el # Load default profile el dev --cuda 1 # Load dev profile with CUDA device 1

 Direct usage (after running 'source <(envlit init)'): source <(envlit load) source <(envlit load dev --cuda 1) source <(envlit load --config path/to/config.yaml)

Dynamic flags from the config file are automatically added as options.

state(from_env)

Output tracked environment variables in .env format.

By default, outputs values from envlit's state (last values set by envlit). Use --from-env to output current values from the environment instead.

 Usage: envlit state # Show tracked variables (from state) envlit state --from-env # Show current environment values envlit state > .env # Export to .env file

unload(profile, config)

Generate shell script to unload environment configuration.

 For daily use with aliases (recommended): eul # Unload current environment

 Direct usage: source <(envlit unload)

envlit.config

Configuration parsing and management. Handles YAML config loading with inheritance support.

load_config(config_path)

Load a YAML configuration file.

Parameters:

Name Type Description Default
config_path str

Path to the YAML configuration file.

required

Returns:

Type Description
dict[str, Any]

Parsed configuration dictionary.

Raises:

Type Description
FileNotFoundError

If the config file doesn't exist.

YAMLError

If the YAML is invalid.

resolve_inheritance(config, config_dir)

Resolve inheritance in a configuration.

Parameters:

Name Type Description Default
config dict[str, Any]

Configuration dictionary.

required
config_dir Path

Directory containing the config file (for resolving relative paths).

required

Returns:

Type Description
dict[str, Any]

Configuration with inheritance resolved.

envlit.script_generator

Shell script generation from configuration. Generates bash scripts that can be sourced to load/unload environments.

escape_shell_value(value)

Escape a value for use in a shell script, preserving ${VAR} references.

We want to preserve ${VAR} and $VAR for shell expansion, including complex parameter expansions with modifiers like ${VAR:-default}, ${VAR:0:5}, etc. Since we use double quotes, we need to escape: $ ` " and newlines, EXCEPT for variable references and their modifiers.

Supports {{DOLLAR}} placeholder for literal dollar signs.

Parameters:

Name Type Description Default
value str

The value to escape.

required

Returns:

Type Description
str

Escaped value safe for use in double quotes.

generate_load_script(config, flag_overrides=None)

Generate a shell script to load an environment configuration.

The generated script follows the sandwich pattern: 1. envlit-internal-track begin (capture snapshot A) 2. Pre-load hooks 3. Environment variable exports 4. Post-load hooks 5. envlit-internal-track end (capture snapshot B, update state) Args: config: Configuration dictionary with env, flags, and hooks sections. flag_overrides: Optional dictionary of flag values to override defaults.

Returns:

Type Description
str

Shell script as a string.

generate_unload_script(config)

Generate a shell script to unload an environment configuration.

The script will: 1. Run pre_unload hooks 2. Call state restoration logic (handled by internal tracker) 3. Run post_unload hooks

Parameters:

Name Type Description Default
config dict[str, Any]

Configuration dictionary with hooks section.

required

Returns:

Type Description
str

Shell script as a string.

envlit.operations

Atomic environment variable operations. Each operation is a pure function: (current_value, op_config) -> new_value

apply_operation(current_value, operation)

Apply a single atomic operation to a value.

Parameters:

Name Type Description Default
current_value str | None

Current value of the variable (None if unset)

required
operation dict[str, Any]

Operation dict with 'op' and optional 'value' keys

required

Returns:

Type Description
str | None

New value after operation (None means unset)

Raises:

Type Description
ValueError

If operation is invalid

apply_operations(initial_value, operations)

Apply a pipeline of operations sequentially.

Parameters:

Name Type Description Default
initial_value str | None

Starting value (None if unset)

required
operations list[dict[str, Any]]

List of operation dicts

required

Returns:

Type Description
str | None

Final value after all operations

normalize_env_value(value)

Normalize an environment value to a list of operations.

Handles three formats: - String: Converted to [{"op": "set", "value": string}] - Dict: Converted to [dict] (single operation) - List of dicts: Returned as-is (pipeline of operations)

Parameters:

Name Type Description Default
value Any

The value from the env section of config

required

Returns:

Type Description
list[dict[str, Any]]

List of operation dictionaries

Raises:

Type Description
ValueError

If value format is invalid

validate_operation(operation)

Validate an operation dictionary.

Raises:

Type Description
ValueError

If operation is invalid

envlit.state

State management for envlit. Implements the Compare-and-Swap algorithm for tracking environment variable changes.

StateManager

Manages the state record for environment variables.

__init__()

Initialize StateManager and load existing state.

get_current_value(var_name)

Get the current value of a tracked variable.

get_env_dict(from_env=False)

Get tracked variables as a dictionary.

Parameters:

Name Type Description Default
from_env bool

If True, get values from os.environ; if False, get from state's 'current' values

False

Returns:

Type Description
dict[str, str]

Dictionary mapping variable names to values

get_original_value(var_name)

Get the original value of a tracked variable.

get_state()

Get the current state dictionary.

get_tracked_variables()

Get list of all tracked variable names.

update_variable(var_name, actual_val, target_val)

Update a variable using the Compare-and-Swap algorithm.

Implements the decision matrix from the design spec: 1. New Variable: Save actual_val as original, set target_val as current 2. Consecutive Load: Keep existing original, update current to target_val 3. Manual Interference: Update original to actual_val, set current to target_val

Parameters:

Name Type Description Default
var_name str

Name of the environment variable.

required
actual_val str | None

Current value in the environment (None if unset).

required
target_val str | None

Desired value to set (None to unset).

required

envlit.internal

Internal tracking functionality for envlit. These functions are called by the generated shell scripts via the envlit-internal-track CLI command.

track_begin()

Capture the current environment state (Snapshot A) and output as JSON.

This is called at the beginning of a load script before any changes are made. The output is captured by the shell: __ENVLIT_SNAPSHOT_A=$(envlit-internal-track begin)

Returns:

Type Description
str

JSON string of current environment variables.

track_end()

Capture the ending state (Snapshot B), compare with Snapshot A, and update the __ENVLIT_STATE variable.

track_restore()

Restore environment variables to their original values from __ENVLIT_STATE. Detects manual changes and preserves them.