aopt 1.4.3

A flexible and typed getopt tools
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
use std::any::TypeId;

use crate::error;
use crate::opt::Action;
#[allow(unused)]
use crate::opt::Cmd;
#[allow(unused)]
use crate::opt::Creator;
use crate::opt::Help;
use crate::opt::Index;
#[allow(unused)]
use crate::opt::Main;
use crate::opt::Opt;
#[allow(unused)]
use crate::opt::Pos;
use crate::opt::Style;
use crate::value::ErasedValue;
use crate::value::ValAccessor;
use crate::Error;
use crate::Uid;

use super::ConfigValue;
use super::OptConfig;

/// A multiple features option type.
///
/// Some types support by default, they all implement [`Infer`](crate::value::Infer).
/// When create the option with `creator` using [`add_opt`](crate::set::OptSet::add_opt), the [`Creator`] will retrieve
/// other informations from the `infer type` list on the table.
/// When create the option from type using [`infer`](crate::opt::ConfigBuildInfer::infer), the [`Creator`] will retrieve
/// other informations from given type.
///
/// | type | action | ignore name | styles | index | alias | default value | creator | infer type |
/// |   -- |    --  |    -        |    --  |   -   |   -   |   --          |  -      |    --      |
/// | [`bool`] | [`Action::Set`] | `false` | [`Style::Combined`] [`Style::Boolean`] | no   | true | false | `b` | [`bool`] |
/// | [`i32`] | [`Action::App`] | `false` | [`Style::Argument`] | no | true | None | None | None |
/// | [`i64`] | [`Action::App`] | `false` | [`Style::Argument`] | no | true | None | `i`  | [`i64`] |
/// | [`u32`] | [`Action::App`] | `false` | [`Style::Argument`] | no | true | None | None | None |
/// | [`u64`] | [`Action::App`] | `false` | [`Style::Argument`] | no | true | None | `u`  | [`u64`] |
/// | [`f32`] | [`Action::App`] | `false` | [`Style::Argument`] | no | true | None | None | None |
/// | [`f64`] | [`Action::App`] | `false` | [`Style::Argument`] | no | true | None | `f`  | [`f64`] |
/// | [`usize`] | [`Action::App`] | `false` | [`Style::Argument`] | no | true | None | None | None |
/// | [`isize`] | [`Action::App`] | `false` | [`Style::Argument`] | no | true | None | None | None |
/// | [`String`]| [`Action::App`] | `false` | [`Style::Argument`] | no | true | None | `s`  | [`String`] |
/// | [`OsString`](std::ffi::OsString) | [`Action::App`] | `false` | [`Style::Argument`] | no | true | None | `r` | [`OsString`](std::ffi::OsString) |
/// | [`Cmd`] | [`Action::Set`] | `false` | [`Style::Cmd`] | [`Forward(1)`](Index::Forward)  | true  |false | `c` | [`Cmd`] |
/// | [`Pos`] | [`Action::App`] | `true` | [`Style::Pos`] | yes | false | None | `p` | [`Pos`] |
/// | [`Main`] | [`Action::Null`] | `true` | [`Style::Main`] | [`AnyWhere`](Index::AnyWhere) | false | None | `m` | [`Main`] |
/// | [`Stdin`](std::io::Stdin) | [`Action::Set`] | [`false`] | [`Style::Boolean`] | None | true | None | None | [`Stdin`](std::io::Stdin) |
/// | [`Stop`](crate::value::Stop) | [`Action::Set`] | [`false`] | [`Style::Boolean`] | None |  true | None | None | [`Stop`](crate::value::Stop) |
///
/// For the value parser support, see [`RawValParser`](crate::value::RawValParser).
#[derive(Debug)]
pub struct AOpt {
    uid: Uid,

    name: String,

    r#type: TypeId,

    help: Help,

    styles: Vec<Style>,

    index: Option<Index>,

    accessor: ValAccessor,

    alias: Option<Vec<String>>,

    action: Action,

    matched: bool,

    force: bool,

    ignore_name: bool,

    ignore_alias: bool,

    ignore_index: bool,
}

impl AOpt {
    pub fn new(name: String, type_id: TypeId, accessor: ValAccessor) -> Self {
        Self {
            uid: 0,
            name,
            r#type: type_id,
            help: Default::default(),
            matched: false,
            force: false,
            action: Default::default(),
            styles: vec![],
            index: None,
            accessor,
            alias: None,
            ignore_name: false,
            ignore_alias: false,
            ignore_index: false,
        }
    }

    /// Set the unique identifier of option.
    pub fn with_uid(mut self, uid: Uid) -> Self {
        self.uid = uid;
        self
    }

    /// Set the name of option.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Set the type of option, see [`Ctor`](crate::set::Ctor).
    pub fn with_type(mut self, r#type: TypeId) -> Self {
        self.r#type = r#type;
        self
    }

    /// If the option will matching the name.
    pub fn with_ignore_name(mut self, ignore_name: bool) -> Self {
        self.ignore_name = ignore_name;
        self
    }

    /// If the option will matching the alias.
    pub fn with_ignore_alias(mut self, ignore_alias: bool) -> Self {
        self.ignore_alias = ignore_alias;
        self
    }

    /// If the option will matching the alias.
    pub fn with_ignore_index(mut self, ignore_index: bool) -> Self {
        self.ignore_index = ignore_index;
        self
    }

    /// Set the hint of option, such as `--option`.
    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
        self.help.set_hint(hint);
        self
    }

    /// Set the help message of option.
    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        self.help.set_help(help);
        self
    }

    /// Set the value action of option.
    pub fn with_action(mut self, action: Action) -> Self {
        self.action = action;
        self
    }

    /// Set the help of option.
    pub fn with_opt_help(mut self, help: Help) -> Self {
        self.help = help;
        self
    }

    /// Set the [`Style`] of option.
    pub fn with_style(mut self, styles: Vec<Style>) -> Self {
        self.styles = styles;
        self
    }

    /// Set the NOA index of option.
    pub fn with_idx(mut self, index: Option<Index>) -> Self {
        self.index = index;
        self
    }

    /// If the option is force required.
    pub fn with_force(mut self, force: bool) -> Self {
        self.force = force;
        self
    }

    /// Set the alias of option.
    pub fn with_alias(mut self, alias: Option<Vec<String>>) -> Self {
        self.alias = alias;
        self
    }

    /// Set the value accessor of option, it will used by [`Policy`](crate::parser::Policy);
    pub fn with_accessor(mut self, value: ValAccessor) -> Self {
        self.accessor = value;
        self
    }
}

impl AOpt {
    pub fn set_name(&mut self, name: impl Into<String>) -> &mut Self {
        self.name = name.into();
        self
    }

    pub fn set_type(&mut self, r#type: TypeId) -> &mut Self {
        self.r#type = r#type;
        self
    }

    pub fn set_value(&mut self, value: ValAccessor) -> &mut Self {
        self.accessor = value;
        self
    }

    pub fn set_hint(&mut self, hint: impl Into<String>) -> &mut Self {
        self.help.set_hint(hint);
        self
    }

    pub fn set_help(&mut self, help: impl Into<String>) -> &mut Self {
        self.help.set_help(help);
        self
    }

    pub fn set_action(&mut self, action: Action) -> &mut Self {
        self.action = action;
        self
    }

    pub fn set_style(&mut self, styles: Vec<Style>) -> &mut Self {
        self.styles = styles;
        self
    }

    pub fn set_index(&mut self, index: Option<Index>) -> &mut Self {
        self.index = index;
        self
    }

    pub fn set_force(&mut self, force: bool) -> &mut Self {
        self.force = force;
        self
    }

    pub fn add_alias(&mut self, name: impl Into<String>) -> &mut Self {
        if let Some(alias) = &mut self.alias {
            alias.push(name.into());
        }
        self
    }

    pub fn rem_alias(&mut self, name: &str) -> &mut Self {
        if let Some(alias) = &mut self.alias {
            if let Some((i, _)) = alias.iter().enumerate().find(|(_, v)| v == &name) {
                alias.remove(i);
            }
        }
        self
    }

    pub fn set_ignore_name(&mut self, ignore_name: bool) -> &mut Self {
        self.ignore_name = ignore_name;
        self
    }

    pub fn set_ignore_alias(&mut self, ignore_alias: bool) -> &mut Self {
        self.ignore_alias = ignore_alias;
        self
    }

    pub fn set_ignore_index(&mut self, ignore_index: bool) -> &mut Self {
        self.ignore_index = ignore_index;
        self
    }
}

impl Opt for AOpt {
    fn reset(&mut self) {
        self.set_matched(false);
    }

    fn uid(&self) -> Uid {
        self.uid
    }

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

    fn r#type(&self) -> &TypeId {
        &self.r#type
    }

    fn hint(&self) -> &str {
        self.help.hint()
    }

    fn help(&self) -> &str {
        self.help.help()
    }

    fn valid(&self) -> bool {
        !self.force() || self.matched()
    }

    fn matched(&self) -> bool {
        self.matched
    }

    fn force(&self) -> bool {
        self.force
    }

    fn action(&self) -> &Action {
        &self.action
    }

    fn index(&self) -> Option<&Index> {
        self.index.as_ref()
    }

    fn alias(&self) -> Option<&Vec<String>> {
        self.alias.as_ref()
    }

    fn accessor(&self) -> &ValAccessor {
        &self.accessor
    }

    fn accessor_mut(&mut self) -> &mut ValAccessor {
        &mut self.accessor
    }

    fn ignore_alias(&self) -> bool {
        self.ignore_alias
    }

    fn ignore_name(&self) -> bool {
        self.ignore_name
    }

    fn ignore_index(&self) -> bool {
        self.ignore_index
    }

    fn set_uid(&mut self, uid: Uid) {
        self.uid = uid;
    }

    fn set_matched(&mut self, matched: bool) {
        self.matched = matched;
    }

    fn mat_style(&self, style: Style) -> bool {
        self.styles.iter().any(|v| v == &style)
    }

    fn mat_force(&self, force: bool) -> bool {
        self.force() == force
    }

    fn mat_name(&self, name: Option<&str>) -> bool {
        name == Some(self.name())
    }

    fn mat_alias(&self, name: &str) -> bool {
        if let Some(alias) = &self.alias {
            alias.iter().any(|v| v == name)
        } else {
            false
        }
    }

    fn mat_index(&self, index: Option<(usize, usize)>) -> bool {
        if let Some((index, total)) = index {
            if let Some(realindex) = self.index() {
                if let Some(realindex) = realindex.calc_index(index, total) {
                    return realindex == index;
                }
            }
        }
        false
    }

    fn init(&mut self) -> Result<(), Error> {
        self.accessor.initialize()
    }

    fn set_name(&mut self, name: impl Into<String>) -> &mut Self {
        self.name = name.into();
        self
    }

    fn set_type(&mut self, r#type: TypeId) -> &mut Self {
        self.r#type = r#type;
        self
    }

    fn set_value(&mut self, value: ValAccessor) -> &mut Self {
        self.accessor = value;
        self
    }

    fn set_hint(&mut self, hint: impl Into<String>) -> &mut Self {
        self.help.set_hint(hint);
        self
    }

    fn set_help(&mut self, help: impl Into<String>) -> &mut Self {
        self.help.set_help(help);
        self
    }

    fn set_action(&mut self, action: Action) -> &mut Self {
        self.action = action;
        self
    }

    fn set_style(&mut self, styles: Vec<Style>) -> &mut Self {
        self.styles = styles;
        self
    }

    fn set_index(&mut self, index: Option<Index>) -> &mut Self {
        self.index = index;
        self
    }

    fn set_force(&mut self, force: bool) -> &mut Self {
        self.force = force;
        self
    }

    fn add_alias(&mut self, name: impl Into<String>) -> &mut Self {
        if let Some(alias) = &mut self.alias {
            alias.push(name.into());
        }
        self
    }

    fn rem_alias(&mut self, name: &str) -> &mut Self {
        if let Some(alias) = &mut self.alias {
            if let Some((i, _)) = alias.iter().enumerate().find(|(_, v)| v == &name) {
                alias.remove(i);
            }
        }
        self
    }

    fn set_ignore_name(&mut self, ignore_name: bool) -> &mut Self {
        self.ignore_name = ignore_name;
        self
    }

    fn set_ignore_alias(&mut self, ignore_alias: bool) -> &mut Self {
        self.ignore_alias = ignore_alias;
        self
    }

    fn set_ignore_index(&mut self, ignore_index: bool) -> &mut Self {
        self.ignore_index = ignore_index;
        self
    }
}

fn gen_hint(
    hint: Option<impl Into<String>>,
    n: &str,
    idx: Option<&Index>,
    alias: Option<&Vec<String>>,
) -> String {
    let hint_generator = || {
        let mut names = Vec::with_capacity(1 + alias.map(|v| v.len()).unwrap_or_default());

        // add name
        names.push(n);
        // add alias
        if let Some(alias_vec) = alias {
            for alias in alias_vec {
                names.push(alias.as_str());
            }
        }
        // sort name by len
        names.sort_by_key(|v| v.len());
        if let Some(index) = idx {
            let index_string = index.to_help();

            // add index string
            if index_string.is_empty() {
                names.join(", ")
            } else {
                format!("{}@{}", names.join(", "), index_string)
            }
        } else {
            names.join(", ")
        }
    };

    hint.map(|v| v.into()).unwrap_or_else(hint_generator)
}

impl TryFrom<OptConfig> for AOpt {
    type Error = Error;

    fn try_from(mut value: OptConfig) -> Result<Self, Self::Error> {
        let r#type = value.take_type();
        let name = value.take_name();
        let force = value.take_force();
        let index = value.take_index();
        let alias = value.take_alias();
        let hint = value.take_hint();
        let help = value.take_help();
        let action = value.take_action();
        let storer = value.take_storer();
        let styles = value.take_style();
        let initializer = value.take_initializer();
        let ignore_name = value.ignore_name();
        let ignore_alias = value.ignore_alias();
        let ignore_index = value.ignore_index();

        let force = force.unwrap_or(false);
        let action = action.unwrap_or(Action::App);
        let storer = storer.ok_or_else(|| error!("incomplete configuration: missing ValStorer"))?;
        let initializer = initializer
            .ok_or_else(|| error!("incomplete configuration: missing ValInitializer"))?;
        let styles = styles.ok_or_else(|| error!("incomplete configuration: missing Style"))?;
        let name = name.ok_or_else(|| error!("incomplete configuration: missing option name"))?;
        let hint = gen_hint(hint.as_ref(), &name, index.as_ref(), alias.as_ref());
        let help = help.unwrap_or_default();
        let r#type =
            r#type.ok_or_else(|| error!("incomplete configuration: missing option value type"))?;
        let help = Help::default().with_help(help).with_hint(hint);

        if ignore_alias {
            if let Some(alias) = &alias {
                debug_assert!(
                    !alias.is_empty(),
                    "option {} not support alias: {:?}",
                    name,
                    alias
                );
            }
        }
        if ignore_index {
            if let Some(index) = &index {
                debug_assert!(
                    !index.is_null(),
                    "please remove the index, option `{}` not support positional parameters: {:?}",
                    name,
                    index
                );
            }
        } else {
            debug_assert!(
                    index.is_some(),
                    "please provide an index, indicate the position you want to capture for option `{}`.",
                    name
                );
        }
        Ok(
            AOpt::new(name, r#type, ValAccessor::new(storer, initializer))
                .with_force(force)
                .with_idx(index)
                .with_action(action)
                .with_alias(alias)
                .with_style(styles)
                .with_opt_help(help)
                .with_ignore_name(ignore_name)
                .with_ignore_alias(ignore_alias)
                .with_ignore_index(ignore_index),
        )
    }
}