standout-dispatch 7.3.0

Command dispatch and routing for clap-based CLIs
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
//! Handler-Command verification for detecting mismatches between
//! `#[handler]` function signatures and clap `Command` definitions.
//!
//! This module provides types and functions to verify that a handler's
//! expected arguments match what the clap Command actually defines,
//! producing clear error messages when they don't.
//!
//! # Example
//!
//! ```rust,ignore
//! use standout_dispatch::verify::{ExpectedArg, verify_handler_args};
//!
//! // Handler expects these args (generated by #[handler] macro)
//! let expected = vec![
//!     ExpectedArg::flag("verbose", "verbose"),
//!     ExpectedArg::optional_arg("filter", "filter"),
//! ];
//!
//! // Verify against the clap Command
//! verify_handler_args(&command, "my_handler", &expected)?;
//! ```

use clap::{ArgAction, Command};
use std::fmt;

/// Describes what kind of argument a handler expects.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArgKind {
    /// A boolean flag (`#[flag]`), extracted via `get_flag()`
    Flag,
    /// A required argument (`#[arg] name: String`)
    RequiredArg,
    /// An optional argument (`#[arg] name: Option<String>`)
    OptionalArg,
    /// A repeatable argument (`#[arg] names: Vec<String>`)
    VecArg,
}

impl fmt::Display for ArgKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ArgKind::Flag => write!(f, "boolean flag"),
            ArgKind::RequiredArg => write!(f, "required argument"),
            ArgKind::OptionalArg => write!(f, "optional argument"),
            ArgKind::VecArg => write!(f, "repeatable argument"),
        }
    }
}

/// What a handler expects for a single parameter.
///
/// Generated by the `#[handler]` macro via `handler_name__expected_args()`.
#[derive(Debug, Clone)]
pub struct ExpectedArg {
    /// The CLI argument name (e.g., "in-progress")
    pub cli_name: String,
    /// The Rust parameter name (e.g., "in_progress")
    pub rust_name: String,
    /// What kind of argument this is
    pub kind: ArgKind,
}

impl ExpectedArg {
    /// Create an expected flag.
    pub fn flag(cli_name: impl Into<String>, rust_name: impl Into<String>) -> Self {
        Self {
            cli_name: cli_name.into(),
            rust_name: rust_name.into(),
            kind: ArgKind::Flag,
        }
    }

    /// Create an expected required argument.
    pub fn required_arg(cli_name: impl Into<String>, rust_name: impl Into<String>) -> Self {
        Self {
            cli_name: cli_name.into(),
            rust_name: rust_name.into(),
            kind: ArgKind::RequiredArg,
        }
    }

    /// Create an expected optional argument.
    pub fn optional_arg(cli_name: impl Into<String>, rust_name: impl Into<String>) -> Self {
        Self {
            cli_name: cli_name.into(),
            rust_name: rust_name.into(),
            kind: ArgKind::OptionalArg,
        }
    }

    /// Create an expected vec argument.
    pub fn vec_arg(cli_name: impl Into<String>, rust_name: impl Into<String>) -> Self {
        Self {
            cli_name: cli_name.into(),
            rust_name: rust_name.into(),
            kind: ArgKind::VecArg,
        }
    }
}

/// A single mismatch between handler expectation and command definition.
#[derive(Debug, Clone)]
pub enum ArgMismatch {
    /// Handler expects an argument that doesn't exist in the command.
    MissingInCommand {
        cli_name: String,
        rust_name: String,
        expected_kind: ArgKind,
    },
    /// Handler expects a flag but command has a non-flag argument.
    NotAFlag {
        cli_name: String,
        actual_action: String,
    },
    /// Handler expects a non-flag but command has a flag.
    UnexpectedFlag {
        cli_name: String,
        expected_kind: ArgKind,
    },
    /// Handler expects required but command has optional (or vice versa).
    RequiredMismatch {
        cli_name: String,
        handler_required: bool,
        command_required: bool,
    },
}

impl fmt::Display for ArgMismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ArgMismatch::MissingInCommand {
                cli_name,
                rust_name,
                expected_kind,
            } => {
                writeln!(f, "  Argument `{cli_name}` (parameter `{rust_name}`):")?;
                writeln!(f, "    - Handler expects: {expected_kind}")?;
                writeln!(f, "    - Command: argument not defined")?;
                writeln!(f)?;
                writeln!(f, "    Fix: Add the argument to your clap Command:")?;
                match expected_kind {
                    ArgKind::Flag => {
                        writeln!(
                            f,
                            "      .arg(Arg::new(\"{cli_name}\").long(\"{cli_name}\").action(ArgAction::SetTrue))"
                        )
                    }
                    ArgKind::RequiredArg => {
                        writeln!(
                            f,
                            "      .arg(Arg::new(\"{cli_name}\").long(\"{cli_name}\").required(true))"
                        )
                    }
                    ArgKind::OptionalArg => {
                        writeln!(
                            f,
                            "      .arg(Arg::new(\"{cli_name}\").long(\"{cli_name}\"))"
                        )
                    }
                    ArgKind::VecArg => {
                        writeln!(
                            f,
                            "      .arg(Arg::new(\"{cli_name}\").long(\"{cli_name}\").action(ArgAction::Append))"
                        )
                    }
                }
            }
            ArgMismatch::NotAFlag {
                cli_name,
                actual_action,
            } => {
                writeln!(f, "  Flag `{cli_name}`:")?;
                writeln!(f, "    - Handler expects: boolean flag (via get_flag)")?;
                writeln!(f, "    - Command defines: {actual_action}")?;
                writeln!(f)?;
                writeln!(f, "    Fix: Change the argument's action to SetTrue:")?;
                writeln!(
                    f,
                    "      .arg(Arg::new(\"{cli_name}\").long(\"{cli_name}\").action(ArgAction::SetTrue))"
                )
            }
            ArgMismatch::UnexpectedFlag {
                cli_name,
                expected_kind,
            } => {
                writeln!(f, "  Argument `{cli_name}`:")?;
                writeln!(f, "    - Handler expects: {expected_kind}")?;
                writeln!(f, "    - Command defines: boolean flag (SetTrue/SetFalse)")?;
                writeln!(f)?;
                writeln!(f, "    Fix: Either:")?;
                writeln!(
                    f,
                    "      - Change the handler parameter to `#[flag] {cli_name}: bool`"
                )?;
                writeln!(
                    f,
                    "      - Or change the command's action: .action(ArgAction::Set)"
                )
            }
            ArgMismatch::RequiredMismatch {
                cli_name,
                handler_required,
                command_required: _,
            } => {
                writeln!(f, "  Argument `{cli_name}`:")?;
                if *handler_required {
                    writeln!(f, "    - Handler expects: required argument")?;
                    writeln!(f, "    - Command defines: optional argument")?;
                    writeln!(f)?;
                    writeln!(f, "    Fix: Either:")?;
                    writeln!(
                        f,
                        "      - Change handler to `#[arg] {}: Option<T>`",
                        cli_name.replace('-', "_")
                    )?;
                    writeln!(f, "      - Or add `.required(true)` to the command arg")
                } else {
                    writeln!(f, "    - Handler expects: optional argument (Option<T>)")?;
                    writeln!(f, "    - Command defines: required argument")?;
                    writeln!(f)?;
                    writeln!(f, "    Fix: Either:")?;
                    writeln!(
                        f,
                        "      - Change handler to `#[arg] {}: T` (not Option)",
                        cli_name.replace('-', "_")
                    )?;
                    writeln!(
                        f,
                        "      - Or remove `.required(true)` from the command arg"
                    )
                }
            }
        }
    }
}

/// Error when handler expectations don't match command definition.
#[derive(Debug, Clone)]
pub struct HandlerMismatchError {
    /// The handler function name
    pub handler_name: String,
    /// The command name (if known)
    pub command_name: Option<String>,
    /// All detected mismatches
    pub mismatches: Vec<ArgMismatch>,
}

impl std::error::Error for HandlerMismatchError {}

impl fmt::Display for HandlerMismatchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let cmd_desc = self
            .command_name
            .as_ref()
            .map(|n| format!(" for command `{n}`"))
            .unwrap_or_default();

        writeln!(
            f,
            "Handler `{}` is incompatible with clap Command{cmd_desc}",
            self.handler_name
        )?;
        writeln!(f)?;

        for mismatch in &self.mismatches {
            write!(f, "{mismatch}")?;
        }

        Ok(())
    }
}

/// Check if an ArgAction represents a boolean flag.
fn is_flag_action(action: &ArgAction) -> bool {
    matches!(action, ArgAction::SetTrue | ArgAction::SetFalse)
}

/// Get a human-readable description of an ArgAction.
fn describe_action(action: &ArgAction) -> String {
    match action {
        ArgAction::Set => "ArgAction::Set (single value)".to_string(),
        ArgAction::Append => "ArgAction::Append (multiple values)".to_string(),
        ArgAction::SetTrue => "ArgAction::SetTrue (boolean flag)".to_string(),
        ArgAction::SetFalse => "ArgAction::SetFalse (boolean flag)".to_string(),
        ArgAction::Count => "ArgAction::Count (counter)".to_string(),
        ArgAction::Help => "ArgAction::Help".to_string(),
        ArgAction::HelpShort => "ArgAction::HelpShort".to_string(),
        ArgAction::HelpLong => "ArgAction::HelpLong".to_string(),
        ArgAction::Version => "ArgAction::Version".to_string(),
        _ => "unknown action".to_string(),
    }
}

/// Verify that a handler's expected arguments match a clap Command's definition.
///
/// Returns `Ok(())` if all expectations are met, or `Err(HandlerMismatchError)`
/// with detailed diagnostics if there are mismatches.
///
/// # Arguments
///
/// * `command` - The clap Command to verify against
/// * `handler_name` - The handler function name (for error messages)
/// * `expected` - The arguments the handler expects (from `__expected_args()`)
///
/// # Example
///
/// ```rust,ignore
/// let command = Command::new("list")
///     .arg(Arg::new("verbose").long("verbose").action(ArgAction::SetTrue));
///
/// let expected = vec![ExpectedArg::flag("verbose", "verbose")];
///
/// verify_handler_args(&command, "list_handler", &expected)?;
/// ```
pub fn verify_handler_args(
    command: &Command,
    handler_name: &str,
    expected: &[ExpectedArg],
) -> Result<(), HandlerMismatchError> {
    let mut mismatches = Vec::new();

    for exp in expected {
        // Find the argument in the command
        let arg = command
            .get_arguments()
            .find(|a| a.get_id() == exp.cli_name.as_str());

        match arg {
            None => {
                // Argument doesn't exist in command
                mismatches.push(ArgMismatch::MissingInCommand {
                    cli_name: exp.cli_name.clone(),
                    rust_name: exp.rust_name.clone(),
                    expected_kind: exp.kind.clone(),
                });
            }
            Some(arg) => {
                let action = arg.get_action();

                match exp.kind {
                    ArgKind::Flag => {
                        // Handler expects a flag - command must have SetTrue/SetFalse
                        if !is_flag_action(action) {
                            mismatches.push(ArgMismatch::NotAFlag {
                                cli_name: exp.cli_name.clone(),
                                actual_action: describe_action(action),
                            });
                        }
                    }
                    ArgKind::RequiredArg => {
                        // Handler expects required arg
                        if is_flag_action(action) {
                            mismatches.push(ArgMismatch::UnexpectedFlag {
                                cli_name: exp.cli_name.clone(),
                                expected_kind: exp.kind.clone(),
                            });
                        } else if matches!(action, ArgAction::Count) {
                            // Count is fine for a required integer arg (it returns 0 if missing)
                        } else if !arg.is_required_set() && arg.get_default_values().is_empty() {
                            mismatches.push(ArgMismatch::RequiredMismatch {
                                cli_name: exp.cli_name.clone(),
                                handler_required: true,
                                command_required: false,
                            });
                        }
                    }
                    ArgKind::OptionalArg => {
                        // Handler expects optional arg
                        if is_flag_action(action) {
                            mismatches.push(ArgMismatch::UnexpectedFlag {
                                cli_name: exp.cli_name.clone(),
                                expected_kind: exp.kind.clone(),
                            });
                        } else if arg.is_required_set() {
                            mismatches.push(ArgMismatch::RequiredMismatch {
                                cli_name: exp.cli_name.clone(),
                                handler_required: false,
                                command_required: true,
                            });
                        }
                    }
                    ArgKind::VecArg => {
                        // Handler expects vec arg - command should have Append
                        if is_flag_action(action) {
                            mismatches.push(ArgMismatch::UnexpectedFlag {
                                cli_name: exp.cli_name.clone(),
                                expected_kind: exp.kind.clone(),
                            });
                        }
                        // Note: We don't strictly require Append - Set with multiple
                        // values can also work. Could add a warning here if needed.
                    }
                }
            }
        }
    }

    if mismatches.is_empty() {
        Ok(())
    } else {
        Err(HandlerMismatchError {
            handler_name: handler_name.to_string(),
            command_name: Some(command.get_name().to_string()),
            mismatches,
        })
    }
}

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

    #[test]
    fn test_verify_matching_flag() {
        let command = Command::new("test").arg(
            Arg::new("verbose")
                .long("verbose")
                .action(ArgAction::SetTrue),
        );

        let expected = vec![ExpectedArg::flag("verbose", "verbose")];

        assert!(verify_handler_args(&command, "test_handler", &expected).is_ok());
    }

    #[test]
    fn test_verify_missing_arg() {
        let command = Command::new("test");

        let expected = vec![ExpectedArg::flag("verbose", "verbose")];

        let err = verify_handler_args(&command, "test_handler", &expected).unwrap_err();
        assert_eq!(err.mismatches.len(), 1);
        assert!(matches!(
            &err.mismatches[0],
            ArgMismatch::MissingInCommand { cli_name, .. } if cli_name == "verbose"
        ));
    }

    #[test]
    fn test_verify_wrong_action_for_flag() {
        let command =
            Command::new("test").arg(Arg::new("verbose").long("verbose").action(ArgAction::Set));

        let expected = vec![ExpectedArg::flag("verbose", "verbose")];

        let err = verify_handler_args(&command, "test_handler", &expected).unwrap_err();
        assert_eq!(err.mismatches.len(), 1);
        assert!(matches!(&err.mismatches[0], ArgMismatch::NotAFlag { .. }));
    }

    #[test]
    fn test_verify_required_mismatch() {
        let command =
            Command::new("test").arg(Arg::new("name").long("name").action(ArgAction::Set));
        // Command has optional, handler expects required

        let expected = vec![ExpectedArg::required_arg("name", "name")];

        let err = verify_handler_args(&command, "test_handler", &expected).unwrap_err();
        assert_eq!(err.mismatches.len(), 1);
        assert!(matches!(
            &err.mismatches[0],
            ArgMismatch::RequiredMismatch {
                handler_required: true,
                command_required: false,
                ..
            }
        ));
    }

    #[test]
    fn test_verify_optional_matches() {
        let command =
            Command::new("test").arg(Arg::new("filter").long("filter").action(ArgAction::Set));

        let expected = vec![ExpectedArg::optional_arg("filter", "filter")];

        assert!(verify_handler_args(&command, "test_handler", &expected).is_ok());
    }

    #[test]
    fn test_error_message_formatting() {
        let command =
            Command::new("list").arg(Arg::new("verbose").long("verbose").action(ArgAction::Set));

        let expected = vec![ExpectedArg::flag("verbose", "verbose")];

        let err = verify_handler_args(&command, "list_handler", &expected).unwrap_err();
        let msg = err.to_string();

        assert!(msg.contains("Handler `list_handler`"));
        assert!(msg.contains("command `list`"));
        assert!(msg.contains("Flag `verbose`"));
        assert!(msg.contains("ArgAction::SetTrue"));
    }
}