envfmt 1.0.0

Expands environment variables in string
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Formats strings by expanding variables, similar to shell expansion.
//!
//! This crate provides a simple and efficient way to substitute variables in a
//! string, using either the process environment or a custom context like a
//! `HashMap`.
//!
//! The main entry points are the [`format()`] and [`format_with()`] functions.
//!
//! ## Docs
//!
//! - [Overview](https://pyk.sh/envfmt)
//! - [Getting Started](https://pyk.sh/envfmt/getting-started)
//! - [Use HashMap as Data Source](https://pyk.sh/envfmt/guides/use-hashmap)
//! - [Provide Default Values](https://pyk.sh/envfmt/guides/default-values)
//! - [Escape a Dollar Sign](https://pyk.sh/envfmt/guides/escape-dollar-sign)
//! - [Implement the Context Trait](https://pyk.sh/envfmt/guides/context-trait)
//!
//! ## Examples
//!
//! Using environment variables:
//!
//! ```rust
//! let formatted = envfmt::format("This package is $CARGO_PKG_NAME.").unwrap();
//! assert_eq!(formatted, "This package is envfmt.");
//! ```
//!
//! Using a custom context:
//!
//! ```
//! use std::collections::HashMap;
//!
//! let mut context = HashMap::new();
//! context.insert("thing", "world");
//!
//! let input = "Hello, ${thing}!";
//! let result = envfmt::format_with(input, &context).unwrap();
//!
//! assert_eq!(result, "Hello, world!");
//! ```

use std::{
    borrow::Borrow,
    collections::HashMap,
    env,
    fmt,
    hash::Hash,
    iter::Peekable,
};

/// Represents errors that can occur during formatting.
#[derive(Debug, PartialEq)]
pub enum Error {
    /// A required variable was not found in the context.
    VariableNotFound(String),

    /// A variable name was invalid, e.g `${}`.
    InvalidVariableName(String),

    /// The input string have an unclosed brace.
    UnclosedBrace,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::VariableNotFound(var) => {
                write!(f, "variable not found: '{}'", var)
            }
            Error::InvalidVariableName(var) => {
                write!(f, "invalid variable name: '{}'", var)
            }
            Error::UnclosedBrace => {
                write!(f, "unexpected end of input: missing closing brace '}}'")
            }
        }
    }
}

impl std::error::Error for Error {}

/// A trait for providing values for variable expansion.
///
/// This allows [`format_with`] to be generic over the source of the
/// variables, making it easy to test with a `HashMap` or use with environment
/// variables.
pub trait Context {
    /// Retrieves a value for a given key.
    ///
    /// # Parameters
    /// - `key`: The name of the variable to look up.
    ///
    /// # Returns
    /// - `Some(String)` if the key exists.
    /// - `None` if the key does not exist.
    fn get(&self, key: &str) -> Option<String>;
}

impl<K, S> Context for HashMap<K, S>
where
    K: Borrow<str> + Eq + Hash,
    S: AsRef<str>,
{
    fn get(&self, key: &str) -> Option<String> {
        self.get(key).map(|s| s.as_ref().to_string())
    }
}

// A `Context` implementation that reads from the process environment variables.
struct Env;

impl Context for Env {
    fn get(&self, key: &str) -> Option<String> {
        env::var(key).ok()
    }
}

/// Formats a string by expanding variables from a given context.
///
/// This is the generic version of the formatting function, which accepts any
/// type that implements the [`Context`] trait as the source for variable
/// values.
///
/// # Parameters
/// - `input`: The string template to format.
/// - `context`: A reference to a context that provides variable values.
///
/// # Returns
/// - `Ok(String)` with the formatted string if successful.
/// - `Err(Error)` if a variable is not found or the syntax is invalid.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use envfmt::{format_with, Context, Error};
///
/// let mut context = HashMap::new();
/// context.insert("VAR", "value");
///
/// // Successful expansion
/// assert_eq!(format_with("Hello, $VAR", &context).unwrap(), "Hello, value");
///
/// // Variable not found
/// assert_eq!(
///     format_with("Hello, $MISSING", &context).unwrap_err(),
///     Error::VariableNotFound("MISSING".to_string())
/// );
/// ```
pub fn format_with<C: Context>(
    input: &str,
    context: &C,
) -> Result<String, Error> {
    let mut result = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '$' {
            if let Some(next_char) = chars.peek() {
                match next_char {
                    // Escaped dollar sign: $$
                    '$' => {
                        result.push('$');
                        chars.next();
                    }
                    // Braced variable: ${VAR} or ${VAR:-default}
                    '{' => {
                        chars.next(); // Consume the '{'
                        format_braced_var(&mut chars, &mut result, context)?;
                    }
                    // Simple variable: $VAR
                    _ if next_char.is_alphabetic() || *next_char == '_' => {
                        format_var(&mut chars, &mut result, context)?;
                    }
                    // Just a literal dollar sign
                    _ => result.push('$'),
                }
            } else {
                result.push('$');
            }
        } else {
            result.push(c);
        }
    }

    Ok(result)
}

// Expands $VAR
fn format_var<C: Context>(
    chars: &mut Peekable<impl Iterator<Item = char>>,
    result: &mut String,
    context: &C,
) -> Result<(), Error> {
    let mut var_name = String::new();
    while let Some(c) = chars.peek() {
        if c.is_alphanumeric() || *c == '_' {
            var_name.push(*c);
            chars.next();
        } else {
            break;
        }
    }

    if var_name.is_empty() {
        // This case should theoretically not be hit due to the entry condition,
        // but as a safeguard.
        return Err(Error::InvalidVariableName("".to_string()));
    }

    match context.get(&var_name) {
        Some(value) => result.push_str(&value),
        None => return Err(Error::VariableNotFound(var_name)),
    }

    Ok(())
}

// Expands ${VAR}
fn format_braced_var<C: Context>(
    chars: &mut Peekable<impl Iterator<Item = char>>,
    result: &mut String,
    context: &C,
) -> Result<(), Error> {
    let mut var_name = String::new();

    // Parse the variable name part
    while let Some(c) = chars.peek() {
        match c {
            '}' => {
                chars.next();
                if var_name.is_empty() {
                    return Err(Error::InvalidVariableName("".to_string()));
                }
                return match context.get(&var_name) {
                    Some(value) => {
                        result.push_str(&value);
                        Ok(())
                    }
                    None => Err(Error::VariableNotFound(var_name)),
                };
            }
            ':' => {
                chars.next();
                if chars.peek() == Some(&'-') {
                    chars.next();
                    return resolve_default_value(
                        chars, result, &var_name, context,
                    );
                } else {
                    var_name.push(':');
                }
            }
            _ => {
                var_name.push(*c);
                chars.next();
            }
        }
    }

    // If we exit the loop, it means we ran out of characters before finding '}'
    Err(Error::UnclosedBrace)
}

fn resolve_default_value<C: Context>(
    chars: &mut Peekable<impl Iterator<Item = char>>,
    result: &mut String,
    var_name: &str,
    context: &C,
) -> Result<(), Error> {
    if var_name.is_empty() {
        return Err(Error::InvalidVariableName("".to_string()));
    }

    // Check context for the variable first. If it exists, use its value.
    if let Some(value) = context.get(var_name) {
        let mut brace_level = 0;
        // We need to discard the default value part, so we consume until the
        // matching '}'
        for c in chars.by_ref() {
            match c {
                '{' => brace_level += 1,
                '}' => {
                    if brace_level == 0 {
                        result.push_str(&value);
                        return Ok(());
                    }
                    brace_level -= 1;
                }
                _ => {}
            }
        }
        return Err(Error::UnclosedBrace);
    }

    // If variable is not in context, use the default value.
    let mut default_value = String::new();
    let mut brace_level = 0;
    for c in chars.by_ref() {
        match c {
            '{' => {
                brace_level += 1;
                default_value.push(c);
            }
            '}' => {
                if brace_level == 0 {
                    result.push_str(&default_value);
                    return Ok(());
                }
                brace_level -= 1;
                default_value.push(c);
            }
            _ => default_value.push(c),
        }
    }
    Err(Error::UnclosedBrace)
}

/// Formats a string by expanding variables from the process environment.
///
/// This is a convenience wrapper around [`format_with`] that uses
/// `std::env::vars` as the context.
///
/// # Examples
///
/// ```
/// let formatted = envfmt::format("This package is $CARGO_PKG_NAME.").unwrap();
/// assert_eq!(formatted, "This package is envfmt.");
/// ```
pub fn format(input: &str) -> Result<String, Error> {
    format_with(input, &Env)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_context() -> HashMap<String, String> {
        let mut ctx = HashMap::new();
        ctx.insert("VAR1".to_string(), "value1".to_string());
        ctx.insert("VAR2".to_string(), "value2".to_string());
        ctx.insert("EMPTY".to_string(), "".to_string());
        ctx
    }

    #[test]
    fn no_vars() {
        let ctx = create_context();
        assert_eq!(format_with("hello world", &ctx).unwrap(), "hello world");
    }

    #[test]
    fn var_simple() {
        let ctx = create_context();
        assert_eq!(format_with("hello $VAR1", &ctx).unwrap(), "hello value1");
    }

    #[test]
    fn var_braced() {
        let ctx = create_context();
        assert_eq!(format_with("hello ${VAR1}", &ctx).unwrap(), "hello value1");
    }

    #[test]
    fn var_multiple() {
        let ctx = create_context();
        assert_eq!(format_with("$VAR1-$VAR2", &ctx).unwrap(), "value1-value2");
        assert_eq!(
            format_with("${VAR1}-${VAR2}", &ctx).unwrap(),
            "value1-value2"
        );
    }

    #[test]
    fn var_adjacent() {
        let ctx = create_context();
        assert_eq!(format_with("$VAR1$VAR2", &ctx).unwrap(), "value1value2");
        assert_eq!(
            format_with("${VAR1}${VAR2}", &ctx).unwrap(),
            "value1value2"
        );
    }

    #[test]
    fn var_not_found_simple() {
        let ctx = create_context();
        assert_eq!(
            format_with("$NOT_FOUND", &ctx).unwrap_err(),
            Error::VariableNotFound("NOT_FOUND".to_string())
        );
    }

    #[test]
    fn var_not_found_braced() {
        let ctx = create_context();
        assert_eq!(
            format_with("${NOT_FOUND}", &ctx).unwrap_err(),
            Error::VariableNotFound("NOT_FOUND".to_string())
        );
    }

    #[test]
    fn var_invalid() {
        let ctx = create_context();
        assert_eq!(
            format_with("test ${}", &ctx).unwrap_err(),
            Error::InvalidVariableName("".to_string())
        );
        assert_eq!(
            format_with("test ${:-default}", &ctx).unwrap_err(),
            Error::InvalidVariableName("".to_string())
        );
    }

    #[test]
    fn default_value() {
        let ctx = create_context();
        assert_eq!(
            format_with("val: ${UNSET:-default_val}", &ctx).unwrap(),
            "val: default_val"
        );
    }

    #[test]
    fn default_value_ignored() {
        let ctx = create_context();
        assert_eq!(
            format_with("val: ${VAR1:-default_val}", &ctx).unwrap(),
            "val: value1"
        );
    }

    #[test]
    fn default_value_empty_var() {
        // NOTE: Standard shell behavior is to use the empty value if set.
        let ctx = create_context();
        assert_eq!(
            format_with("val: ${EMPTY:-default_val}", &ctx).unwrap(),
            "val: "
        );
    }

    #[test]
    fn default_value_with_braces() {
        let ctx = create_context();
        let input = "${UNSET:-{key: value}}";
        let expected = "{key: value}";
        assert_eq!(format_with(input, &ctx).unwrap(), expected);
    }

    #[test]
    fn default_value_unset() {
        let ctx = create_context();
        assert_eq!(format_with("val: ${UNSET:-}", &ctx).unwrap(), "val: ");
    }

    #[test]
    fn dollar_escaped() {
        let ctx = create_context();
        assert_eq!(
            format_with("this is not a $VAR1, it is $$VAR1", &ctx).unwrap(),
            "this is not a value1, it is $VAR1"
        );
        assert_eq!(format_with("$$", &ctx).unwrap(), "$");
    }

    #[test]
    fn dollar_suffix() {
        let ctx = create_context();
        assert_eq!(format_with("hello $", &ctx).unwrap(), "hello $");
    }

    #[test]
    fn dollar_with_space() {
        let ctx = create_context();
        assert_eq!(
            format_with("hello $ world", &ctx).unwrap(),
            "hello $ world"
        );
    }

    #[test]
    fn brace_unmatched() {
        let ctx = create_context();
        assert_eq!(
            format_with("test ${VAR1", &ctx).unwrap_err(),
            Error::UnclosedBrace
        );
        assert_eq!(
            format_with("test ${UNSET:-default", &ctx).unwrap_err(),
            Error::UnclosedBrace
        );
    }

    #[test]
    fn complex_string() {
        let ctx = create_context();
        let input = "path is $VAR1, version is ${VAR2:-1.0}, but not $UNDEFINED_VAR. Cost is $$50.";
        let expected_err = Error::VariableNotFound("UNDEFINED_VAR".to_string());
        assert_eq!(format_with(input, &ctx).unwrap_err(), expected_err);

        let input_with_default = "path is $VAR1, version is ${VAR2:-1.0}, maybe ${UNDEFINED_VAR:-fallback}. Cost is $$50.";
        let expected_str =
            "path is value1, version is value2, maybe fallback. Cost is $50.";
        assert_eq!(
            format_with(input_with_default, &ctx).unwrap(),
            expected_str
        );
    }
}