Skip to main content

expand_variables

Function expand_variables 

Source
pub fn expand_variables<P, I, S>(path: P, vars: I) -> PathBuf
where P: AsRef<Path>, I: IntoIterator<Item = (S, S)>, S: AsRef<str>,
Expand description

Expands shell-style variables in a path string.

This function takes a path containing variables in $VAR or ${VAR} syntax and substitutes them with values from the provided iterator of key-value pairs. Any variables not found in the provided mappings are left unchanged.

§Generic Parameters

  • P - A type that can be converted to a Path
  • I - An iterator-like type that produces (S, S) tuples
  • S - A type that can be read as &str

§Arguments

  • path - The path string or Path object containing variables
  • vars - An iterator of (key, value) pairs for variable substitution

§Returns

A PathBuf with all variables substituted with their corresponding values.

§Examples

use std::collections::HashMap;

let mut vars = HashMap::new();
vars.insert("USER", "john");
vars.insert("PROJECT", "rust");

let expanded = expand_variables("/home/$USER/$PROJECT", vars);
assert_eq!(expanded.to_string_lossy(), "/home/john/rust");

With a vector:

let vars = vec![("USER", "john"), ("PROJECT", "rust")];
let expanded = expand_variables("/home/$USER/${PROJECT}", vars);
assert_eq!(expanded.to_string_lossy(), "/home/john/rust");