6 releases

0.2.2 Sep 19, 2022
0.2.1 Sep 19, 2022
0.1.2 Mar 3, 2022
0.1.0 Feb 22, 2022
0.0.1-reserved Feb 22, 2022

#61 in Template engine

Download history 8/week @ 2022-12-01 27/week @ 2022-12-08 26/week @ 2022-12-15 187/week @ 2022-12-22 242/week @ 2022-12-29 299/week @ 2023-01-05 96/week @ 2023-01-12 118/week @ 2023-01-19 162/week @ 2023-01-26 281/week @ 2023-02-02 110/week @ 2023-02-09 293/week @ 2023-02-16 89/week @ 2023-02-23 114/week @ 2023-03-02 188/week @ 2023-03-09 209/week @ 2023-03-16

638 downloads per month
Used in clara-shell

BSD-2-Clause OR Apache-2.0

31KB
685 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

~170–560KB
~11K SLoC