sarge 9.0.0

Zero-dependencies arguments parser.
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
#![doc = include_str!("../README.md")]
#![warn(clippy::pedantic)]
#![warn(missing_docs)]
#![allow(clippy::needless_pass_by_value)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::redundant_closure_for_method_calls)]
#![allow(clippy::float_cmp)]
#![allow(clippy::needless_doctest_main)]
#![allow(clippy::doc_markdown)]

pub mod prelude;

use std::env;
use std::marker::PhantomData;
use std::ops::Deref;

#[cfg(feature = "macros")]
pub mod macros;

pub mod tag;
use tag::Full;

mod error;
pub use error::ArgParseError;

#[cfg(feature = "help")]
mod help;
#[cfg(feature = "help")]
use help::DocParams;

mod types;
pub use types::{ArgResult, ArgumentType, DefaultedArgResult};

#[doc(hidden)]
pub trait __SargeDefault<T> {
    fn __sarge_default(self) -> T;
}

impl<T> __SargeDefault<T> for T {
    fn __sarge_default(self) -> T {
        self
    }
}

impl __SargeDefault<String> for &str {
    fn __sarge_default(self) -> String {
        self.to_string()
    }
}

#[doc(hidden)]
pub fn __sarge_default<T, D>(d: D) -> T
where
    D: __SargeDefault<T>,
{
    d.__sarge_default()
}

/// A helper trait for expression defaults in `sarge!`.
///
/// This is intentionally narrower than `__SargeDefault`: it avoids adding
/// `&str -> String` for all expressions, which can otherwise trigger type
/// inference ambiguity for defaults like `"foo".into()`.
#[doc(hidden)]
pub trait __SargeDefaultExpr<T> {
    fn __sarge_default_expr(self) -> T;
}

impl<T> __SargeDefaultExpr<T> for T {
    fn __sarge_default_expr(self) -> T {
        self
    }
}

impl __SargeDefaultExpr<Vec<String>> for Vec<&'_ str> {
    fn __sarge_default_expr(self) -> Vec<String> {
        self.into_iter().map(str::to_string).collect()
    }
}

#[doc(hidden)]
pub fn __sarge_default_expr<T>(d: impl __SargeDefaultExpr<T>) -> T {
    d.__sarge_default_expr()
}

#[cfg(test)]
mod test;

#[derive(Clone, Debug)]
#[allow(clippy::option_option)]
struct InternalArgument {
    tag: Full,
    consumes: bool,
    repeatable: bool,
    cli_set: bool,
    val: Option<Option<String>>,
}

/// The results of [`ArgumentReader::parse`]. Used both for retrieving
/// [`ArgumentRef`]s and for accessing the
/// [remainder](Arguments::remainder) of the input arguments.
///
/// `Arguments` implements `Deref<Target = [String]>`, so you can treat it
/// like a `&[String]`.
#[derive(Clone, Debug)]
pub struct Arguments {
    args: Vec<InternalArgument>,
    remainder: Vec<String>,
}

impl AsRef<[String]> for Arguments {
    fn as_ref(&self) -> &[String] {
        self.remainder.as_slice()
    }
}

// TODO: should there be AsRef AND Deref AND From?
impl Deref for Arguments {
    type Target = [String];

    fn deref(&self) -> &Self::Target {
        self.remainder.as_slice()
    }
}

impl From<Arguments> for Vec<String> {
    fn from(args: Arguments) -> Vec<String> {
        args.remainder
    }
}

impl Arguments {
    /// All the CLI arguments that didn't get parsed as part of an argument.
    ///
    /// `Arguments` implements `Deref<Target = [String]>`, so you can also just
    /// treat it like a `&[String]`. This is just to give you an explicit way
    /// to do so.
    pub fn remainder(&self) -> &[String] {
        self
    }

    pub(crate) fn get_arg(&self, i: usize) -> &InternalArgument {
        &self.args[i]
    }
}

/// An internal tag to an argument. Use this to retrieve the value of an
/// argument from an [`Arguments`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ArgumentRef<T: ArgumentType> {
    i: usize,
    _marker: PhantomData<fn() -> T>,
}

impl<T: ArgumentType> ArgumentRef<T> {
    /// Retrieve the value of the argument from an [`Arguments`].
    ///
    /// # Errors
    ///
    /// If the argument type fails to parse,
    /// this will return that argument types error.
    /// If there was no value given to the argument,
    /// returns `None`.
    ///
    /// For `String` and `bool`, this can never fail.
    pub fn get(&self, args: &Arguments) -> ArgResult<T> {
        if let Some(val) = &args.get_arg(self.i).val {
            T::from_value(val.as_deref())
        } else {
            T::default_value().map(Ok)
        }
    }

    /// Retrieve the value of the argument from an [`Arguments`] without applying
    /// the type's [`ArgumentType::default_value`].
    ///
    /// This is primarily useful for macro expansions that want wrapper semantics
    /// (`#ok`/`#err`) and macro-provided defaults to take precedence.
    #[doc(hidden)]
    pub fn get_raw(&self, args: &Arguments) -> ArgResult<T> {
        if let Some(val) = &args.get_arg(self.i).val {
            T::from_value(val.as_deref())
        } else {
            None
        }
    }

    /// Retrieve the tag of the argument from an [`Arguments`].
    ///
    /// Note that this always returns a [`Full`] tag, even when the argument
    /// wasn't created with one.
    pub fn tag<'a>(&self, args: &'a Arguments) -> &'a Full {
        &args.get_arg(self.i).tag
    }
}

/// The structure that actually reads all your arguments.
///
/// Use [`ArgumentReader::add`] to register arguments and get [`ArgumentRef`]s.
/// Then, use <code>[ArgumentReader::parse]{_cli,_env,_provided}</code> to get
/// [`Arguments`], which contains the results of parsing. Finally, you can use
/// [`ArgumentRef::get`] to retrieve the values of your arguments.
#[derive(Debug, Clone, Default)]
#[allow(clippy::doc_markdown)]
pub struct ArgumentReader {
    args: Vec<InternalArgument>,

    /// Program-level documentation.
    ///
    /// Only available on feature `help`.
    pub doc: Option<String>,
}

impl ArgumentReader {
    /// Returns an empty [`ArgumentReader`].
    pub fn new() -> Self {
        Self {
            args: Vec::new(),
            doc: None,
        }
    }

    /// Returns help for all the arguments.
    ///
    /// Only available on feature `help`.
    ///
    /// # Panics
    ///
    /// If the name of the executable could not be found, panics.
    #[cfg(feature = "help")]
    pub fn help(&self) -> String {
        let exe = option_env!("CARGO_BIN_NAME")
            .map(String::from)
            .or_else(|| {
                std::env::current_exe()
                    .ok()
                    .and_then(|s| s.file_stem().map(|s| s.to_string_lossy().into_owned()))
            })
            .expect("failed to get executable");

        let mut out = String::new();
        out.push_str(&exe);
        out.push_str(" [options...] <arguments...>\n");

        if let Some(doc) = &self.doc {
            out.push_str(doc);
            out.push_str("\n\n");
        }

        let mut params = DocParams::default();
        for arg in &self.args {
            help::update_params(&mut params, &arg.tag);
        }

        for arg in &self.args {
            out.push_str(&help::render_argument(&arg.tag, params));
            out.push('\n');
        }

        out
    }

    /// Prints help for all the arguments.
    ///
    /// Only available on feature `help`.
    ///
    /// # Panics
    ///
    /// If the name of the executable could not be found, panics.
    #[cfg(feature = "help")]
    pub fn print_help(&self) {
        print!("{}", self.help());
    }

    /// Adds an argument to the parser.
    pub fn add<T: ArgumentType>(&mut self, tag: Full) -> ArgumentRef<T> {
        let arg = InternalArgument {
            tag,
            consumes: T::CONSUMES,
            repeatable: T::REPEATABLE,
            cli_set: false,
            val: None,
        };

        let i = self.args.len();
        self.args.push(arg);

        ArgumentRef {
            i,
            _marker: PhantomData,
        }
    }

    /// Parse arguments from `std::env::{args,vars}`.
    ///
    /// # Errors
    ///
    /// If any arguments fail to parse their values, this
    /// will forward that error. Otherwise, see
    /// [`ArgParseError`] for a list of all possible errors.
    pub fn parse(self) -> Result<Arguments, ArgParseError> {
        self.parse_provided(env::args(), env::vars())
    }

    /// Parse from the provided environment variables and CLI arguments.
    ///
    /// # Errors
    ///
    /// If any arguments fail to parse their values, this
    /// will forward that error. Otherwise, see
    /// [`ArgParseError`] for a list of all possible errors.
    pub fn parse_provided<
        A: AsRef<str>,
        IA: IntoIterator<Item = A>,
        K: AsRef<str>,
        V: AsRef<str>,
        IE: IntoIterator<Item = (K, V)>,
    >(
        mut self,
        cli: IA,
        env: IE,
    ) -> Result<Arguments, ArgParseError> {
        self.parse_env(env);
        self.parse_cli(cli)
    }

    /// Parse the provided arguments as environment variables.
    fn parse_env<K: AsRef<str>, V: AsRef<str>, I: IntoIterator<Item = (K, V)>>(&mut self, args: I) {
        let mut env_args: Vec<_> = self
            .args
            .iter_mut()
            .filter(|arg| arg.tag.has_env())
            .collect();

        if !env_args.is_empty() {
            for (key, val) in args {
                let key_ref = key.as_ref();
                let val = val.as_ref();
                if let Some(arg) = env_args
                    .iter_mut()
                    .find(|arg| arg.tag.env.as_ref().is_some_and(|env| env == key_ref))
                {
                    arg.val = Some(Some(val.to_string()));
                }
            }
        }
    }

    /// Parses the provided arguments as if they were from the CLI.
    ///
    /// If `reset == true`, clears the values of all arguments beforehand.
    /// You probably want to leave this at `false`, unless you're re-using
    /// your parser.
    ///
    /// # Errors
    ///
    /// See [`parse`](ArgumentReader::parse) for details.
    fn parse_cli<A: AsRef<str>, IA: IntoIterator<Item = A>>(
        mut self,
        args: IA,
    ) -> Result<Arguments, ArgParseError> {
        fn tostring<S: AsRef<str>>(arg: S) -> String {
            <S as AsRef<str>>::as_ref(&arg).to_string()
        }

        let mut args = args.into_iter().peekable();
        let mut remainder = Vec::new();

        while let Some(arg) = args.next() {
            let arg = arg.as_ref();
            if let Some(mut long) = arg.strip_prefix("--") {
                let val = if let Some((left, right)) = long.split_once('=') {
                    long = left;
                    Some(right)
                } else {
                    None
                };

                let arg = self
                    .args
                    .iter_mut()
                    .find(|arg| arg.tag.matches_long(long))
                    .ok_or(ArgParseError::UnknownFlag(long.to_string()))?;

                if !arg.cli_set {
                    arg.val = None;
                    arg.cli_set = true;
                }

                let val = if arg.consumes {
                    if val.is_none() {
                        args.next().map(tostring)
                    } else {
                        val.map(tostring)
                    }
                } else {
                    None
                };

                if arg.repeatable {
                    if let Some(val) = val {
                        match &mut arg.val {
                            Some(Some(existing)) => {
                                existing.push(',');
                                existing.push_str(&val);
                            }
                            _ => {
                                arg.val = Some(Some(val));
                            }
                        }
                    }
                } else {
                    arg.val = Some(val);
                }
            } else if let Some(shorts) = arg.strip_prefix('-') {
                if shorts.is_empty() {
                    remainder.push(String::from("-"));
                } else {
                    let mut consumed = false;
                    for short in shorts.chars() {
                        let arg = self
                            .args
                            .iter_mut()
                            .find(|arg| arg.tag.matches_short(short))
                            .ok_or(ArgParseError::UnknownFlag(short.to_string()))?;

                        if arg.consumes && consumed {
                            return Err(ArgParseError::ConsumedValue(shorts.to_string()));
                        }

                        let next = if arg.consumes {
                            consumed = true;
                            args.next().map(|arg| arg.as_ref().to_string())
                        } else {
                            None
                        };

                        if !arg.cli_set {
                            arg.val = None;
                            arg.cli_set = true;
                        }

                        if arg.repeatable {
                            if let Some(next) = next {
                                match &mut arg.val {
                                    Some(Some(existing)) => {
                                        existing.push(',');
                                        existing.push_str(&next);
                                    }
                                    _ => {
                                        arg.val = Some(Some(next));
                                    }
                                }
                            }
                        } else {
                            arg.val = Some(next);
                        }
                    }
                }
            } else {
                remainder.push(arg.to_string());
            }
        }

        Ok(Arguments {
            args: self.args,
            remainder,
        })
    }
}