envsubst-rs icon indicating copy to clipboard operation
envsubst-rs copied to clipboard

substitute and count vars remaining

Open ratmice opened this issue 5 years ago • 2 comments

It might be nice if there was a function like: fn substitute_count_remaining_vars(template: T, variables: &HashMap<String, String>) -> Result<(String, usize), Error> which returned the number of variables not substituted, so you could perform something like: Presumably, it'd be nice to have a ValidatedVarMap<String, String> to avoid calling validate() in the loop?

With that you could still ensure that it terminates even though is_templated returns true. I don't really have a need for it at the moment, but is this something you would consider accepting a patch for?

    let mut foo = "${${foo}bar}".to_string();
    let mut variables_left = 0;
    let mut vars = HashMap::new();
    vars.insert("foo".to_string(), "bar".to_string());
    vars.insert("barbar".to_string(), "baz".to_string());
    loop {
        let (bar, n) = substitute_count_remaining_vars(foo.into(), &vars)?;
        if n < variables_left {
            variables_left = n;
            foo = bar;
            continue;
        }
        foo = bar;
        break;
    }

ratmice avatar Nov 03 '20 00:11 ratmice

(Sorry for the delay, I missed the original notification for this).

Not against adding more stuff here, but unless there is a clear usecase for those things I'd rather hold. The library is small and naïf on purpose.

And by the way, "${${foo}bar}" is a problematic template which we should probably detect and reject.

lucab avatar Mar 01 '21 11:03 lucab

I think it is okay in a template (Or at least I'm failing to see why it is problematic at least when vars doesn't change between substitutions), however it is definitely problematic a key, where IIRC vars.insert("${foo}bar"), IIRC is already rejected.

FWIW no worries about the delay, I'll see If I can come up with a sufficiently compelling use case, and if not we can close.

ratmice avatar Mar 01 '21 19:03 ratmice