json-structure 0.6.0

JSON Structure schema validation library for Rust
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
//! jstruct - JSON Structure CLI validator
//!
//! A command-line tool for validating JSON Structure schemas and instances.

use std::fs;
use std::io::{self, Read};
use std::path::PathBuf;
use std::process::ExitCode;

use clap::{Args, Parser, Subcommand, ValueEnum};
use serde::Serialize;

use json_structure::{InstanceValidator, SchemaValidator, SchemaValidatorOptions, ValidationResult};

/// Exit codes
const EXIT_SUCCESS: u8 = 0;
const EXIT_INVALID: u8 = 1;
const EXIT_ERROR: u8 = 2;

/// Output format for validation results
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
enum OutputFormat {
    /// Human-readable text output (default)
    #[default]
    Text,
    /// Machine-readable JSON output
    Json,
    /// Test Anything Protocol output
    Tap,
}

/// jstruct - JSON Structure schema and instance validator
#[derive(Parser)]
#[command(name = "jstruct")]
#[command(author = "JSON Structure Contributors")]
#[command(version)]
#[command(about = "JSON Structure schema and instance validator", long_about = None)]
#[command(propagate_version = true)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Check schema file(s) for validity
    #[command(alias = "c")]
    Check(CheckArgs),

    /// Validate instance file(s) against a schema
    #[command(alias = "v")]
    Validate(ValidateArgs),
}

#[derive(Args)]
struct CheckArgs {
    /// Schema file(s) to check. Use '-' to read from stdin.
    #[arg(required = true)]
    files: Vec<PathBuf>,

    /// Bundle file(s) containing schemas for $import resolution
    #[arg(short, long)]
    bundle: Vec<PathBuf>,

    /// Output format
    #[arg(short, long, value_enum, default_value_t = OutputFormat::Text)]
    format: OutputFormat,

    /// Suppress output, use exit code only
    #[arg(short, long)]
    quiet: bool,

    /// Show detailed validation information
    #[arg(short, long)]
    verbose: bool,
}

#[derive(Args)]
struct ValidateArgs {
    /// Schema file to validate against
    #[arg(short, long, required = true)]
    schema: PathBuf,

    /// Instance file(s) to validate. Use '-' to read from stdin.
    #[arg(required = true)]
    files: Vec<PathBuf>,

    /// Bundle file(s) containing schemas for $import resolution
    #[arg(short, long)]
    bundle: Vec<PathBuf>,

    /// Output format
    #[arg(short, long, value_enum, default_value_t = OutputFormat::Text)]
    format: OutputFormat,

    /// Suppress output, use exit code only
    #[arg(short, long)]
    quiet: bool,

    /// Show detailed validation information
    #[arg(short, long)]
    verbose: bool,
}

/// Result for a single file validation
#[derive(Debug, Serialize)]
struct FileResult {
    file: String,
    valid: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
    errors: Vec<ErrorInfo>,
    /// Source content for displaying excerpts (not serialized)
    #[serde(skip)]
    source_content: Option<String>,
}

/// Error information for JSON output
#[derive(Debug, Serialize)]
struct ErrorInfo {
    path: String,
    message: String,
    code: String,
    severity: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    line: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    column: Option<usize>,
}

fn main() -> ExitCode {
    let cli = Cli::parse();

    let exit_code = match cli.command {
        Commands::Check(args) => cmd_check(args),
        Commands::Validate(args) => cmd_validate(args),
    };

    ExitCode::from(exit_code)
}

/// Check schema files for validity
fn cmd_check(args: CheckArgs) -> u8 {
    // Load bundle schemas if provided
    let external_schemas = match load_bundle_schemas(&args.bundle, args.quiet) {
        Ok(schemas) => schemas,
        Err(_) => return EXIT_ERROR,
    };

    let options = SchemaValidatorOptions {
        allow_import: !external_schemas.is_empty(),
        external_schemas,
        ..SchemaValidatorOptions::default()
    };
    let validator = SchemaValidator::with_options(options);
    let mut results = Vec::new();
    let mut has_invalid = false;
    let mut has_error = false;

    for file in &args.files {
        let result = check_schema(&validator, file);
        
        if result.error.is_some() {
            has_error = true;
        } else if !result.valid {
            has_invalid = true;
        }
        
        results.push(result);
    }

    if !args.quiet {
        output_results(&results, args.format, args.verbose);
    }

    if has_error {
        EXIT_ERROR
    } else if has_invalid {
        EXIT_INVALID
    } else {
        EXIT_SUCCESS
    }
}

/// Validate instance files against a schema
fn cmd_validate(args: ValidateArgs) -> u8 {
    // Load bundle schemas if provided
    let external_schemas = match load_bundle_schemas(&args.bundle, args.quiet) {
        Ok(schemas) => schemas,
        Err(_) => return EXIT_ERROR,
    };

    let has_bundle = !external_schemas.is_empty();
    let schema_options = SchemaValidatorOptions {
        allow_import: has_bundle,
        external_schemas,
        ..SchemaValidatorOptions::default()
    };

    // Load and validate the schema first
    let schema_content = match read_file(&args.schema) {
        Ok(content) => content,
        Err(e) => {
            if !args.quiet {
                eprintln!("jstruct: cannot read schema '{}': {}", args.schema.display(), e);
            }
            return EXIT_ERROR;
        }
    };

    // Parse the schema
    let schema: serde_json::Value = match serde_json::from_str(&schema_content) {
        Ok(v) => v,
        Err(e) => {
            if !args.quiet {
                eprintln!("jstruct: invalid JSON in schema '{}': {}", args.schema.display(), e);
            }
            return EXIT_ERROR;
        }
    };

    // Validate the schema first
    let schema_validator = SchemaValidator::with_options(schema_options);
    let schema_result = schema_validator.validate(&schema_content);
    if !schema_result.is_valid() {
        if !args.quiet {
            let first_error = schema_result.errors().next()
                .map(|e| e.message.as_str())
                .unwrap_or("unknown error");
            eprintln!("jstruct: invalid schema '{}': {}", args.schema.display(), first_error);
        }
        return EXIT_ERROR;
    }

    let instance_validator = InstanceValidator::new();
    let mut results = Vec::new();
    let mut has_invalid = false;
    let mut has_error = false;

    for file in &args.files {
        let result = validate_instance(&instance_validator, file, &schema);
        
        if result.error.is_some() {
            has_error = true;
        } else if !result.valid {
            has_invalid = true;
        }
        
        results.push(result);
    }

    if !args.quiet {
        output_results(&results, args.format, args.verbose);
    }

    if has_error {
        EXIT_ERROR
    } else if has_invalid {
        EXIT_INVALID
    } else {
        EXIT_SUCCESS
    }
}

/// Load schemas from bundle files for $import resolution
fn load_bundle_schemas(bundle_files: &[PathBuf], quiet: bool) -> Result<Vec<serde_json::Value>, ()> {
    let mut schemas = Vec::new();
    
    for file in bundle_files {
        let content = match read_file(file) {
            Ok(c) => c,
            Err(e) => {
                if !quiet {
                    eprintln!("jstruct: cannot read bundle file '{}': {}", file.display(), e);
                }
                return Err(());
            }
        };
        
        let schema: serde_json::Value = match serde_json::from_str(&content) {
            Ok(v) => v,
            Err(e) => {
                if !quiet {
                    eprintln!("jstruct: invalid JSON in bundle file '{}': {}", file.display(), e);
                }
                return Err(());
            }
        };
        
        schemas.push(schema);
    }
    
    Ok(schemas)
}

/// Check a single schema file
fn check_schema(validator: &SchemaValidator, file: &PathBuf) -> FileResult {
    let file_name = if file.as_os_str() == "-" {
        "<stdin>".to_string()
    } else {
        file.display().to_string()
    };

    let content = match read_file(file) {
        Ok(c) => c,
        Err(e) => {
            return FileResult {
                file: file_name,
                valid: false,
                error: Some(e.to_string()),
                errors: vec![],
                source_content: None,
            };
        }
    };

    let result = validator.validate(&content);
    validation_result_to_file_result(&file_name, result, Some(content))
}

/// Validate a single instance file
fn validate_instance(
    validator: &InstanceValidator,
    file: &PathBuf,
    schema: &serde_json::Value,
) -> FileResult {
    let file_name = if file.as_os_str() == "-" {
        "<stdin>".to_string()
    } else {
        file.display().to_string()
    };

    let content = match read_file(file) {
        Ok(c) => c,
        Err(e) => {
            return FileResult {
                file: file_name,
                valid: false,
                error: Some(e.to_string()),
                errors: vec![],
                source_content: None,
            };
        }
    };

    let result = validator.validate(&content, schema);
    validation_result_to_file_result(&file_name, result, Some(content))
}

/// Convert ValidationResult to FileResult
fn validation_result_to_file_result(file: &str, result: ValidationResult, source_content: Option<String>) -> FileResult {
    let errors: Vec<ErrorInfo> = result
        .all_errors()
        .iter()
        .map(|e| ErrorInfo {
            path: e.path.clone(),
            message: e.message.clone(),
            code: e.code.clone(),
            severity: e.severity.to_string(),
            line: if e.location.is_unknown() {
                None
            } else {
                Some(e.location.line)
            },
            column: if e.location.is_unknown() {
                None
            } else {
                Some(e.location.column)
            },
        })
        .collect();

    FileResult {
        file: file.to_string(),
        valid: result.is_valid(),
        error: None,
        errors,
        source_content,
    }
}

/// Read file contents, handling stdin ("-")
fn read_file(path: &PathBuf) -> io::Result<String> {
    if path.as_os_str() == "-" {
        let mut buffer = String::new();
        io::stdin().read_to_string(&mut buffer)?;
        Ok(buffer)
    } else {
        fs::read_to_string(path)
    }
}

/// Output results in the specified format
fn output_results(results: &[FileResult], format: OutputFormat, verbose: bool) {
    match format {
        OutputFormat::Text => output_text(results, verbose),
        OutputFormat::Json => output_json(results),
        OutputFormat::Tap => output_tap(results, verbose),
    }
}

/// Output results as human-readable text
fn output_text(results: &[FileResult], verbose: bool) {
    // Pre-compute source lines for all results that have source content
    let source_lines: Vec<Option<Vec<&str>>> = results
        .iter()
        .map(|r| r.source_content.as_ref().map(|s| s.lines().collect()))
        .collect();

    for (idx, result) in results.iter().enumerate() {
        if let Some(ref error) = result.error {
            println!("\u{2717} {}: {}", result.file, error);
        } else if result.valid {
            println!("\u{2713} {}: valid", result.file);
        } else {
            println!("\u{2717} {}: invalid", result.file);
            let lines = source_lines[idx].as_ref();
            for error in &result.errors {
                let path = if error.path.is_empty() { "/" } else { &error.path };
                let severity_icon = if error.severity == "warning" { "\u{26A0}" } else { "\u{2717}" };
                
                // Always show line/column when available
                let loc = error.line.map(|l| {
                    format!(" (line {}, col {})", l, error.column.unwrap_or(0))
                }).unwrap_or_default();
                
                println!("  {} [{}] {}: {}{}", severity_icon, error.code, path, error.message, loc);
                
                // In verbose mode, show source excerpt with caret marker
                if verbose {
                    if let (Some(line_num), Some(col), Some(src_lines)) = (error.line, error.column, lines) {
                        if line_num > 0 && line_num <= src_lines.len() {
                            let source_line = src_lines[line_num - 1];
                            println!("    |");
                            println!("  {} | {}", line_num, source_line);
                            // Create caret marker at the column position
                            let line_num_width = line_num.to_string().len();
                            let padding = " ".repeat(line_num_width + col);
                            println!("    |{}^", padding);
                        }
                    }
                }
            }
        }
    }
}

/// Output results as JSON
fn output_json(results: &[FileResult]) {
    let output = if results.len() == 1 {
        serde_json::to_string_pretty(&results[0]).unwrap()
    } else {
        serde_json::to_string_pretty(results).unwrap()
    };
    println!("{}", output);
}

/// Output results in TAP format
fn output_tap(results: &[FileResult], verbose: bool) {
    println!("1..{}", results.len());
    
    // Pre-compute source lines for all results that have source content
    let source_lines: Vec<Option<Vec<&str>>> = results
        .iter()
        .map(|r| r.source_content.as_ref().map(|s| s.lines().collect()))
        .collect();
    
    for (i, result) in results.iter().enumerate() {
        let n = i + 1;
        
        if let Some(ref error) = result.error {
            println!("not ok {} - {}", n, result.file);
            println!("  # {}", error);
        } else if result.valid {
            println!("ok {} - {}", n, result.file);
        } else {
            println!("not ok {} - {}", n, result.file);
            let lines = source_lines[i].as_ref();
            for error in &result.errors {
                let path = if error.path.is_empty() { "/" } else { &error.path };
                let severity = if error.severity == "warning" { "warning" } else { "error" };
                
                // Always show line/column when available
                let loc = error.line.map(|l| {
                    format!(" (line {}, col {})", l, error.column.unwrap_or(0))
                }).unwrap_or_default();
                
                println!("  # [{}] {} {}: {}{}", error.code, severity, path, error.message, loc);
                
                // In verbose mode, show source excerpt
                if verbose {
                    if let (Some(line_num), Some(src_lines)) = (error.line, lines) {
                        if line_num > 0 && line_num <= src_lines.len() {
                            let source_line = src_lines[line_num - 1];
                            println!("  #   > {}", source_line);
                            if let Some(col) = error.column {
                                let padding = " ".repeat(col.saturating_sub(1));
                                println!("  #   > {}^", padding);
                            }
                        }
                    }
                }
            }
        }
    }
}