help-probe 0.1.0

CLI tool discovery and automation framework that extracts structured information from command help text
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
use crate::model::{ArgumentSpec, ArgumentType, OptionSpec, ProbeResult};
use serde::Serialize;

/// Result of validating a command invocation.
#[derive(Debug, Serialize)]
pub struct ValidationResult {
    /// Whether the command is valid.
    pub is_valid: bool,
    /// List of validation errors.
    pub errors: Vec<ValidationError>,
    /// List of validation warnings.
    pub warnings: Vec<ValidationError>,
}

/// A single validation error or warning.
#[derive(Debug, Serialize, Clone)]
pub struct ValidationError {
    /// Type of validation error.
    pub error_type: ValidationErrorType,
    /// Human-readable error message.
    pub message: String,
    /// The option or argument that caused the error (if applicable).
    pub target: Option<String>,
}

/// Types of validation errors.
#[derive(Debug, Serialize, Clone)]
pub enum ValidationErrorType {
    /// Required argument is missing.
    MissingRequiredArgument,
    /// Required option is missing.
    MissingRequiredOption,
    /// Unknown option provided.
    UnknownOption,
    /// Option requires an argument but none provided.
    OptionMissingArgument,
    /// Option provided but doesn't take an argument.
    OptionUnexpectedArgument,
    /// Invalid argument type (e.g., number expected but string provided).
    InvalidArgumentType,
    /// Unknown subcommand.
    UnknownSubcommand,
    /// Too many arguments provided (non-variadic argument limit exceeded).
    TooManyArguments,
    /// Too few arguments provided.
    TooFewArguments,
}

/// Validate a command invocation against a ProbeResult.
///
/// This checks:
/// - Required arguments are provided
/// - Required options are provided
/// - Options are valid (known to the command)
/// - Arguments match expected types
/// - Subcommands are valid
///
/// # Examples
///
/// ```
/// use help_probe::{validation::validate_command, model::{ProbeResult, OptionSpec, OptionType}};
///
/// let result = ProbeResult {
///     command: "mytool".to_string(),
///     args: vec![],
///     exit_code: Some(0),
///     timed_out: false,
///     help_flag_detected: true,
///     usage_blocks: vec![],
///     options: vec![OptionSpec {
///         short_flags: vec!["-v".to_string()],
///         long_flags: vec!["--verbose".to_string()],
///         description: Some("Verbose output".to_string()),
///         option_type: OptionType::Boolean,
///         required: false,
///         default_value: None,
///         takes_argument: false,
///         argument_name: None,
///         choices: vec![],
///     }],
///     subcommands: vec![],
///     arguments: vec![],
///     examples: vec![],
///     environment_variables: vec![],
///     validation_rules: vec![],
///     raw_stdout: String::new(),
///     raw_stderr: String::new(),
/// };
///
/// // Valid command
/// let validation = validate_command(&result, "mytool", &["--verbose".to_string()]);
/// assert!(validation.is_valid);
///
/// // Invalid option
/// let validation = validate_command(&result, "mytool", &["--unknown".to_string()]);
/// assert!(!validation.is_valid);
/// assert!(validation.errors.iter().any(|e| matches!(e.error_type, help_probe::validation::ValidationErrorType::UnknownOption)));
/// ```
pub fn validate_command(result: &ProbeResult, command: &str, args: &[String]) -> ValidationResult {
    let mut errors = Vec::new();
    let mut warnings = Vec::new();

    // Verify command name matches
    if command != result.command {
        warnings.push(ValidationError {
            error_type: ValidationErrorType::UnknownSubcommand,
            message: format!(
                "Command name mismatch: expected '{}', got '{}'",
                result.command, command
            ),
            target: Some(command.to_string()),
        });
    }

    // Parse arguments into options, subcommands, and positional arguments
    let parsed = parse_command_args(args, result);

    // Validate options
    validate_options(result, &parsed, &mut errors, &mut warnings);

    // Validate arguments
    validate_arguments(result, &parsed, &mut errors, &mut warnings);

    // Validate subcommands
    validate_subcommands(result, &parsed, &mut errors, &mut warnings);

    ValidationResult {
        is_valid: errors.is_empty(),
        errors,
        warnings,
    }
}

/// Parsed representation of command arguments.
struct ParsedArgs {
    /// Options found (flag -> value if takes argument)
    options: std::collections::HashMap<String, Option<String>>,
    /// Subcommands found
    subcommands: Vec<String>,
    /// Positional arguments
    positional_args: Vec<String>,
}

/// Parse command arguments into options, subcommands, and positional arguments.
fn parse_command_args(args: &[String], result: &ProbeResult) -> ParsedArgs {
    let mut options = std::collections::HashMap::new();
    let mut subcommands = Vec::new();
    let mut positional_args = Vec::new();

    // Build set of all known options
    let mut known_options = std::collections::HashSet::new();
    for opt in &result.options {
        for short in &opt.short_flags {
            known_options.insert(short.clone());
        }
        for long in &opt.long_flags {
            known_options.insert(long.clone());
        }
    }

    // Build set of known subcommands
    let known_subcommands: std::collections::HashSet<String> =
        result.subcommands.iter().map(|s| s.name.clone()).collect();

    let mut i = 0;
    while i < args.len() {
        let arg = &args[i];

        // Check if it's an option
        if arg.starts_with("--") {
            // Long option
            let (opt_name, value) = if let Some(eq_pos) = arg.find('=') {
                (
                    arg[..eq_pos].to_string(),
                    Some(arg[eq_pos + 1..].to_string()),
                )
            } else {
                (arg.clone(), None)
            };

            // Check if next arg is a value (not an option or subcommand)
            if value.is_none() && i + 1 < args.len() {
                let next = &args[i + 1];
                if !next.starts_with('-') && !known_subcommands.contains(next) {
                    // Check if this option takes an argument
                    if let Some(opt_spec) = find_option_by_flag(&opt_name, result) {
                        if opt_spec.takes_argument {
                            options.insert(opt_name, Some(next.clone()));
                            i += 2;
                            continue;
                        }
                    }
                }
            }

            options.insert(opt_name, value);
            i += 1;
        } else if arg.starts_with('-') && arg.len() > 1 {
            // Short option(s)
            let chars: Vec<char> = arg.chars().skip(1).collect();
            for (idx, ch) in chars.iter().enumerate() {
                let opt_name = format!("-{}", ch);
                if known_options.contains(&opt_name) {
                    // Check if this option takes an argument
                    if let Some(opt_spec) = find_option_by_flag(&opt_name, result) {
                        if opt_spec.takes_argument {
                            // Last char in group, next arg is value
                            if idx == chars.len() - 1 && i + 1 < args.len() {
                                let next = &args[i + 1];
                                if !next.starts_with('-') {
                                    options.insert(opt_name, Some(next.clone()));
                                    i += 2;
                                    break;
                                }
                            }
                        }
                    }
                    options.insert(opt_name, None);
                }
            }
            i += 1;
        } else if known_subcommands.contains(arg) {
            // Subcommand
            subcommands.push(arg.clone());
            i += 1;
        } else {
            // Positional argument
            positional_args.push(arg.clone());
            i += 1;
        }
    }

    ParsedArgs {
        options,
        subcommands,
        positional_args,
    }
}

/// Find an option spec by its flag name.
fn find_option_by_flag<'a>(flag: &str, result: &'a ProbeResult) -> Option<&'a OptionSpec> {
    result.options.iter().find(|opt| {
        opt.short_flags.contains(&flag.to_string()) || opt.long_flags.contains(&flag.to_string())
    })
}

/// Validate options in the parsed command.
fn validate_options(
    result: &ProbeResult,
    parsed: &ParsedArgs,
    errors: &mut Vec<ValidationError>,
    warnings: &mut Vec<ValidationError>,
) {
    // Build set of all known options
    let mut known_options = std::collections::HashSet::new();
    for opt in &result.options {
        for short in &opt.short_flags {
            known_options.insert(short.clone());
        }
        for long in &opt.long_flags {
            known_options.insert(long.clone());
        }
    }

    // Check for unknown options
    for opt_name in parsed.options.keys() {
        if !known_options.contains(opt_name) {
            errors.push(ValidationError {
                error_type: ValidationErrorType::UnknownOption,
                message: format!("Unknown option: {}", opt_name),
                target: Some(opt_name.clone()),
            });
        }
    }

    // Check required options
    for opt in &result.options {
        if opt.required {
            let found = opt
                .short_flags
                .iter()
                .any(|f| parsed.options.contains_key(f))
                || opt
                    .long_flags
                    .iter()
                    .any(|f| parsed.options.contains_key(f));

            if !found {
                let opt_name = opt
                    .long_flags
                    .first()
                    .or_else(|| opt.short_flags.first())
                    .unwrap();
                errors.push(ValidationError {
                    error_type: ValidationErrorType::MissingRequiredOption,
                    message: format!("Required option missing: {}", opt_name),
                    target: Some(opt_name.clone()),
                });
            }
        }

        // Check if option that takes argument has one
        if opt.takes_argument {
            for flag in &opt.short_flags {
                if let Some(value) = parsed.options.get(flag) {
                    if value.is_none() {
                        errors.push(ValidationError {
                            error_type: ValidationErrorType::OptionMissingArgument,
                            message: format!("Option {} requires an argument", flag),
                            target: Some(flag.clone()),
                        });
                    }
                }
            }
            for flag in &opt.long_flags {
                if let Some(value) = parsed.options.get(flag) {
                    if value.is_none() {
                        errors.push(ValidationError {
                            error_type: ValidationErrorType::OptionMissingArgument,
                            message: format!("Option {} requires an argument", flag),
                            target: Some(flag.clone()),
                        });
                    }
                }
            }
        } else {
            // Check if boolean option has unexpected argument
            for flag in &opt.short_flags {
                if let Some(Some(_)) = parsed.options.get(flag) {
                    warnings.push(ValidationError {
                        error_type: ValidationErrorType::OptionUnexpectedArgument,
                        message: format!("Option {} does not take an argument", flag),
                        target: Some(flag.clone()),
                    });
                }
            }
            for flag in &opt.long_flags {
                if let Some(Some(_)) = parsed.options.get(flag) {
                    warnings.push(ValidationError {
                        error_type: ValidationErrorType::OptionUnexpectedArgument,
                        message: format!("Option {} does not take an argument", flag),
                        target: Some(flag.clone()),
                    });
                }
            }
        }
    }
}

/// Validate arguments in the parsed command.
fn validate_arguments(
    result: &ProbeResult,
    parsed: &ParsedArgs,
    errors: &mut Vec<ValidationError>,
    warnings: &mut Vec<ValidationError>,
) {
    let required_args: Vec<&ArgumentSpec> = result
        .arguments
        .iter()
        .filter(|a| a.required && !a.variadic)
        .collect();

    let variadic_args: Vec<&ArgumentSpec> =
        result.arguments.iter().filter(|a| a.variadic).collect();

    // Check required arguments
    let required_count = required_args.len();
    if parsed.positional_args.len() < required_count {
        errors.push(ValidationError {
            error_type: ValidationErrorType::TooFewArguments,
            message: format!(
                "Too few arguments: expected at least {}, got {}",
                required_count,
                parsed.positional_args.len()
            ),
            target: None,
        });
    }

    // Check variadic arguments (if any)
    if variadic_args.is_empty() && parsed.positional_args.len() > required_count {
        errors.push(ValidationError {
            error_type: ValidationErrorType::TooManyArguments,
            message: format!(
                "Too many arguments: expected {}, got {}",
                required_count,
                parsed.positional_args.len()
            ),
            target: None,
        });
    }

    // Validate argument types (basic checking)
    for (idx, arg_value) in parsed.positional_args.iter().enumerate() {
        if let Some(arg_spec) = result.arguments.get(idx) {
            if let Some(arg_type) = &arg_spec.arg_type {
                if !validate_argument_type(arg_value, arg_type) {
                    warnings.push(ValidationError {
                        error_type: ValidationErrorType::InvalidArgumentType,
                        message: format!(
                            "Argument '{}' may not match expected type {:?}",
                            arg_value, arg_type
                        ),
                        target: Some(arg_spec.name.clone()),
                    });
                }
            }
        }
    }
}

/// Validate that an argument value matches the expected type.
fn validate_argument_type(value: &str, arg_type: &ArgumentType) -> bool {
    match arg_type {
        ArgumentType::Number => value.parse::<f64>().is_ok() || value.parse::<i64>().is_ok(),
        ArgumentType::Path => {
            // Basic path validation - check if it looks like a path
            value.contains('/') || value.contains('\\') || !value.contains(' ')
        }
        ArgumentType::Url => value.starts_with("http://") || value.starts_with("https://"),
        ArgumentType::Email => value.contains('@') && value.contains('.'),
        ArgumentType::String => true, // Everything is a string
    }
}

/// Validate subcommands in the parsed command.
fn validate_subcommands(
    result: &ProbeResult,
    parsed: &ParsedArgs,
    errors: &mut Vec<ValidationError>,
    _warnings: &mut Vec<ValidationError>,
) {
    let known_subcommands: std::collections::HashSet<String> =
        result.subcommands.iter().map(|s| s.name.clone()).collect();

    for subcmd in &parsed.subcommands {
        if !known_subcommands.contains(subcmd) {
            errors.push(ValidationError {
                error_type: ValidationErrorType::UnknownSubcommand,
                message: format!("Unknown subcommand: {}", subcmd),
                target: Some(subcmd.clone()),
            });
        }
    }
}