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
use std::convert::From;
use std::error::Error;
use std::fmt::{Display, Error as FmtError, Write, Result as FmtResult};
use std::iter::Iterator;

#[cfg(test)]
mod tests;

#[derive(Debug)]
struct ExpandableStringSplit<'a> {
    src: &'a str,
    chars_iter: std::str::CharIndices<'a>,
    token_start: usize,
    reading_var: bool,
    done: bool,
}

fn split_expandable_string(s: &str) -> ExpandableStringSplit {
    ExpandableStringSplit {
        chars_iter: s.char_indices(),
        src: s,
        token_start: 0,
        reading_var: false,
        done: false,
    }
}

#[derive(Debug, PartialEq, Eq)]
enum ExpandableStrEntry<'a> {
    Substr(&'a str),
    Var(&'a str),
}

#[derive(Debug, PartialEq, Eq)]
pub enum ExpandableStrSplitError {
    /// Invalid input string (basically, non-closed variable name)
    InvalidFormat,

    /// Bad variable name; names should not contain space or equality sign
    InvalidVariableName,
}

impl Display for ExpandableStrSplitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> FmtResult {
        match self {
            ExpandableStrSplitError::InvalidFormat => write!(f, "Invalid format"),
            ExpandableStrSplitError::InvalidVariableName => write!(f, "Invalid variable name"),
        }
    }    
}

impl Error for ExpandableStrSplitError {}


type ExpandableStrSplitResult<'a> = Result<ExpandableStrEntry<'a>, ExpandableStrSplitError>;

impl<'a> Iterator for ExpandableStringSplit<'a> {
    type Item = ExpandableStrSplitResult<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        while let Some((n, c)) = self.chars_iter.next() {
            if c == '%' {
                let reading_var = self.reading_var;
                self.reading_var = !reading_var;
                if n > 0 {
                    let token_slice = &self.src[self.token_start..n];
                    self.token_start = n + 1;
                    if !token_slice.is_empty() {
                        if reading_var {
                            return Some(Ok(ExpandableStrEntry::Var(token_slice)));
                        } else {
                            return Some(Ok(ExpandableStrEntry::Substr(token_slice)));
                        }
                    }
                } else {
                    self.token_start = 1;
                }
            } else if self.reading_var {
                match c {
                    '=' | ' ' => {
                        self.done = true;
                        return Some(Err(ExpandableStrSplitError::InvalidVariableName));
                    }
                    _ => (),
                }
            }
        }

        self.done = true;

        if !self.reading_var {
            let token_slice = &self.src[self.token_start..];
            if !token_slice.is_empty() {
                self.token_start = self.src.len();
                Some(Ok(ExpandableStrEntry::Substr(token_slice)))
            } else {
                None
            }
        } else {
            Some(Err(ExpandableStrSplitError::InvalidFormat))
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum ExpandStringError<'a> {
    Splitting(ExpandableStrSplitError),
    /// Variable specified in source string is missing in provided context (or process environment)
    MissingVariable(&'a str),
    Formatting(FmtError),
}

impl Display for ExpandStringError<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> FmtResult {
        match self {
            ExpandStringError::Splitting(e) => write!(f, "Failed to split source string: {}", e),
            ExpandStringError::MissingVariable(v) => write!(f, "Variable required to expand source string is missing: {}", v),
            ExpandStringError::Formatting(e) => write!(f, "Invalid source string format: {}", e),
        }
    }
}

impl Error for ExpandStringError<'_> {}


impl<'a> From<ExpandableStrSplitError> for ExpandStringError<'a> {
    fn from(e: ExpandableStrSplitError) -> Self {
        Self::Splitting(e)
    }
}

impl<'a> From<FmtError> for ExpandStringError<'a> {
    fn from(e: FmtError) -> Self {
        Self::Formatting(e)
    }
}

pub fn expand_string_with_values<F, S>(s: &str, get_value: F) -> Result<String, ExpandStringError>
where
    F: Fn(&str) -> Option<S>,
    S: Display,
{
    let mut expanded_str = String::with_capacity(s.len());

    for entry in split_expandable_string(s) {
        match entry? {
            ExpandableStrEntry::Substr(s) => {
                expanded_str += s;
            }
            ExpandableStrEntry::Var(id) => {
                let val = get_value(id).ok_or(ExpandStringError::MissingVariable(id))?;
                write!(&mut expanded_str, "{}", val)?;
            }
        }
    }

    Ok(expanded_str)
}

#[cfg(feature = "env")]
pub fn expand_string_with_env(s: &str) -> Result<String, ExpandStringError> {
    fn get_var_value(key: &str) -> Option<String> {
        use std::ffi::{OsStr, OsString};

        std::env::var_os(key)
            .as_ref()
            .map(OsString::as_os_str)
            .map(OsStr::to_string_lossy)
            .map(Into::into)
    }

    expand_string_with_values(s, get_var_value)
}