mabi-cli 1.7.0

Mabinogion - Industrial Protocol Simulator CLI
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
//! Validate command implementation.
//!
//! Validates scenario and configuration files.

use crate::context::CliContext;
use crate::error::{CliError, CliResult};
use crate::output::{
    StatusType, TableBuilder, ValidationError, ValidationResult, ValidationWarning,
};
use crate::runner::{Command, CommandOutput};
use crate::runner_contract::{is_machine_format, write_failure, write_success, CliErrorPayload};
use async_trait::async_trait;
use mabi_scenario::Scenario;
use serde::Serialize;
use std::path::PathBuf;

/// Validate command for checking configuration files.
pub struct ValidateCommand {
    /// Paths to validate.
    paths: Vec<PathBuf>,
    /// Whether to show detailed output.
    detailed: bool,
    /// Whether to check for warnings only (no errors = success).
    strict: bool,
}

#[derive(Debug, Clone, Serialize)]
struct ConfigValidationFileReport {
    path: String,
    valid: bool,
    errors: Vec<ValidationError>,
    warnings: Vec<ValidationWarning>,
}

#[derive(Debug, Clone, Serialize)]
struct ConfigValidationReport {
    total_files: usize,
    valid_files: usize,
    errors: usize,
    warnings: usize,
    strict: bool,
    files: Vec<ConfigValidationFileReport>,
}

impl ValidateCommand {
    /// Create a new validate command.
    pub fn new(paths: Vec<PathBuf>) -> Self {
        Self {
            paths,
            detailed: false,
            strict: false,
        }
    }

    /// Enable detailed output.
    pub fn with_detailed(mut self, detailed: bool) -> Self {
        self.detailed = detailed;
        self
    }

    /// Enable strict mode (warnings become errors).
    pub fn with_strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }

    /// Validate a single file.
    async fn validate_file(&self, ctx: &CliContext, path: &PathBuf) -> ValidationResult {
        let resolved_path = ctx.resolve_path(path);
        let mut errors = Vec::new();
        let mut warnings = Vec::new();

        // Check file exists
        if !resolved_path.exists() {
            errors.push(ValidationError {
                path: path.display().to_string(),
                message: "File not found".into(),
            });
            return ValidationResult {
                valid: false,
                errors,
                warnings,
            };
        }

        // Read file content
        let content = match tokio::fs::read_to_string(&resolved_path).await {
            Ok(c) => c,
            Err(e) => {
                errors.push(ValidationError {
                    path: path.display().to_string(),
                    message: format!("Failed to read file: {}", e),
                });
                return ValidationResult {
                    valid: false,
                    errors,
                    warnings,
                };
            }
        };

        // Determine file type and validate
        let extension = resolved_path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");

        match extension {
            "yaml" | "yml" => {
                self.validate_yaml(&content, path, &mut errors, &mut warnings);
            }
            "json" => {
                self.validate_json(&content, path, &mut errors, &mut warnings);
            }
            "toml" => {
                self.validate_toml(&content, path, &mut errors, &mut warnings);
            }
            _ => {
                warnings.push(ValidationWarning {
                    path: path.display().to_string(),
                    message: format!("Unknown file extension: {}", extension),
                });
            }
        }

        // Check for scenario-specific validation
        if content.contains("devices:") || content.contains("\"devices\"") {
            self.validate_scenario_content(&content, path, &mut errors, &mut warnings);
        }

        let valid = errors.is_empty() && (!self.strict || warnings.is_empty());

        ValidationResult {
            valid,
            errors,
            warnings,
        }
    }

    /// Validate YAML content.
    fn validate_yaml(
        &self,
        content: &str,
        path: &PathBuf,
        errors: &mut Vec<ValidationError>,
        _warnings: &mut Vec<ValidationWarning>,
    ) {
        if let Err(e) = serde_yaml::from_str::<serde_yaml::Value>(content) {
            errors.push(ValidationError {
                path: path.display().to_string(),
                message: format!("Invalid YAML: {}", e),
            });
        }
    }

    /// Validate JSON content.
    fn validate_json(
        &self,
        content: &str,
        path: &PathBuf,
        errors: &mut Vec<ValidationError>,
        _warnings: &mut Vec<ValidationWarning>,
    ) {
        if let Err(e) = serde_json::from_str::<serde_json::Value>(content) {
            errors.push(ValidationError {
                path: path.display().to_string(),
                message: format!("Invalid JSON: {}", e),
            });
        }
    }

    /// Validate TOML content.
    fn validate_toml(
        &self,
        content: &str,
        path: &PathBuf,
        errors: &mut Vec<ValidationError>,
        _warnings: &mut Vec<ValidationWarning>,
    ) {
        if let Err(e) = toml::from_str::<toml::Value>(content) {
            errors.push(ValidationError {
                path: path.display().to_string(),
                message: format!("Invalid TOML: {}", e),
            });
        }
    }

    /// Validate scenario-specific content.
    fn validate_scenario_content(
        &self,
        content: &str,
        path: &PathBuf,
        errors: &mut Vec<ValidationError>,
        warnings: &mut Vec<ValidationWarning>,
    ) {
        // Try to parse as scenario
        if let Ok(scenario) = serde_yaml::from_str::<Scenario>(content) {
            // Validate scenario fields
            if scenario.name.is_empty() {
                errors.push(ValidationError {
                    path: path.display().to_string(),
                    message: "Scenario name is required".into(),
                });
            }

            if scenario.devices.is_empty() {
                warnings.push(ValidationWarning {
                    path: path.display().to_string(),
                    message: "Scenario has no devices".into(),
                });
            }

            // Validate devices
            for (idx, device) in scenario.devices.iter().enumerate() {
                if device.id.is_empty() {
                    errors.push(ValidationError {
                        path: format!("{}:devices[{}]", path.display(), idx),
                        message: "Device ID is required".into(),
                    });
                }

                if device.protocol.is_empty() {
                    errors.push(ValidationError {
                        path: format!("{}:devices[{}]", path.display(), idx),
                        message: "Device protocol is required".into(),
                    });
                }

                // Validate protocol
                let valid_protocols = ["modbus_tcp", "modbus_rtu", "opcua", "bacnet", "knx"];
                if !valid_protocols.contains(&device.protocol.to_lowercase().as_str()) {
                    warnings.push(ValidationWarning {
                        path: format!("{}:devices[{}]", path.display(), idx),
                        message: format!("Unknown protocol: {}", device.protocol),
                    });
                }
            }

            // Validate scenario points
            for (idx, point) in scenario.points.iter().enumerate() {
                if point.id.is_empty() {
                    errors.push(ValidationError {
                        path: format!("{}:points[{}]", path.display(), idx),
                        message: "Point ID is required".into(),
                    });
                }

                if point.point_id.is_empty() {
                    errors.push(ValidationError {
                        path: format!("{}:points[{}]", path.display(), idx),
                        message: "Target point_id is required".into(),
                    });
                }

                if point.device_id.is_empty() && point.device_tags.is_empty() {
                    warnings.push(ValidationWarning {
                        path: format!("{}:points[{}]", path.display(), idx),
                        message: "Point has neither device_id nor device_tags".into(),
                    });
                }
            }
        }
    }
}

#[async_trait]
impl Command for ValidateCommand {
    fn name(&self) -> &str {
        "validate"
    }

    fn description(&self) -> &str {
        "Validate scenario and configuration files"
    }

    fn validate(&self) -> CliResult<()> {
        if self.paths.is_empty() {
            return Err(CliError::InvalidConfig {
                message: "At least one file path is required".into(),
            });
        }
        Ok(())
    }

    async fn execute(&self, ctx: &mut CliContext) -> CliResult<CommandOutput> {
        let output = ctx.output();
        let machine_output = is_machine_format(output.format());
        let mut all_valid = true;
        let mut results = Vec::new();

        if !machine_output {
            output.header("Validating Files");
        }

        for path in &self.paths {
            let result = self.validate_file(ctx, path).await;
            if !result.valid {
                all_valid = false;
            }
            results.push((path.clone(), result));
        }

        let total = results.len();
        let valid_count = results.iter().filter(|(_, r)| r.valid).count();
        let error_count: usize = results.iter().map(|(_, r)| r.errors.len()).sum();
        let warning_count: usize = results.iter().map(|(_, r)| r.warnings.len()).sum();
        let report = ConfigValidationReport {
            total_files: total,
            valid_files: valid_count,
            errors: error_count,
            warnings: warning_count,
            strict: self.strict,
            files: results
                .iter()
                .map(|(path, result)| ConfigValidationFileReport {
                    path: path.display().to_string(),
                    valid: result.valid,
                    errors: result.errors.clone(),
                    warnings: result.warnings.clone(),
                })
                .collect(),
        };

        if machine_output {
            if all_valid {
                write_success(output, "validate config", &report)?;
                return Ok(CommandOutput::quiet_success());
            }

            let mut errors = Vec::new();
            for file in &report.files {
                for error in &file.errors {
                    errors.push(
                        CliErrorPayload::new(6, "validation_error", error.message.clone())
                            .with_path(error.path.clone()),
                    );
                }
                if file.errors.is_empty() && !file.valid {
                    errors.push(
                        CliErrorPayload::new(6, "validation_error", "file failed validation")
                            .with_path(file.path.clone()),
                    );
                }
            }
            if errors.is_empty() {
                errors.push(CliErrorPayload::new(
                    6,
                    "validation_error",
                    "one or more files failed validation",
                ));
            }
            write_failure(output, "validate config", 6, &report, errors)?;
            return Ok(CommandOutput::quiet_failure(6));
        }

        // Display results
        if self.detailed {
            for (path, result) in &results {
                output.kv("File", path.display());

                if result.errors.is_empty() && result.warnings.is_empty() {
                    output.success("  Valid");
                } else {
                    for error in &result.errors {
                        output.error(format!("  {}: {}", error.path, error.message));
                    }
                    for warning in &result.warnings {
                        output.warning(format!("  {}: {}", warning.path, warning.message));
                    }
                }
                println!();
            }
        } else {
            // Summary table
            let mut table = TableBuilder::new(output.colors_enabled())
                .header(["File", "Errors", "Warnings", "Status"]);

            for (path, result) in &results {
                let status = if result.valid { "Valid" } else { "Invalid" };
                let status_type = if result.valid {
                    StatusType::Success
                } else {
                    StatusType::Error
                };

                table = table.status_row(
                    [
                        path.display().to_string(),
                        result.errors.len().to_string(),
                        result.warnings.len().to_string(),
                        status.to_string(),
                    ],
                    status_type,
                );
            }
            table.print();
        }

        // Summary
        println!();
        output.kv("Total files", total);
        output.kv("Valid", valid_count);
        output.kv("Errors", error_count);
        output.kv("Warnings", warning_count);

        if all_valid {
            output.success("All files are valid");
            Ok(CommandOutput::quiet_success())
        } else {
            Err(CliError::ValidationFailed {
                errors: format!("{} file(s) failed validation", total - valid_count),
            })
        }
    }
}