Crate envfmt

Crate envfmt 

Source
Expand description

Formats strings by expanding variables, 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.

The main entry points are the format() and format_with() functions.

§Syntax

The formatting syntax is designed to be familiar to users of Unix shells.

  • $VAR Simple variables

    • A variable name starts with an alphabetic character or an underscore, followed by any number of alphanumeric characters or underscores.
    • The expansion is greedy, meaning it will match the longest possible valid variable name.
  • ${VAR} Braced variables

    • This syntax is useful for separating a variable name from subsequent characters.
  • ${VAR:-default} Default values

    • If VAR is not found in the context, the default value is used instead.
    • If VAR is present in the context, even if its value is an empty string, the default is not used. This matches standard shell behavior.
  • $$ Escaping

    • To include a literal dollar sign in the output, use $$.

§Examples

Using environment variables:

let formatted = envfmt::format("This package is $CARGO_PKG_NAME.").unwrap();
assert_eq!(formatted, "This package is envfmt.");

Using a custom context:

use std::collections::HashMap;

let mut context = HashMap::new();
context.insert("thing", "world");

let input = "Hello, ${thing}!";
let result = envfmt::format_with(input, &context).unwrap();

assert_eq!(result, "Hello, world!");

Enums§

Error
Represents errors that can occur during formatting.

Traits§

Context
A trait for providing values for variable expansion.

Functions§

format
Formats a string by expanding variables from the process environment.
format_with
Formats a string by expanding variables from a given context.