envfmt
A lightweight Rust crate for expanding environment-style variables in strings, similar to shell expansion.
This crate provides a simple and efficient way to substitute variables in a
string, using either the process environment or a custom context like a
HashMap
.
Features
- Zero Dependencies:
envfmt
is built with only the Rust standard library (plusthiserror
for convenience). - Familiar Syntax: Supports common shell variable expansion patterns.
- Simple variables:
$VAR
- Braced variables:
${VAR}
- Default values for unset variables:
${VAR:-default}
- Escaping:
$$
to get a literal$
- Simple variables:
- Flexible & Testable: Use the primary
envfmt::format()
for environment variables, orenvfmt::format_with()
with aHashMap
for easy testing and custom data sources. - Ergonomic: Works with
HashMap<String, _>
andHashMap<&str, _>
keys out of the box.
Getting Started
Add envfmt
to your project's dependencies:
Usage
This is the most common use case. First, ensure an environment variable is set in your shell:
export ETHERSCAN_API_KEY="key"
Then, use envfmt::format()
to expand it:
let key = format.unwrap;
assert_eq!;
If a variable might be missing, you can provide a fallback default value:
let log_config = "${LOG_LEVEL:-INFO}";
let log_level = format.unwrap;
assert_eq!;
For advance usage, or if your variables come from a source other than the
environment, use envfmt::format_with()
. This is fast, safe, and doesn't
require modifying the global environment.
let mut context = new;
context.insert;
let template = "Hello $user!";
let message = format_with?;
assert_eq!;
License
This project is licensed under the MIT License.