raz-validation 0.2.4

Smart options validation system for raz
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
# Raz Validation Documentation

The `raz-validation` crate provides intelligent command-line option validation for the Raz ecosystem.

## Table of Contents

- [Overview]#overview
- [Architecture]#architecture
- [Getting Started]#getting-started
- [Built-in Providers]#built-in-providers
- [Creating Custom Providers]#creating-custom-providers
- [Validation Levels]#validation-levels
- [Error Handling]#error-handling
- [Integration Patterns]#integration-patterns
- [Performance Considerations]#performance-considerations
- [API Reference]#api-reference

## Overview

Raz Validation solves the problem of providing immediate, helpful feedback for command-line options without waiting for tool execution. Instead of generic "unknown option" errors, users get contextual suggestions and framework-aware validation.

### Key Benefits

- **Immediate Feedback** - Catch errors before cargo/tool execution
- **Context-Aware** - Knows which options work with which commands
- **Framework Support** - Built-in knowledge of Cargo, Leptos, Dioxus
- **Smart Suggestions** - "Did you mean --release?" error messages
- **Extensible** - Easy to add new tools and frameworks

## Architecture

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│ ValidationEngine│────│ValidationRegistry│────│  OptionProvider │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         │              ┌─────────────────┐              │
         └──────────────│OptionSuggester │              │
                        └─────────────────┘              │
                                              ┌─────────────────┐
                                              │ CargoProvider   │
                                              │ LeptosProvider  │
                                              │ CustomProvider  │
                                              └─────────────────┘
```

### Core Components

- **ValidationEngine** - Main API entry point
- **ValidationRegistry** - Manages multiple providers
- **OptionProvider** - Interface for tool-specific validation
- **OptionSuggester** - Fuzzy matching for suggestions

## Getting Started

### Basic Usage

```rust
use raz_validation::{ValidationEngine, ValidationConfig, ValidationLevel};

// Create engine with default providers
let engine = ValidationEngine::new();

// Validate options
match engine.validate_option("build", "--release", None) {
    Ok(_) => println!("Valid option"),
    Err(e) => println!("Error: {}", e),
}

// Get suggestions for typos
let suggestions = engine.suggest_option("build", "--relase");
// suggestions: ["--release"]
```

### With Custom Configuration

```rust
let config = ValidationConfig::with_level(ValidationLevel::Strict)
    .add_provider("dioxus")
    .with_suggestion_threshold(50);

let engine = ValidationEngine::with_config(config);
```

### Integration with Override Parser

```rust
use raz_override::parser::override_parser::OverrideParser;

let parser = OverrideParser::with_validation_config("build", config);
let parsed = parser.parse("--release --features serde").unwrap();

// Validation happens automatically
parser.validate(&parsed)?;
```

## Built-in Providers

### CargoProvider

Supports all major cargo commands with comprehensive option definitions:

**Commands:**
- `build`, `test`, `run`, `check`, `clippy`, `doc`, `clean`, `bench`, `install`, `publish`

**Key Options:**
- `--release`, `--dev` - Build modes
- `--features`, `--all-features`, `--no-default-features` - Feature flags
- `--target` - Target triple
- `--bin`, `--lib`, `--bins` - Target selection (with conflict detection)
- `--jobs`, `-j` - Parallel jobs (with number validation)

**Example:**
```rust
// Valid cargo options
engine.validate_option("build", "--release", None)?;
engine.validate_option("build", "--features", Some("serde,tokio"))?;
engine.validate_option("test", "--nocapture", None)?;

// Conflict detection
engine.validate_options("build", &HashMap::from([
    ("--lib".to_string(), None),
    ("--bin".to_string(), Some("myapp".to_string())), // Error: conflicts with --lib
]))?;
```

### LeptosProvider

Supports Leptos framework commands with specialized options:

**Commands:**
- `leptos build`, `leptos serve`, `leptos watch`, `leptos new`, `leptos end-to-end`

**Key Options:**
- `--bin-features`, `--lib-features` - Separate feature sets for binary and library
- `--hot-reload`, `--reload-port` - Development features
- `--precompress` - Asset optimization
- `--template` - Project templates

**Example:**
```rust
// Leptos-specific options
engine.validate_option("leptos build", "--bin-features", Some("ssr"))?;
engine.validate_option("leptos serve", "--hot-reload", None)?;
engine.validate_option("leptos new", "--template", Some("start-axum"))?;
```

## Creating Custom Providers

### Basic Provider

```rust
use raz_validation::provider::{OptionProvider, OptionDef, ValueValidator};

struct MyToolProvider;

impl OptionProvider for MyToolProvider {
    fn name(&self) -> &str {
        "mytool"
    }

    fn get_options(&self, command: &str) -> Vec<OptionDef> {
        match command {
            "mytool build" => vec![
                OptionDef::flag("--verbose", "Enable verbose output"),
                OptionDef::single("--output", "Output file", ValueValidator::FilePath),
                OptionDef::multiple("--exclude", "Exclude patterns", ValueValidator::Any),
            ],
            _ => vec![],
        }
    }

    fn validate(&self, command: &str, option: &str, value: Option<&str>) -> ValidationResult<()> {
        // Custom validation logic
        Ok(())
    }

    fn get_commands(&self) -> Vec<String> {
        vec!["mytool build".to_string(), "mytool test".to_string()]
    }
}
```

### Advanced Provider with Value Validation

```rust
impl OptionProvider for AdvancedProvider {
    fn validate(&self, command: &str, option: &str, value: Option<&str>) -> ValidationResult<()> {
        match (option, value) {
            ("--port", Some(port)) => {
                let port_num: u16 = port.parse()
                    .map_err(|_| ValidationError::invalid_value(option, port, "must be a number"))?;
                
                if port_num < 1024 {
                    return Err(ValidationError::invalid_value(
                        option, port, "port must be >= 1024 for non-root users"
                    ));
                }
                Ok(())
            }
            ("--level", Some(level)) => {
                if !["debug", "info", "warn", "error"].contains(&level) {
                    return Err(ValidationError::invalid_value(
                        option, level, "must be one of: debug, info, warn, error"
                    ));
                }
                Ok(())
            }
            _ => Ok(()),
        }
    }
}
```

### Registering Custom Providers

```rust
let mut engine = ValidationEngine::new();
engine.register_provider(Box::new(MyToolProvider));

// Now can validate mytool options
engine.validate_option("mytool build", "--verbose", None)?;
```

## Validation Levels

### ValidationLevel::Off
- **Behavior**: No validation performed
- **Use Case**: Maximum compatibility, performance-critical paths
- **Returns**: Always `Ok(())`

```rust
let config = ValidationConfig::with_level(ValidationLevel::Off);
let engine = ValidationEngine::with_config(config);

// Always passes
engine.validate_option("any-command", "--any-option", Some("any-value"))?;
```

### ValidationLevel::Normal (Default)
- **Behavior**: Validate known options, allow unknown ones
- **Use Case**: Development, helpful feedback without blocking
- **Returns**: Errors for invalid values, warnings for unknown options

```rust
// Known option with invalid value -> Error
let result = engine.validate_option("build", "--jobs", Some("abc"));
assert!(result.is_err());

// Unknown option -> Warning (but still Ok)
let result = engine.validate_option("build", "--unknown-flag", None);
assert!(result.is_ok());
```

### ValidationLevel::Strict
- **Behavior**: Reject unknown options with suggestions
- **Use Case**: Production, CI/CD, strict environments
- **Returns**: Errors for any unrecognized options

```rust
let config = ValidationConfig::with_level(ValidationLevel::Strict);
let engine = ValidationEngine::with_config(config);

// Unknown option -> Error with suggestions
let result = engine.validate_option("build", "--relase", None);
assert!(result.is_err());
// Error message: "Unknown option '--relase' for command 'build'. Did you mean: --release"
```

## Error Handling

### Error Types

```rust
use raz_validation::ValidationError;

match engine.validate_option("build", "--invalid", Some("value")) {
    Err(ValidationError::UnknownOption { command, option, suggestions }) => {
        println!("Unknown option '{}' for command '{}'", option, command);
        if !suggestions.is_empty() {
            println!("Did you mean: {}", suggestions.join(", "));
        }
    }
    Err(ValidationError::InvalidValue { option, value, reason }) => {
        println!("Invalid value '{}' for option '{}': {}", value, option, reason);
    }
    Err(ValidationError::OptionConflict { option, conflicts_with }) => {
        println!("Option '{}' conflicts with '{}'", option, conflicts_with);
    }
    Ok(_) => println!("Valid option"),
}
```

### Formatted Error Messages

```rust
let error = ValidationError::unknown_option("build", "--relase", vec!["--release".to_string()]);
println!("{}", error.format_with_suggestions());
// Output: "Unknown option '--relase' for command 'build'\nDid you mean: --release"
```

## Integration Patterns

### With Override System

```rust
use raz_override::parser::override_parser::OverrideParser;
use raz_validation::{ValidationConfig, ValidationLevel};

// Create parser with validation
let config = ValidationConfig::with_level(ValidationLevel::Normal);
let parser = OverrideParser::with_validation_config("build", config);

// Parse and validate in one step
let parsed = parser.parse("--release --features serde,tokio")?;
parser.validate(&parsed)?;

// Get suggestions for errors
if let Err(e) = parser.validate(&parsed) {
    let suggestions = parser.suggest_option("--relase");
    println!("Error: {}. Suggestions: {}", e, suggestions.join(", "));
}
```

### With CLI Applications

```rust
use clap::Parser;
use raz_validation::{ValidationEngine, ValidationLevel};

#[derive(Parser)]
struct Args {
    #[clap(long)]
    command: String,
    
    #[clap(long)]
    options: Vec<String>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args = Args::parse();
    let engine = ValidationEngine::new();
    
    // Validate each option
    for option in &args.options {
        engine.validate_option(&args.command, option, None)?;
    }
    
    println!("All options are valid!");
    Ok(())
}
```

### Batch Validation

```rust
use std::collections::HashMap;

let options = HashMap::from([
    ("--release".to_string(), None),
    ("--features".to_string(), Some("serde,tokio".to_string())),
    ("--target".to_string(), Some("x86_64-unknown-linux-gnu".to_string())),
]);

// Validate all options at once
engine.validate_options("build", &options)?;
```

## Performance Considerations

### Lazy Loading
- Option definitions are loaded only when needed
- Providers are initialized on first use
- Suggestion matching is optimized for common cases

### Caching Strategy
```rust
// Engine reuse is recommended
let engine = ValidationEngine::new(); // Initialize once

// Reuse for multiple validations
for option in options {
    engine.validate_option("build", option, None)?;
}
```

### Memory Usage
- Minimal overhead in `Off` and `Minimal` modes
- Option definitions cached per provider
- Fuzzy matcher uses efficient algorithms

### Benchmarks
```bash
# Run benchmarks
cargo bench -p raz-validation

# Typical performance:
# - Option validation: ~1-5μs
# - Suggestion generation: ~10-50μs
# - Provider lookup: ~100ns
```

## API Reference

### ValidationEngine

```rust
impl ValidationEngine {
    pub fn new() -> Self;
    pub fn with_config(config: ValidationConfig) -> Self;
    
    pub fn validate_option(&self, command: &str, option: &str, value: Option<&str>) -> ValidationResult<()>;
    pub fn validate_options(&self, command: &str, options: &HashMap<String, Option<String>>) -> ValidationResult<()>;
    pub fn suggest_option(&self, command: &str, option: &str) -> Vec<String>;
    
    pub fn register_provider(&mut self, provider: Box<dyn OptionProvider>);
    pub fn get_options(&self, command: &str) -> Vec<OptionDef>;
}
```

### ValidationConfig

```rust
impl ValidationConfig {
    pub fn with_level(level: ValidationLevel) -> Self;
    pub fn add_provider(self, provider: impl Into<String>) -> Self;
    pub fn with_suggestion_threshold(self, threshold: i64) -> Self;
    
    pub fn is_provider_enabled(&self, provider: &str) -> bool;
}
```

### OptionProvider Trait

```rust
pub trait OptionProvider: Send + Sync {
    fn name(&self) -> &str;
    fn get_options(&self, command: &str) -> Vec<OptionDef>;
    fn validate(&self, command: &str, option: &str, value: Option<&str>) -> ValidationResult<()>;
    fn get_commands(&self) -> Vec<String>;
    fn supports_command(&self, command: &str) -> bool;
}
```

### OptionDef Builder

```rust
impl OptionDef {
    pub fn flag(name: impl Into<String>, description: impl Into<String>) -> Self;
    pub fn single(name: impl Into<String>, description: impl Into<String>, validator: ValueValidator) -> Self;
    pub fn multiple(name: impl Into<String>, description: impl Into<String>, validator: ValueValidator) -> Self;
    
    pub fn conflicts_with(self, options: Vec<String>) -> Self;
    pub fn requires(self, options: Vec<String>) -> Self;
    pub fn deprecated(self, message: impl Into<String>) -> Self;
    pub fn repeatable(self) -> Self;
}
```