schemaorg-validate 0.2.0

Parse and validate Schema.org structured data (JSON-LD, Microdata, RDFa) against the official vocabulary and Google Rich Results profiles.
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
//! `schemaorg-validate` -- CLI for Schema.org structured data validation.
//!
//! Validates HTML files, URLs, or stdin input against the Schema.org vocabulary
//! and optional Rich Results profiles (Google, baseline).

use std::collections::HashSet;
use std::io::Read;
use std::process::ExitCode;

use clap::{Parser, ValueEnum};

use schemaorg_rs::profiles::{Eligibility, ProfileRegistry, ProfileResult};
use schemaorg_rs::validation::diagnostics::{Severity, ValidationDiagnostic};
use schemaorg_rs::validation::ValidationResult;
use schemaorg_rs::{extract_all, validation, vocabulary};

/// Errors that can occur during CLI execution.
#[derive(Debug, thiserror::Error)]
enum CliError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    #[error("http error: {0}")]
    Http(#[from] Box<ureq::Error>),

    #[error("extraction failed: {0}")]
    Extraction(#[from] schemaorg_rs::ExtractionError),

    #[error("profile error: {0}")]
    Profile(#[from] schemaorg_rs::ProfileError),

    #[error("{0}")]
    InvalidInput(String),
}

/// Validate Schema.org structured data in HTML.
///
/// Extracts JSON-LD, Microdata, and RDFa Lite structured data from HTML,
/// validates it against the Schema.org vocabulary, and optionally checks
/// Google Rich Results eligibility.
#[derive(Parser)]
#[command(
    name = "schemaorg-validate",
    version,
    about = "Validate Schema.org structured data in HTML"
)]
struct Cli {
    /// Local HTML file to validate
    #[arg(long, group = "input")]
    file: Option<std::path::PathBuf>,

    /// URL to fetch and validate
    #[arg(long, group = "input")]
    url: Option<String>,

    /// Read HTML from stdin
    #[arg(long, group = "input")]
    stdin: bool,

    /// Validation profile
    #[arg(long, default_value = "google", value_enum)]
    profile: ProfileChoice,

    /// Output format
    #[arg(long, default_value = "text", value_enum)]
    format: OutputFormat,

    /// Minimum severity to display
    #[arg(long, default_value = "warning", value_enum)]
    severity: SeverityFilter,

    /// Disable colored output
    #[arg(long)]
    no_color: bool,

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

    /// Print vendored Schema.org version
    #[arg(long)]
    schema_version: bool,
}

/// Validation profile selection.
#[derive(Clone, ValueEnum)]
enum ProfileChoice {
    /// Google Rich Results profiles
    Google,
    /// Generic Schema.org best-practice profile
    Baseline,
    /// Skip profile evaluation (vocabulary validation only)
    None,
}

/// Output format selection.
#[derive(Clone, ValueEnum)]
enum OutputFormat {
    /// Human-readable text with colors
    Text,
    /// Structured JSON
    Json,
    /// SARIF 2.1.0 (for GitHub Code Scanning)
    Sarif,
}

/// Minimum severity filter.
#[derive(Clone, ValueEnum)]
enum SeverityFilter {
    /// Show only errors
    Error,
    /// Show errors and warnings
    Warning,
    /// Show everything
    Info,
}

impl SeverityFilter {
    const fn passes(&self, severity: Severity) -> bool {
        match self {
            Self::Error => matches!(severity, Severity::Error),
            Self::Warning => matches!(severity, Severity::Error | Severity::Warning),
            Self::Info => true,
        }
    }
}

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

    if cli.schema_version {
        println!("Schema.org v{}", vocabulary::schema_version());
        return ExitCode::SUCCESS;
    }

    match run(&cli) {
        Ok(has_errors) => {
            if has_errors {
                ExitCode::from(1)
            } else {
                ExitCode::SUCCESS
            }
        }
        Err(e) => {
            eprintln!("Error: {e}");
            ExitCode::from(2)
        }
    }
}

/// Core pipeline: read input -> extract -> validate -> profile -> output.
///
/// Returns `Ok(true)` if validation errors were found, `Ok(false)` if clean.
fn run(cli: &Cli) -> Result<bool, CliError> {
    let (html, source_name) = read_input(cli)?;

    // 1. Extract structured data
    let graph = extract_all(&html)?;

    // 2. Validate against vocabulary
    let vocab_result = validation::validate(&graph);

    // 3. Evaluate against profile (if requested)
    let profile_result = match cli.profile {
        ProfileChoice::Google => {
            let registry = ProfileRegistry::with_google();
            Some(registry.evaluate("google", &graph, &vocab_result.diagnostics)?)
        }
        ProfileChoice::Baseline => {
            let registry = ProfileRegistry::with_baseline();
            Some(registry.evaluate("baseline", &graph, &vocab_result.diagnostics)?)
        }
        ProfileChoice::None => None,
    };

    // 4. Format and output
    if !cli.quiet {
        match cli.format {
            OutputFormat::Text => {
                format_text(&vocab_result, profile_result.as_ref(), &source_name, cli);
            }
            OutputFormat::Json => {
                format_json(&vocab_result, profile_result.as_ref(), &source_name, &graph)?;
            }
            OutputFormat::Sarif => {
                format_sarif(&vocab_result, profile_result.as_ref(), &source_name)?;
            }
        }
    }

    // 5. Determine exit: errors present?
    let has_vocab_errors = vocab_result.has_errors();
    let has_profile_errors = profile_result
        .as_ref()
        .is_some_and(|pr| pr.eligibility == Eligibility::NotEligible);

    Ok(has_vocab_errors || has_profile_errors)
}

/// Reads HTML from one of three sources: file, URL, or stdin.
fn read_input(cli: &Cli) -> Result<(String, String), CliError> {
    if let Some(path) = &cli.file {
        let html = std::fs::read_to_string(path).map_err(|e| {
            CliError::InvalidInput(
                format!("cannot read file '{}': {e}", path.display()),
            )
        })?;
        Ok((html, path.display().to_string()))
    } else if let Some(url) = &cli.url {
        let resp = ureq::get(url)
            .set("User-Agent", concat!("schemaorg-validate/", env!("CARGO_PKG_VERSION")))
            .call()
            .map_err(|e| CliError::Http(Box::new(e)))?;
        let html = resp.into_string()
            .map_err(|e| CliError::InvalidInput(format!("failed to read response body: {e}")))?;
        Ok((html, url.clone()))
    } else if cli.stdin {
        let mut html = String::new();
        std::io::stdin().read_to_string(&mut html)?;
        Ok((html, "<stdin>".to_string()))
    } else {
        Err(CliError::InvalidInput(
            "no input specified (use --file, --url, or --stdin)".into(),
        ))
    }
}

/////////////////////////////////////////////////////////////////////////
// Text Output Formatter
/////////////////////////////////////////////////////////////////////////

/// ANSI color codes (disabled via `--no-color` or `NO_COLOR` env).
struct Colors {
    red: &'static str,
    yellow: &'static str,
    blue: &'static str,
    green: &'static str,
    bold: &'static str,
    dim: &'static str,
    reset: &'static str,
}

const COLORS_ON: Colors = Colors {
    red: "\x1b[31m",
    yellow: "\x1b[33m",
    blue: "\x1b[34m",
    green: "\x1b[32m",
    bold: "\x1b[1m",
    dim: "\x1b[2m",
    reset: "\x1b[0m",
};

const COLORS_OFF: Colors = Colors {
    red: "",
    yellow: "",
    blue: "",
    green: "",
    bold: "",
    dim: "",
    reset: "",
};

fn use_color(cli: &Cli) -> bool {
    if cli.no_color {
        return false;
    }
    std::env::var("NO_COLOR").is_err()
}

fn format_text(
    vocab_result: &ValidationResult,
    profile_result: Option<&ProfileResult>,
    source_name: &str,
    cli: &Cli,
) {
    let c = if use_color(cli) { &COLORS_ON } else { &COLORS_OFF };

    // Header
    println!(
        "\n{dim}-- schemaorg-validate {reset}{dim}{}{reset}",
        "-".repeat(40),
        dim = c.dim,
        reset = c.reset,
    );
    println!("  {bold}Source:{reset}  {source_name}", bold = c.bold, reset = c.reset);

    if profile_result.is_some() {
        let profile_name = match cli.profile {
            ProfileChoice::Google => "google-rich-results",
            ProfileChoice::Baseline => "baseline",
            ProfileChoice::None => "none",
        };
        println!("  {bold}Profile:{reset} {profile_name}", bold = c.bold, reset = c.reset);
    }
    println!(
        "  {bold}Schema.org:{reset} v{}",
        vocabulary::schema_version(),
        bold = c.bold,
        reset = c.reset,
    );

    // Vocabulary diagnostics
    let filtered: Vec<_> = vocab_result
        .diagnostics
        .iter()
        .filter(|d| cli.severity.passes(d.severity))
        .collect();

    if filtered.is_empty() {
        println!(
            "\n  {green}\u{2713} No vocabulary issues found{reset}",
            green = c.green,
            reset = c.reset,
        );
    } else {
        println!(
            "\n{dim}-- Vocabulary {reset}{dim}{}{reset}",
            "-".repeat(47),
            dim = c.dim,
            reset = c.reset,
        );
        for diag in &filtered {
            print_diagnostic(diag, c);
        }
    }

    // Profile results
    if let Some(pr) = profile_result {
        println!(
            "\n{dim}-- Profile Results {reset}{dim}{}{reset}",
            "-".repeat(42),
            dim = c.dim,
            reset = c.reset,
        );

        for tr in &pr.type_results {
            let status = if tr.eligible {
                format!("{green}ELIGIBLE{reset}", green = c.green, reset = c.reset)
            } else {
                format!("{red}NOT ELIGIBLE{reset}", red = c.red, reset = c.reset)
            };
            println!("  {bold}{}{reset}: {status}", tr.schema_type, bold = c.bold, reset = c.reset);

            if !tr.required_missing.is_empty() {
                println!(
                    "    {red}Required missing:{reset} {}",
                    tr.required_missing.join(", "),
                    red = c.red,
                    reset = c.reset,
                );
            }
            if !tr.recommended_missing.is_empty() {
                println!(
                    "    {yellow}Recommended missing:{reset} {}",
                    tr.recommended_missing.join(", "),
                    yellow = c.yellow,
                    reset = c.reset,
                );
            }
        }

        // Profile-specific diagnostics
        let profile_diags: Vec<_> = pr
            .diagnostics
            .iter()
            .filter(|d| cli.severity.passes(d.severity))
            .collect();
        for diag in &profile_diags {
            print_diagnostic(diag, c);
        }

        // Eligibility summary
        let elig_str = match pr.eligibility {
            Eligibility::Eligible => {
                format!("{green}Eligible{reset}", green = c.green, reset = c.reset)
            }
            Eligibility::WarningsOnly => format!(
                "{yellow}Eligible (with warnings){reset}",
                yellow = c.yellow,
                reset = c.reset,
            ),
            Eligibility::NotEligible => {
                format!("{red}Not Eligible{reset}", red = c.red, reset = c.reset)
            }
            Eligibility::Restricted => format!(
                "{blue}Restricted{reset}",
                blue = c.blue,
                reset = c.reset,
            ),
        };
        println!("\n  {bold}Eligibility:{reset} {elig_str}", bold = c.bold, reset = c.reset);
    }

    // Summary counts
    let error_count = vocab_result.errors().count()
        + profile_result.map_or(0, |pr| {
            pr.diagnostics.iter().filter(|d| d.severity == Severity::Error).count()
        });
    let warning_count = vocab_result.warnings().count()
        + profile_result.map_or(0, |pr| {
            pr.diagnostics
                .iter()
                .filter(|d| d.severity == Severity::Warning)
                .count()
        });

    println!(
        "\n  {error_count} error(s), {warning_count} warning(s)\n",
    );
}

/// Prints a single diagnostic line in text format.
fn print_diagnostic(diag: &ValidationDiagnostic, c: &Colors) {
    let (icon, color) = match diag.severity {
        Severity::Error => ("\u{2717}", c.red),
        Severity::Warning => ("\u{26a0}", c.yellow),
        Severity::Info => ("\u{2139}", c.blue),
    };
    let severity_label = match diag.severity {
        Severity::Error => "ERROR",
        Severity::Warning => "WARN ",
        Severity::Info => "INFO ",
    };

    let loc = diag
        .source_location
        .as_ref()
        .map(|l| format!(" (line {})", l.line))
        .unwrap_or_default();

    println!(
        "  {color}{icon} {severity_label}{reset}  {path}{loc} -- {msg}",
        color = color,
        reset = c.reset,
        path = diag.path,
        msg = diag.message,
    );
}

/////////////////////////////////////////////////////////////////////////
// JSON Output Formatter
/////////////////////////////////////////////////////////////////////////

fn format_json(
    vocab_result: &ValidationResult,
    profile_result: Option<&ProfileResult>,
    source_name: &str,
    graph: &schemaorg_rs::StructuredDataGraph,
) -> Result<(), CliError> {
    // Collect unique formats from extracted nodes
    let formats: Vec<String> = graph
        .nodes
        .iter()
        .map(|n| format!("{:?}", n.source_format))
        .collect::<HashSet<_>>()
        .into_iter()
        .collect();

    let mut output = serde_json::json!({
        "source": source_name,
        "schema_version": vocabulary::schema_version(),
        "extraction": {
            "node_count": graph.nodes.len(),
            "formats": formats,
            "warning_count": graph.warnings.len()
        },
        "vocabulary": {
            "diagnostics": vocab_result.diagnostics,
            "error_count": vocab_result.errors().count(),
            "warning_count": vocab_result.warnings().count()
        }
    });

    if let Some(pr) = profile_result {
        output["profile"] = serde_json::json!({
            "eligibility": pr.eligibility.to_string(),
            "type_results": pr.type_results,
            "diagnostics": pr.diagnostics
        });
    }

    println!(
        "{}",
        serde_json::to_string_pretty(&output)
            .map_err(|e| CliError::InvalidInput(format!("JSON serialization failed: {e}")))?
    );
    Ok(())
}

/////////////////////////////////////////////////////////////////////////
// SARIF Output Formatter
/////////////////////////////////////////////////////////////////////////

fn format_sarif(
    vocab_result: &ValidationResult,
    profile_result: Option<&ProfileResult>,
    source_name: &str,
) -> Result<(), CliError> {
    let sarif = schemaorg_rs::sarif::build_sarif(vocab_result, profile_result, source_name);
    println!(
        "{}",
        serde_json::to_string_pretty(&sarif)
            .map_err(|e| CliError::InvalidInput(format!("SARIF serialization failed: {e}")))?
    );
    Ok(())
}