cmdkit 0.2.0

Core library for CLI tools, providing common functionality and utilities for building command-line 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
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
use std::{option::Option, sync::Arc};

use super::strategy::FallbackSubcommandStrategy;
use super::{
    CommandStrategy, FunctionStrategy, StrategyError, SubcommandCatalog, SubcommandRouter,
};

/// Declarative value-taking option metadata.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Switch {
    /// Canonical option name, for example: "path".
    pub name: String,
    /// Human-readable description for help output.
    pub description: String,
    /// Alternative spellings accepted during parsing.
    pub aliases: Vec<String>,
}

impl Switch {
    /// Creates a value-taking option declaration.
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            aliases: Vec::new(),
        }
    }

    /// Adds alias spellings for this option.
    pub fn with_aliases(mut self, aliases: Vec<String>) -> Self {
        self.aliases = aliases;
        self
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Argument {
    /// Canonical
    /// Argument name, for example: "verbose".
    pub name: String,
    /// Human-readable description for help output.
    pub description: String,
    /// Alternative spellings accepted during parsing.
    pub aliases: Vec<String>,
    /// Numeric payload that can be mapped to an enum or bit mask.
    pub value: Option<String>,
    /// Whether this argument is required or optional.
    pub required: bool,
}

impl Argument {
    /// Creates a
    /// Argument declaration with the given numeric payload.
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            aliases: Vec::new(),
            value: None,
            required: false,
        }
    }

    /// Adds alias spellings for this
    /// Argument.
    pub fn with_aliases(mut self, aliases: Vec<impl Into<String>>) -> Self {
        self.aliases = aliases.into_iter().map(|s| s.into()).collect();
        self
    }

    /// Sets the value for this argument.
    pub fn set_value(mut self, value: impl Into<String>) -> Self {
        self.value = Some(value.into());
        self
    }

    /// Sets required to true, indicating this argument is required.
    pub fn set_required(mut self) -> Self {
        self.required = true;
        self
    }
}

/// User-facing metadata for a single CLI command.
#[derive(Clone)]
pub struct CommandMetaData {
    /// Command name used for lookup (for example: "help", "new", "build").
    pub name: String,
    /// Short description shown in generated help output.
    pub description: String,
    /// Optional explicit usage text for this command.
    pub usage: Option<String>,
    /// Optional detailed long-form help text.
    pub long_description: Option<String>,
    /// Optional command examples shown in help output.
    pub examples: Vec<String>,
    /// Optional option/flag descriptions shown in help output.
    pub options: Vec<Switch>,
    /// Optional
    /// Argument/flag descriptions shown in help output.
    pub arguments: Vec<Argument>,
    /// Optional aliases accepted by command discovery layers.
    pub aliases: Vec<String>,
}

impl CommandMetaData {
    /// Creates command metadata with required fields and sensible defaults.
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            usage: None,
            long_description: None,
            examples: Vec::new(),
            options: Vec::new(),
            arguments: Vec::new(),
            aliases: Vec::new(),
        }
    }

    /// Adds explicit usage text for help rendering.
    pub fn with_usage(mut self, usage: impl Into<String>) -> Self {
        self.usage = Some(usage.into());
        self
    }

    /// Adds detailed long-form description for help rendering.
    pub fn with_long_description(mut self, long_description: impl Into<String>) -> Self {
        self.long_description = Some(long_description.into());
        self
    }

    /// Adds example entries for this command.
    pub fn with_examples(mut self, examples: Vec<String>) -> Self {
        self.examples = examples;
        self
    }

    /// Adds value-taking option definitions for this command.
    pub fn with_options(mut self, options: Vec<Switch>) -> Self {
        self.options = options;
        self
    }

    /// Adds
    /// Argument/flag definitions for this command.
    pub fn with_arguments(mut self, arguments: Vec<Argument>) -> Self {
        self.arguments = arguments;
        self
    }

    /// Adds alias entries for this command.
    pub fn with_aliases(mut self, aliases: Vec<String>) -> Self {
        self.aliases = aliases;
        self
    }
}

/// Metadata + handler pair for a single CLI command.
#[derive(Clone)]
pub struct Command {
    /// User-facing command metadata.
    pub metadata: CommandMetaData,
    strategy: Arc<dyn CommandStrategy>,
}

impl Command {
    /// Creates a command specification from any handler implementation type.
    pub fn new<S>(name: impl Into<String>, description: impl Into<String>, strategy: S) -> Self
    where
        S: CommandStrategy + 'static,
    {
        Self {
            metadata: CommandMetaData::new(name, description),
            strategy: Arc::new(strategy),
        }
    }

    /// Executes this command after parsing raw argv-style arguments into the strategy contract.
    pub fn execute(&self, args: Vec<String>) -> Result<(), StrategyError> {
        let invocation = parser::ArgumentParser::parse(args, &self.metadata, |token| {
            self.matches_subcommand(token)
        })?;
        self.strategy
            .execute(invocation.options, invocation.arguments, invocation.params)
    }

    /// Returns the optional subcommand catalog exposed by the underlying strategy.
    pub fn subcommand_catalog(&self) -> Option<&dyn SubcommandCatalog> {
        self.strategy.subcommand_catalog()
    }

    /// Creates a command specification directly from a function or closure handler.
    pub fn from_fn<F>(name: impl Into<String>, description: impl Into<String>, runner: F) -> Self
    where
        F: Fn(Vec<Switch>, Vec<Argument>, Vec<String>) -> Result<(), StrategyError>
            + Send
            + Sync
            + 'static,
    {
        Self::new(name, description, FunctionStrategy::new(runner))
    }

    /// Creates a fluent command builder.
    pub fn builder(name: impl Into<String>, description: impl Into<String>) -> CommandBuilder {
        CommandBuilder::new(name, description)
    }

    fn matches_subcommand(&self, token: &str) -> bool {
        self.subcommand_catalog().is_some_and(|catalog| {
            catalog.subcommands().into_iter().any(|command| {
                command.metadata.name == token
                    || command.metadata.aliases.iter().any(|alias| alias == token)
            })
        })
    }
}

struct ParsedInvocation {
    options: Vec<Switch>,
    arguments: Vec<Argument>,
    params: Vec<String>,
}

/// Creates a fluent command builder.
pub fn command(name: impl Into<String>, description: impl Into<String>) -> CommandBuilder {
    CommandBuilder::new(name, description)
}

/// creates a value-taking option declaration.
pub fn argument(name: impl Into<String>, description: impl Into<String>) -> Argument {
    Argument::new(name, description)
}

/// creates a value-taking option declaration with the required flag set to true.
pub fn switch(name: impl Into<String>, description: impl Into<String>) -> Switch {
    Switch::new(name, description)
}
/// Fluent command builder that hides strategy implementation details.
pub struct CommandBuilder {
    metadata: CommandMetaData,
    strategy: Option<Arc<dyn CommandStrategy>>,
    subcommands: Vec<Command>,
}

impl CommandBuilder {
    /// Creates a builder with required metadata.
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            metadata: CommandMetaData::new(name, description),
            strategy: None,
            subcommands: Vec::new(),
        }
    }

    /// Sets command strategy implementation.
    pub fn handler<S>(mut self, strategy: S) -> Self
    where
        S: CommandStrategy + 'static,
    {
        self.strategy = Some(Arc::new(strategy));
        self
    }

    /// Sets command strategy using a function/closure.
    pub fn handler_fn<F>(mut self, runner: F) -> Self
    where
        F: Fn(Vec<Switch>, Vec<Argument>, Vec<String>) -> Result<(), StrategyError>
            + Send
            + Sync
            + 'static,
    {
        self.strategy = Some(Arc::new(FunctionStrategy::new(runner)));
        self
    }

    /// Adds a subcommand.
    pub fn subcommand<C>(mut self, subcommand: C) -> Self
    where
        C: Into<Command>,
    {
        self.subcommands.push(subcommand.into());
        self
    }

    /// Adds explicit usage text for help rendering.
    pub fn with_usage(mut self, usage: impl Into<String>) -> Self {
        self.metadata = self.metadata.with_usage(usage);
        self
    }

    /// Adds detailed long-form description for help rendering.
    pub fn with_long_description(mut self, long_description: impl Into<String>) -> Self {
        self.metadata = self.metadata.with_long_description(long_description);
        self
    }

    /// Adds example entries for this command.
    pub fn with_examples(mut self, examples: Vec<String>) -> Self {
        self.metadata = self.metadata.with_examples(examples);
        self
    }

    /// Adds option/flag description entries for this command.
    pub fn with_options(mut self, options: Vec<Switch>) -> Self {
        self.metadata = self.metadata.with_options(options);
        self
    }

    /// Adds
    /// Argument/flag description entries for this command.
    pub fn with_arguments(mut self, arguments: Vec<Argument>) -> Self {
        self.metadata = self.metadata.with_arguments(arguments);
        self
    }

    /// Adds alias entries for this command.
    pub fn with_aliases(mut self, aliases: Vec<impl Into<String>>) -> Self {
        self.metadata = self
            .metadata
            .with_aliases(aliases.into_iter().map(|s| s.into()).collect());
        self
    }

    /// Builds the final command.
    pub fn build(self) -> Command {
        let strategy: Arc<dyn CommandStrategy> = if self.subcommands.is_empty() {
            self.strategy.unwrap_or_else(|| {
                Arc::new(FunctionStrategy::new(|_, _, _| {
                    Err(StrategyError::internal(
                        "command has no handler; configure a handler or subcommand",
                    ))
                }))
            })
        } else {
            let mut router = SubcommandRouter::new();
            for subcommand in self.subcommands {
                router.register_mut(subcommand);
            }

            match self.strategy {
                Some(fallback) => Arc::new(FallbackSubcommandStrategy::new(fallback, router)),
                None => Arc::new(router),
            }
        };

        Command {
            metadata: self.metadata,
            strategy,
        }
    }
}

impl From<CommandBuilder> for Command {
    fn from(value: CommandBuilder) -> Self {
        value.build()
    }
}

mod parser {
    use super::{Argument, CommandMetaData, ParsedInvocation, Switch};
    use crate::StrategyError;

    pub(super) struct ArgumentParser;

    impl ArgumentParser {
        fn find_declared_argument<'a>(
            metadata: &'a CommandMetaData,
            flag: &str,
        ) -> Option<&'a Argument> {
            metadata.arguments.iter().find(|argument| {
                argument.name == flag || argument.aliases.iter().any(|alias| alias == flag)
            })
        }

        fn find_declared_switch<'a>(
            metadata: &'a CommandMetaData,
            flag: &str,
        ) -> Option<&'a Switch> {
            metadata.options.iter().find(|option| {
                option.name == flag || option.aliases.iter().any(|alias| alias == flag)
            })
        }

        fn upsert_argument(arguments: &mut Vec<Argument>, argument: Argument) {
            if let Some(existing) = arguments
                .iter_mut()
                .find(|existing| existing.name == argument.name)
            {
                *existing = argument;
                return;
            }

            arguments.push(argument);
        }

        fn validate_required_arguments(
            metadata: &CommandMetaData,
            arguments: &[Argument],
        ) -> Result<(), StrategyError> {
            for required in metadata
                .arguments
                .iter()
                .filter(|argument| argument.required)
            {
                let value = arguments
                    .iter()
                    .find(|argument| argument.name == required.name)
                    .and_then(|argument| argument.value.as_deref());

                if value.is_none_or(|value| value.trim().is_empty()) {
                    return Err(StrategyError::invalid_arguments(format!(
                        "missing value for required argument '--{}'",
                        required.name
                    )));
                }
            }

            Ok(())
        }

        pub fn parse<F>(
            args: Vec<String>,
            metadata: &CommandMetaData,
            is_subcommand: F,
        ) -> Result<ParsedInvocation, StrategyError>
        where
            F: Fn(&str) -> bool,
        {
            let mut options = Vec::new();
            let mut arguments = Vec::new();
            let mut params = Vec::new();
            let mut index = 0;

            while index < args.len() {
                let token = &args[index];

                if is_subcommand(token) {
                    break;
                }

                let Some(flag) = token.strip_prefix("--") else {
                    params.push(token.clone());
                    index += 1;
                    continue;
                };

                if let Some((flag_name, inline_value)) = flag.split_once('=') {
                    if let Some(argument_decl) = Self::find_declared_argument(metadata, flag_name) {
                        Self::upsert_argument(
                            &mut arguments,
                            argument_decl.clone().set_value(inline_value.to_string()),
                        );
                        index += 1;
                        continue;
                    }

                    if let Some(option_decl) = Self::find_declared_switch(metadata, flag_name) {
                        return Err(StrategyError::invalid_arguments(format!(
                            "switch '--{}' does not take a value",
                            option_decl.name
                        )));
                    }

                    return Err(StrategyError::invalid_arguments(format!(
                        "unknown flag '--{}'",
                        flag_name
                    )));
                }

                if let Some(argument_decl) = Self::find_declared_argument(metadata, flag) {
                    let Some(next) = args.get(index + 1) else {
                        return Err(StrategyError::invalid_arguments(format!(
                            "missing value for argument '--{}'",
                            argument_decl.name
                        )));
                    };

                    if next.starts_with("--") || is_subcommand(next) {
                        return Err(StrategyError::invalid_arguments(format!(
                            "missing value for argument '--{}'",
                            argument_decl.name
                        )));
                    }

                    Self::upsert_argument(
                        &mut arguments,
                        argument_decl.clone().set_value(next.clone()),
                    );
                    index += 2;
                    continue;
                }

                if let Some(option_decl) = Self::find_declared_switch(metadata, flag) {
                    if flag.contains('=') {
                        return Err(StrategyError::invalid_arguments(format!(
                            "switch '--{}' does not take a value",
                            option_decl.name
                        )));
                    }

                    options.push(option_decl.clone());
                    index += 1;
                    continue;
                }

                return Err(StrategyError::invalid_arguments(format!(
                    "unknown flag '--{}'",
                    flag
                )));
            }

            params.extend_from_slice(&args[index..]);

            Self::validate_required_arguments(metadata, &arguments)?;

            Ok(ParsedInvocation {
                options,
                arguments,
                params,
            })
        }
    }
}