cliproc 2.1.1

A fast, low-level, and configurable command-line processor
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
use std::fmt::Debug;
use std::fmt::Display;
use std::marker::PhantomData;

/// An argument type that can be switched on/off.
pub struct Raisable {}

/// An argument type that can store a value.
pub struct Valuable {}

/// An argument type that can be invoked to take an action.
pub struct Callable {}

/// The typestate pattern for the different arguments that are possible on
/// the command-line.
pub trait ArgState {}

impl ArgState for Raisable {}
impl ArgState for Callable {}
impl ArgState for Valuable {}

/// A container for data provided on the command-line.
#[derive(PartialEq)]
pub struct Arg<S: ArgState> {
    data: ArgType,
    _marker: PhantomData<S>,
}

impl<S: ArgState> From<Arg<S>> for ArgType {
    fn from(value: Arg<S>) -> Self {
        value.data
    }
}

impl Arg<Raisable> {
    /// Create a new flag argument.
    pub fn flag<T: AsRef<str>>(name: T) -> Arg<Raisable> {
        Self {
            data: ArgType::Flag(Flag::new(name.as_ref().to_string())),
            _marker: PhantomData::<Raisable>,
        }
    }

    /// Specify the switch character that is also associated with this flag.
    pub fn switch(self, c: char) -> Self {
        Self {
            data: ArgType::Flag(self.data.into_flag().unwrap().switch(c)),
            _marker: PhantomData::<Raisable>,
        }
    }
}

impl Arg<Valuable> {
    /// Create a new option argument.
    pub fn option<T: AsRef<str>>(name: T) -> Arg<Valuable> {
        Self {
            data: ArgType::Optional(Optional::new(name)),
            _marker: PhantomData::<Valuable>,
        }
    }

    /// Create a new positional argument.
    pub fn positional<T: AsRef<str>>(name: T) -> Arg<Valuable> {
        Self {
            data: ArgType::Positional(Positional::new(name)),
            _marker: PhantomData::<Valuable>,
        }
    }

    /// Specify the name of the value that is associated with this argument.
    ///
    /// This function only modifies arguments that were created as options, and
    /// silently leaves any other arguments unmodified.
    pub fn value<T: AsRef<str>>(self, name: T) -> Self {
        Self {
            data: match self.data.is_option() {
                true => ArgType::Optional(self.data.into_option().unwrap().value(name)),
                false => self.data,
            },
            _marker: self._marker,
        }
    }

    /// Specify the switch character that is associated with this argument.
    ///
    /// This function only modifies arguments that were created as options, and
    /// silently leaves any other arguments unmodified.
    pub fn switch(self, c: char) -> Arg<Valuable> {
        Self {
            data: match self.data.is_option() {
                true => ArgType::Optional(self.data.into_option().unwrap().switch(c)),
                false => self.data,
            },
            _marker: self._marker,
        }
    }
}

impl Arg<Callable> {
    /// Create a new subcommand argument.
    pub fn subcommand<T: AsRef<str>>(name: T) -> Arg<Callable> {
        Self {
            data: ArgType::Positional(Positional::new(name)),
            _marker: PhantomData::<Callable>,
        }
    }
}

mod symbol {
    pub const FLAG: &str = "--";
    pub const POS_BRACKET_L: &str = "<";
    pub const POS_BRACKER_R: &str = ">";
}

#[derive(PartialEq)]
pub enum ArgType {
    Flag(Flag),
    Positional(Positional),
    Optional(Optional),
}

impl ArgType {
    pub fn as_flag(&self) -> Option<&Flag> {
        match self {
            ArgType::Flag(f) => Some(f),
            ArgType::Optional(o) => Some(o.get_flag()),
            ArgType::Positional(_) => None,
        }
    }

    pub fn as_option(&self) -> Option<&Optional> {
        match self {
            ArgType::Flag(_) => None,
            ArgType::Optional(o) => Some(o),
            ArgType::Positional(_) => None,
        }
    }

    fn is_option(&self) -> bool {
        match self {
            Self::Optional(_) => true,
            _ => false,
        }
    }

    pub fn into_option(self) -> Option<Optional> {
        match self {
            ArgType::Flag(_) => None,
            ArgType::Optional(o) => Some(o),
            ArgType::Positional(_) => None,
        }
    }

    pub fn into_flag(self) -> Option<Flag> {
        match self {
            ArgType::Flag(f) => Some(f),
            ArgType::Optional(_) => None,
            ArgType::Positional(_) => None,
        }
    }

    pub fn into_positional(self) -> Option<Positional> {
        match self {
            ArgType::Flag(_) => None,
            ArgType::Optional(_) => None,
            ArgType::Positional(p) => Some(p),
        }
    }
}

impl Display for ArgType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        match self {
            ArgType::Flag(a) => write!(f, "{}", a),
            ArgType::Positional(a) => write!(f, "{}", a),
            ArgType::Optional(a) => write!(f, "{}", a),
        }
    }
}

impl Debug for ArgType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "'{}'", self.to_string())
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct Positional {
    name: String,
}

impl Positional {
    pub fn new<T: AsRef<str>>(s: T) -> Self {
        Self {
            name: s.as_ref().to_string(),
        }
    }
}

impl Display for Positional {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(
            f,
            "{}{}{}",
            symbol::POS_BRACKET_L,
            self.name,
            symbol::POS_BRACKER_R
        )
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct Flag {
    name: String,
    switch: Option<char>,
}

impl Flag {
    pub fn new<T: AsRef<str>>(s: T) -> Self {
        Self {
            name: s.as_ref().to_string(),
            switch: None,
        }
    }

    pub fn switch(mut self, c: char) -> Self {
        self.switch = Some(c);
        self
    }

    pub fn get_name(&self) -> &str {
        self.name.as_ref()
    }

    pub fn get_switch(&self) -> Option<&char> {
        self.switch.as_ref()
    }
}

impl Display for Flag {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(f, "{}{}", symbol::FLAG, self.get_name())
    }
}

#[derive(Debug, PartialEq)]
pub struct Optional {
    option: Flag,
    value: Positional,
}

impl Optional {
    pub fn new<T: AsRef<str>>(s: T) -> Self {
        Self {
            option: Flag::new(s.as_ref()),
            value: Positional::new(s),
        }
    }

    pub fn value<T: AsRef<str>>(mut self, s: T) -> Self {
        self.value.name = s.as_ref().to_string();
        self
    }

    pub fn switch(mut self, c: char) -> Self {
        self.option.switch = Some(c);
        self
    }

    pub fn get_flag(&self) -> &Flag {
        &self.option
    }

    pub fn get_positional(&self) -> &Positional {
        &self.value
    }
}

impl Display for Optional {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(f, "{} {}", self.option, self.value)
    }
}

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

    #[test]
    fn positional_new() {
        let ip = Positional::new("ip");
        assert_eq!(
            ip,
            Positional {
                name: String::from("ip")
            }
        );

        let version = Positional::new("version");
        assert_eq!(
            version,
            Positional {
                name: String::from("version")
            }
        );
    }

    #[test]
    fn positional_disp() {
        let ip = Positional::new("ip");
        assert_eq!(ip.to_string(), "<ip>");

        let topic = Positional::new("topic");
        assert_eq!(topic.to_string(), "<topic>");
    }

    #[test]
    fn flag_new() {
        let help = Flag::new("help").switch('h');
        assert_eq!(
            help,
            Flag {
                name: String::from("help"),
                switch: Some('h'),
            }
        );
        assert_eq!(help.get_switch(), Some(&'h'));
        assert_eq!(help.get_name(), "help");

        let version = Flag::new("version");
        assert_eq!(
            version,
            Flag {
                name: String::from("version"),
                switch: None,
            }
        );
        assert_eq!(version.get_switch(), None);
        assert_eq!(version.get_name(), "version");
    }

    #[test]
    fn flag_disp() {
        let help = Flag::new("help");
        assert_eq!(help.to_string(), "--help");

        let version = Flag::new("version");
        assert_eq!(version.to_string(), "--version");
    }

    #[test]
    fn optional_new() {
        let code = Optional::new("code");
        assert_eq!(
            code,
            Optional {
                option: Flag::new("code"),
                value: Positional::new("code"),
            }
        );
        assert_eq!(code.get_flag().get_switch(), None);

        let version = Optional::new("color").value("rgb");
        assert_eq!(
            version,
            Optional {
                option: Flag::new("color"),
                value: Positional::new("rgb"),
            }
        );
        assert_eq!(version.get_flag().get_switch(), None);

        let version = Optional::new("color").value("rgb").switch('c');
        assert_eq!(
            version,
            Optional {
                option: Flag::new("color").switch('c'),
                value: Positional::new("rgb"),
            }
        );
        assert_eq!(version.get_flag().get_switch(), Some(&'c'));

        assert_eq!(version.get_positional(), &Positional::new("rgb"));
    }

    #[test]
    fn optional_disp() {
        let code = Optional::new("code");
        assert_eq!(code.to_string(), "--code <code>");

        let color = Optional::new("color").value("rgb");
        assert_eq!(color.to_string(), "--color <rgb>");

        let color = Optional::new("color").value("rgb").switch('c');
        assert_eq!(color.to_string(), "--color <rgb>");
    }

    #[test]
    fn arg_disp() {
        let command = ArgType::Positional(Positional::new("command"));
        assert_eq!(command.to_string(), "<command>");

        let help = ArgType::Flag(Flag::new("help"));
        assert_eq!(help.to_string(), "--help");

        assert_eq!(help.as_flag().unwrap().to_string(), "--help");

        let color = ArgType::Optional(Optional::new("color").value("rgb"));
        assert_eq!(color.to_string(), "--color <rgb>");

        assert_eq!(color.as_flag().unwrap().get_name(), "color");
    }

    #[test]
    fn arg_impossible_pos_as_flag() {
        let command = ArgType::Positional(Positional::new("command"));
        assert_eq!(command.as_flag(), None);
    }
}