env-or-file (0.1.1)

Published 2026-10-10 14:44:37 +00:00 by jontze

Installation

[registries.forgejo]
index = "sparse+" # Sparse index
# index = "" # Git

[net]
git-fetch-with-cli = true
cargo add env-or-file@0.1.1 --registry forgejo

About this package

Read configuration values and secrets from `KEY` or from the file referenced by `KEY_FILE`

env-or-file

Read a value from an environment variable, or from the file another variable points to.

MY_SECRET=super-secret               → "super-secret"
MY_SECRET_FILE=/run/secrets/secret   → contents of /run/secrets/secret

This follows the *_FILE convention of Docker secrets, Kubernetes secret volumes and the official postgres/mariadb images.

Usage

[dependencies]
env-or-file = { version = "0.1", registry = "wffl" }
let secret = env_or_file::var("MY_SECRET")?;            // required
let level = env_or_file::var_opt("LOG_LEVEL")?;          // Option<String>
let key = env_or_file::var_bytes("SIGNING_KEY")?;        // Vec<u8>
let token = env_or_file::EnvOrFile::new("TOKEN")         // custom suffix: TOKEN_PATH
    .file_suffix("_PATH")
    .var()?;

Rules

KEY KEY_FILE Result
set unset value of KEY
unset set file contents, with one trailing \n / \r\n stripped
set set Error::Conflict
unset unset Error::NotPresent (var_opt returns Ok(None))
  • Relative paths are resolved against the current working directory.
  • Errors implement std::error::Error and keep the underlying io::Error as their source().
  • Errors never contain the value, only variable names and paths.

Compile time

Opt in with the macros feature to get env!-like macros with the same rules:

env-or-file = { version = "0.1", registry = "wffl", features = ["macros"] }
const API_URL: &str = env_or_file::env_or_file!("API_URL");
const DSN: Option<&str> = env_or_file::option_env_or_file!("SENTRY_DSN");

Relative paths are resolved against the crate's CARGO_MANIFEST_DIR. Cargo rebuilds when either variable or the file changes. The value is embedded in plain text in the binary, so don't use the macros for runtime secrets.

Development

nix develop                                # toolchain + tools
cargo test --workspace --all-features      # all tests
nix flake check                            # everything CI runs

The crate contains no unsafe code (unsafe_code = "forbid", including tests).

Dependencies

ID Version
env-or-file-macros =0.1.1
tempfile ^3.27.0
trybuild ^1.0.122

Keywords

env secrets config file
Details
Cargo
2026-10-10 14:44:37 +00:00
10
MIT OR Apache-2.0
24 KiB
Assets (1)
Versions (2) View all
0.1.1 2026-10-10
0.1.0 2026-10-10