nanoargs 0.6.0

A minimal, zero-dependency argument parser for Rust CLI applications
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
use crate::parser::ArgParser;
use crate::types::*;
use crate::validators::Validator;

/// Standalone builder for defining a boolean flag argument.
///
/// Construct with [`Flag::new()`], chain modifiers like [`.short()`](Flag::short)
/// and [`.hidden()`](Flag::hidden), then pass to [`ArgBuilder::flag()`].
#[derive(Clone, Debug)]
pub struct Flag {
    long: String,
    short: Option<char>,
    description: String,
    hidden: bool,
}

impl Flag {
    /// Create a new flag with a long name. Description defaults to empty string.
    pub fn new(long: &str) -> Self {
        Self {
            long: long.to_string(),
            short: None,
            description: String::new(),
            hidden: false,
        }
    }

    /// Set the description shown in help text.
    pub fn desc(mut self, description: &str) -> Self {
        self.description = description.to_string();
        self
    }

    /// Set the optional single-character short form.
    pub fn short(mut self, ch: char) -> Self {
        self.short = Some(ch);
        self
    }

    /// Mark this flag as hidden (excluded from help text).
    pub fn hidden(mut self) -> Self {
        self.hidden = true;
        self
    }
}

impl From<Flag> for FlagDef {
    fn from(f: Flag) -> FlagDef {
        FlagDef {
            long: f.long,
            short: f.short,
            description: f.description,
            hidden: f.hidden,
        }
    }
}

/// Standalone builder for defining a key-value option argument.
///
/// Construct with [`Opt::new()`], chain modifiers like [`.short()`](Opt::short),
/// [`.required()`](Opt::required), [`.default()`](Opt::default),
/// [`.env()`](Opt::env), [`.multi()`](Opt::multi), and [`.hidden()`](Opt::hidden),
/// then pass to [`ArgBuilder::option()`].
#[derive(Clone, Debug)]
pub struct Opt {
    long: String,
    short: Option<char>,
    placeholder: String,
    description: String,
    required: bool,
    default: Option<String>,
    env_var: Option<String>,
    multi: bool,
    hidden: bool,
    validator: Option<Validator>,
}

impl Opt {
    /// Create a new option with only the long name.
    /// Placeholder defaults to the uppercased long name; description defaults to empty.
    pub fn new(long: &str) -> Self {
        let placeholder = long.to_uppercase();
        Self {
            long: long.to_string(),
            short: None,
            placeholder,
            description: String::new(),
            required: false,
            default: None,
            env_var: None,
            multi: false,
            hidden: false,
            validator: None,
        }
    }

    /// Set the placeholder shown in help text (e.g. "FILE").
    pub fn placeholder(mut self, placeholder: &str) -> Self {
        self.placeholder = placeholder.to_string();
        self
    }

    /// Set the description shown in help text.
    pub fn desc(mut self, description: &str) -> Self {
        self.description = description.to_string();
        self
    }

    /// Set the optional single-character short form.
    pub fn short(mut self, ch: char) -> Self {
        self.short = Some(ch);
        self
    }

    /// Mark this option as required.
    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }

    /// Set a default value for this option.
    pub fn default(mut self, value: &str) -> Self {
        self.default = Some(value.to_string());
        self
    }

    /// Set an environment variable fallback for this option.
    pub fn env(mut self, var_name: &str) -> Self {
        self.env_var = Some(var_name.to_string());
        self
    }

    /// Mark this option as accepting multiple values.
    pub fn multi(mut self) -> Self {
        self.multi = true;
        self
    }

    /// Mark this option as hidden (excluded from help text).
    pub fn hidden(mut self) -> Self {
        self.hidden = true;
        self
    }

    /// Attach a validator to this option.
    pub fn validate(mut self, v: Validator) -> Self {
        self.validator = Some(v);
        self
    }
}

impl From<Opt> for OptionDef {
    fn from(o: Opt) -> OptionDef {
        OptionDef {
            long: o.long,
            short: o.short,
            placeholder: o.placeholder,
            description: o.description,
            required: o.required,
            default: o.default,
            env_var: o.env_var,
            multi: o.multi,
            hidden: o.hidden,
            validator: o.validator,
        }
    }
}

/// Standalone builder for defining a positional argument.
///
/// Construct with [`Pos::new()`], chain modifiers like [`.desc()`](Pos::desc),
/// [`.required()`](Pos::required), [`.default()`](Pos::default), and
/// [`.multi()`](Pos::multi), then pass to [`ArgBuilder::positional()`].
#[derive(Clone, Debug)]
pub struct Pos {
    name: String,
    description: String,
    required: bool,
    default: Option<String>,
    multi: bool,
    validator: Option<Validator>,
}

impl Pos {
    /// Create a new positional with a name and description.
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            description: String::new(),
            required: false,
            default: None,
            multi: false,
            validator: None,
        }
    }

    /// Set the description shown in help text.
    pub fn desc(mut self, description: &str) -> Self {
        self.description = description.to_string();
        self
    }

    /// Mark this positional as required.
    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }

    /// Set a default value for this positional argument.
    pub fn default(mut self, value: &str) -> Self {
        self.default = Some(value.to_string());
        self
    }

    /// Mark this positional as collecting all remaining arguments.
    pub fn multi(mut self) -> Self {
        self.multi = true;
        self
    }

    /// Attach a validator to this positional.
    pub fn validate(mut self, v: Validator) -> Self {
        self.validator = Some(v);
        self
    }
}

impl From<Pos> for PositionalDef {
    fn from(p: Pos) -> PositionalDef {
        PositionalDef {
            name: p.name,
            description: p.description,
            required: p.required,
            default: p.default,
            multi: p.multi,
            validator: p.validator,
        }
    }
}

/// Fluent builder for constructing an [`ArgParser`].
///
/// Chain calls to [`flag()`](ArgBuilder::flag), [`option()`](ArgBuilder::option),
/// [`positional()`](ArgBuilder::positional), and [`subcommand()`](ArgBuilder::subcommand)
/// to define the argument schema, then call [`build()`](ArgBuilder::build) to produce
/// the parser. Construct argument definitions using [`Flag`], [`Opt`], and [`Pos`]
/// and pass them directly to the builder methods.
#[must_use = "builder does nothing until .build() is called"]
#[derive(Clone, Debug)]
pub struct ArgBuilder {
    program_name: Option<String>,
    program_desc: Option<String>,
    version: Option<String>,
    flags: Vec<FlagDef>,
    options: Vec<OptionDef>,
    positionals: Vec<PositionalDef>,
    subcommands: Vec<SubcommandDef>,
    groups: Vec<(String, Vec<String>)>,
    conflicts: Vec<(String, Vec<String>)>,
}

impl ArgBuilder {
    /// Create a new builder with no arguments defined.
    pub fn new() -> Self {
        Self {
            program_name: None,
            program_desc: None,
            version: None,
            flags: Vec::new(),
            options: Vec::new(),
            positionals: Vec::new(),
            subcommands: Vec::new(),
            groups: Vec::new(),
            conflicts: Vec::new(),
        }
    }

    /// Set the program name shown in usage and version text.
    pub fn name(mut self, name: &str) -> Self {
        self.program_name = Some(name.to_string());
        self
    }

    /// Set the program description shown at the top of help text.
    pub fn description(mut self, desc: &str) -> Self {
        self.program_desc = Some(desc.to_string());
        self
    }

    /// Set the version string. Enables `--version` / `-V` flags.
    pub fn version(mut self, version: &str) -> Self {
        self.version = Some(version.to_string());
        self
    }

    /// Add a flag definition to the builder.
    pub fn flag(mut self, flag: Flag) -> Self {
        self.flags.push(FlagDef::from(flag));
        self
    }

    /// Add an option definition to the builder.
    pub fn option(mut self, opt: Opt) -> Self {
        self.options.push(OptionDef::from(opt));
        self
    }

    /// Add a positional argument definition to the builder.
    pub fn positional(mut self, pos: Pos) -> Self {
        self.positionals.push(PositionalDef::from(pos));
        self
    }

    /// Register a subcommand with a name, description, and its own pre-built ArgParser.
    pub fn subcommand(mut self, name: &str, desc: &str, parser: ArgParser) -> Self {
        if let Some(existing) = self.subcommands.iter_mut().find(|s| s.name == name) {
            existing.description = desc.to_string();
            existing.parser = parser;
        } else {
            self.subcommands.push(SubcommandDef {
                name: name.to_string(),
                description: desc.to_string(),
                parser,
            });
        }
        self
    }

    /// Declare an argument group: at least one of the named arguments must be provided.
    pub fn group(mut self, name: &str, members: &[&str]) -> Self {
        self.groups.push((name.to_string(), members.iter().map(|m| m.to_string()).collect()));
        self
    }

    /// Declare a conflict set: at most one of the named arguments may be provided.
    pub fn conflict(mut self, name: &str, members: &[&str]) -> Self {
        self.conflicts.push((name.to_string(), members.iter().map(|m| m.to_string()).collect()));
        self
    }

    /// Validate the schema and produce an [`ArgParser`].
    ///
    /// Returns [`ParseError::InvalidFormat`] if there are duplicate long names,
    /// duplicate short characters, or a `-V` conflict when a version is set.
    #[must_use = "returns the built ArgParser; did you forget to assign it?"]
    pub fn build(self) -> Result<ArgParser, ParseError> {
        // Validate no duplicate long names across flags and options
        let mut seen_longs = std::collections::HashSet::new();
        for flag in &self.flags {
            if !seen_longs.insert(&flag.long) {
                return Err(ParseError::InvalidFormat(format!(
                    "duplicate long argument name: --{}",
                    flag.long
                )));
            }
        }
        for opt in &self.options {
            if !seen_longs.insert(&opt.long) {
                return Err(ParseError::InvalidFormat(format!(
                    "duplicate long argument name: --{}",
                    opt.long
                )));
            }
        }

        // Validate no duplicate short chars across flags and options
        let mut seen_shorts = std::collections::HashSet::new();
        for flag in &self.flags {
            if let Some(ch) = flag.short {
                if !seen_shorts.insert(ch) {
                    return Err(ParseError::InvalidFormat(format!("duplicate short argument: -{}", ch)));
                }
            }
        }
        for opt in &self.options {
            if let Some(ch) = opt.short {
                if !seen_shorts.insert(ch) {
                    return Err(ParseError::InvalidFormat(format!("duplicate short argument: -{}", ch)));
                }
            }
        }

        // Validate no -V conflict when version is configured
        if self.version.is_some() {
            for flag in &self.flags {
                if flag.short == Some('V') {
                    return Err(ParseError::InvalidFormat(
                        "duplicate short argument: -V (reserved for --version)".to_string(),
                    ));
                }
            }
            for opt in &self.options {
                if opt.short == Some('V') {
                    return Err(ParseError::InvalidFormat(
                        "duplicate short argument: -V (reserved for --version)".to_string(),
                    ));
                }
            }
        }

        // Validate positional configurations
        for pos in &self.positionals {
            if pos.required && pos.default.is_some() {
                return Err(ParseError::InvalidFormat(format!(
                    "positional '{}' cannot be both required and have a default",
                    pos.name
                )));
            }
            if pos.required && pos.multi {
                return Err(ParseError::InvalidFormat(format!(
                    "positional '{}' cannot be both required and multi",
                    pos.name
                )));
            }
        }
        if let Some(pos) = self
            .positionals
            .iter()
            .enumerate()
            .find(|(i, p)| p.multi && *i < self.positionals.len() - 1)
            .map(|(_, p)| p)
        {
            return Err(ParseError::InvalidFormat(format!(
                "multi positional '{}' must be the last positional",
                pos.name
            )));
        }

        // Validate groups and conflicts
        let mut validated_groups = Vec::new();
        for (name, members) in &self.groups {
            if members.len() < 2 {
                return Err(ParseError::InvalidFormat(format!(
                    "group '{}' requires at least two members",
                    name
                )));
            }
            for member in members {
                if !self.flags.iter().any(|f| f.long == *member) && !self.options.iter().any(|o| o.long == *member) {
                    return Err(ParseError::InvalidFormat(format!(
                        "group '{}' references unknown argument: --{}",
                        name, member
                    )));
                }
            }
            validated_groups.push(GroupDef {
                name: name.clone(),
                members: members.clone(),
            });
        }

        let mut validated_conflicts = Vec::new();
        for (name, members) in &self.conflicts {
            if members.len() < 2 {
                return Err(ParseError::InvalidFormat(format!(
                    "conflict '{}' requires at least two members",
                    name
                )));
            }
            for member in members {
                if !self.flags.iter().any(|f| f.long == *member) && !self.options.iter().any(|o| o.long == *member) {
                    return Err(ParseError::InvalidFormat(format!(
                        "conflict '{}' references unknown argument: --{}",
                        name, member
                    )));
                }
            }
            validated_conflicts.push(ConflictDef {
                name: name.clone(),
                members: members.clone(),
            });
        }

        Ok(ArgParser {
            program_name: self.program_name,
            program_desc: self.program_desc,
            version: self.version,
            flags: self.flags,
            options: self.options,
            positionals: self.positionals,
            subcommands: self.subcommands,
            groups: validated_groups,
            conflicts: validated_conflicts,
        })
    }
}

impl Default for ArgBuilder {
    fn default() -> Self {
        Self::new()
    }
}