Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for any type that implements display #28

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
#![allow(clippy::implicit_hasher)]

use std::collections::HashMap;
use std::fmt::Display;

/// Library errors.
#[derive(thiserror::Error, Debug)]
Expand All @@ -40,7 +41,10 @@ pub struct Error(String);
///
/// Given an input string `template`, replace tokens of the form `${foo}` with
/// values provided in `variables`.
pub fn substitute<T>(template: T, variables: &HashMap<String, String>) -> Result<String, Error>
pub fn substitute<T>(
template: T,
variables: &HashMap<String, impl Display>,
) -> Result<String, Error>
where
T: Into<String>,
{
Expand All @@ -50,11 +54,12 @@ where
}

for (k, v) in variables {
let s = format!("{}", v);
validate(k, "key")?;
validate(v, "value")?;
validate(&s, "value")?;

let from = format!("${{{}}}", k);
output = output.replace(&from, v)
output = output.replace(&from, &s)
}

Ok(output)
Expand Down Expand Up @@ -141,7 +146,7 @@ mod tests {
#[test]
fn basic_empty_vars() {
let template = "foo ${VAR} bar";
let env = HashMap::new();
let env = HashMap::<String, String>::new();

let out = substitute(template, &env).unwrap();
assert_eq!(out, template);
Expand All @@ -168,4 +173,21 @@ mod tests {
let mut env = HashMap::new();
env.insert("VAR".to_string(), "${VAR}".to_string());
}

#[test]
fn generic_hashmap() {
struct Item;
impl std::fmt::Display for Item {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "var")
}
}
let template = "foo ${VAR} bar";
let mut env = HashMap::new();
env.insert("VAR".to_string(), Item);

let out = substitute(template, &env).unwrap();
let expected = "foo var bar";
assert_eq!(out, expected);
}
}