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
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
#[cfg(feature = "serde")]
use serde::de::{Deserialize, Deserializer, Visitor};
use std::borrow::Cow;
use std::str::CharIndices;

/// A command parsed into arguments that might be borrowed from the source.
#[derive(Debug, PartialEq, Eq)]
pub struct Cmd<S = String> {
    /// The path of the command to be executed.
    pub path: S,
    /// Optional arguments to the command.
    pub args: Vec<S>,
}

/// A variant of the command that borrows the data and does no copying
/// unless necessary.
pub type CmdBorrowed<'a> = Cmd<Cow<'a, str>>;

/// Iterator over arguments of the command.
pub struct ArgIter<'a> {
    source: &'a str,
    chars: CharIndices<'a>,
}

impl<'a> ArgIter<'a> {
    /// Construct a new argument iterator from the source.
    pub fn new(source: &'a str) -> Self {
        ArgIter {
            source,
            chars: source.char_indices(),
        }
    }
}

impl<'a> Iterator for ArgIter<'a> {
    type Item = Cow<'a, str>;

    fn next(&mut self) -> Option<Self::Item> {
        #[derive(Clone, Copy)]
        enum State {
            None,
            Quote(char),
        }

        let mut previous;
        let mut initial;
        let mut owned: Option<String> = None;
        loop {
            let (i, ch) = self.chars.next()?;
            if !ch.is_whitespace() {
                previous = ch;
                initial = i;
                break;
            }
        }
        let mut last = self.source.len();

        let mut state = match previous {
            '"' | '\'' => {
                initial += 1;
                State::Quote(previous)
            }
            '\\' => {
                initial += 1;
                State::None
            }
            _ => State::None,
        };
        let initial_state = state;
        let mut state_changes = 0;
        let mut found_whitespace = false;

        for (l, c) in self.chars.by_ref() {
            last = l;

            if (c == '"' || c == '\'') && previous != '\\' {
                match state {
                    State::None => {
                        state_changes += 1;
                        state = State::Quote(c)
                    }
                    State::Quote(q) if c == q => {
                        state_changes += 1;
                        state = State::None
                    }
                    _ => {}
                }
            } else if let State::None = state {
                if c.is_whitespace() {
                    found_whitespace = true;
                    break;
                }
            }

            if c != '\\' || previous == '\\' {
                if let Some(ref mut arg) = owned {
                    arg.push(c);
                }
            }

            if c == '\\' && owned.is_none() {
                owned = Some(self.source[initial..last].to_string());
            }
            previous = c;
        }

        if !found_whitespace && owned.is_none() {
            last = self.source.len();
        };

        match initial_state {
            State::Quote(_) if state_changes == 1 => {
                if let Some(ref mut arg) = owned {
                    arg.pop();
                } else {
                    last -= 1;
                }
            }
            _ => {}
        };

        owned
            .map(|s| s.into())
            .or_else(|| self.source.get(initial..last).map(|s| s.into()))
    }
}

#[cfg(feature = "serde")]
impl<'de: 'a, 'a> Deserialize<'de> for Cmd<Cow<'a, str>> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct CommandVisitor;

        impl<'de> Visitor<'de> for CommandVisitor {
            type Value = Cmd<Cow<'de, str>>;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(formatter, "a command string")
            }

            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E> {
                let mut iter = ArgIter::new(v);
                let path = iter.next().unwrap_or(Cow::Borrowed(""));
                let args = iter.collect();
                Ok(Cmd { path, args })
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> {
                let mut iter = ArgIter::new(v).map(|s| Cow::Owned(s.to_string()));
                let path = iter.next().unwrap_or_else(|| "".into());
                let args = iter.collect();
                Ok(Cmd { path, args })
            }
        }

        deserializer.deserialize_string(CommandVisitor)
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Cmd {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct CommandVisitor;

        impl<'de> Visitor<'de> for CommandVisitor {
            type Value = Cmd;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(formatter, "a command string")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> {
                let mut iter = ArgIter::new(v).map(|s| s.to_string());
                let path = iter.next().unwrap_or_else(|| "".into());
                let args = iter.collect();
                Ok(Cmd { path, args })
            }
        }

        deserializer.deserialize_string(CommandVisitor)
    }
}

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

    #[test]
    fn test_argiter() {
        let source = "echo h \"hello\\\" world\" \"\" \"h\\\"\"";
        let args: Vec<Cow<str>> = ArgIter::new(source).collect();
        assert_eq!(args, &["echo", "h", "hello\" world", "", "h\""]);
    }

    #[test]
    fn test_deserialize() {
        #[derive(Debug, PartialEq, Eq, serde_derive::Deserialize)]
        pub struct Simple<'a> {
            #[serde(borrow)]
            owned: CmdBorrowed<'a>,
            #[serde(borrow)]
            borrowed: CmdBorrowed<'a>,
        }

        let cmd = toml::de::from_str::<Simple>(include_str!("test.toml")).unwrap();

        assert_eq!(
            cmd,
            Simple {
                owned: Cmd {
                    path: "echo".into(),
                    args: vec!["hello world".into()],
                },
                borrowed: Cmd {
                    path: "rm".into(),
                    args: vec!["-rf".into()],
                }
            }
        );
        assert!(matches!(cmd.borrowed.path, Cow::Borrowed(_)));
    }
}