Apero.Env (Apero v1.0.0)

Copy Markdown View Source

Environment variable management for Apero.

Provides loading from .env files, merging with system environment, value parsing, required-variable validation and type coercion.

Loading a .env file

Apero.Env.load(".env")
System.get_env("MY_VAR")  # now available

Summary

Functions

Returns a map of all current environment variables.

Removes a key from the process environment.

Gets an environment variable, returning default if not set.

Gets an environment variable and casts it to the given type.

Loads a .env file and puts each key-value pair into the process environment.

Sets a key-value pair in the process environment.

Reads a .env file and returns its contents as a map without modifying the process environment.

Validates that all required environment variables are set.

Writes a map of key-value pairs to a .env file.

Functions

all()

@spec all() :: map()

Returns a map of all current environment variables.

delete(key)

@spec delete(binary()) :: :ok

Removes a key from the process environment.

get(key, default \\ nil)

@spec get(binary(), any()) :: binary() | any()

Gets an environment variable, returning default if not set.

get_as(key, type)

@spec get_as(binary(), :string | :integer | :float | :boolean | :atom) ::
  {:ok, any()} | {:error, binary()}

Gets an environment variable and casts it to the given type.

Supported types: :string, :integer, :float, :boolean, :atom.

Returns {:ok, value} or {:error, reason}.

Examples

iex> System.put_env("PORT", "4000")
iex> Apero.Env.get_as("PORT", :integer)
{:ok, 4000}

iex> System.put_env("DEBUG", "true")
iex> Apero.Env.get_as("DEBUG", :boolean)
{:ok, true}

load(path \\ ".env")

@spec load(binary()) :: {:ok, map()} | {:error, binary()}

Loads a .env file and puts each key-value pair into the process environment.

Lines starting with # and empty lines are ignored. Both KEY=VALUE and export KEY=VALUE formats are supported. Values may optionally be quoted.

Returns the loaded values as a map.

put(key, value)

@spec put(binary(), binary()) :: :ok

Sets a key-value pair in the process environment.

read(path \\ ".env")

@spec read(binary()) :: {:ok, map()} | {:error, binary()}

Reads a .env file and returns its contents as a map without modifying the process environment.

require_keys(keys)

@spec require_keys([binary()]) :: {:ok, map()} | {:error, [binary()]}

Validates that all required environment variables are set.

Returns {:ok, map} with the values, or {:error, [missing_keys]}.

Examples

iex> System.put_env("HOST", "localhost")
iex> {:ok, values} = Apero.Env.require_keys(["HOST"])
iex> values["HOST"]
"localhost"

write(path \\ ".env", vars)

@spec write(binary(), map()) :: :ok | {:error, binary()}

Writes a map of key-value pairs to a .env file.

Existing content is replaced. Values containing spaces are quoted.