8 releases

0.3.0 Aug 31, 2023
0.2.3 Jul 26, 2023
0.2.2 Sep 19, 2022
0.1.2 Mar 3, 2022
0.0.1-reserved Feb 22, 2022

#24 in Template engine

Download history 13776/week @ 2023-12-14 13270/week @ 2023-12-21 11048/week @ 2023-12-28 13827/week @ 2024-01-04 14589/week @ 2024-01-11 16466/week @ 2024-01-18 17274/week @ 2024-01-25 14813/week @ 2024-02-01 8825/week @ 2024-02-08 11394/week @ 2024-02-15 14729/week @ 2024-02-22 17740/week @ 2024-02-29 15582/week @ 2024-03-07 17946/week @ 2024-03-14 16143/week @ 2024-03-21 14334/week @ 2024-03-28

66,787 downloads per month
Used in 10 crates (6 directly)

BSD-2-Clause OR Apache-2.0

43KB
936 lines

subst

Shell-like variable substitution for strings and byte strings.

Features

  • Perform substitution in &str or in &[u8].
  • Provide a custom map of variables or use environment variables.
  • Short format: "Hello $name!"
  • Long format: "Hello ${name}!"
  • Default values: "Hello ${name:person}!"
  • Recursive substitution in default values: "${XDG_CONFIG_HOME:$HOME/.config}/my-app/config.toml"
  • Perform substitution on all string values in YAML data (optional, requires the yaml feature).

Variable names can consist of alphanumeric characters and underscores. They are allowed to start with numbers.

Examples

The substitute() function can be used to perform substitution on a &str. The variables can either be a HashMap or a BTreeMap.

let mut variables = HashMap::new();
variables.insert("name", "world");
assert_eq!(subst::substitute("Hello $name!", &variables)?, "Hello world!");

The variables can also be taken directly from the environment with the Env map.

assert_eq!(
  subst::substitute("$XDG_CONFIG_HOME/my-app/config.toml", &subst::Env)?,
  "/home/user/.config/my-app/config.toml",
);

Substitution can also be done on byte strings using the substitute_bytes() function.

let mut variables = HashMap::new();
variables.insert("name", b"world");
assert_eq!(subst::substitute_bytes(b"Hello $name!", &variables)?, b"Hello world!");

Dependencies

~0.2–0.8MB
~15K SLoC