odcs 0.9.0

Reference implementation of the Open Data Contract Standard (ODCS)
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Command-line interface.

use std::io::{self, Write};
use std::path::PathBuf;

use clap::{Parser, Subcommand};

use crate::diagnostics::{inspect_contract, DiagnosticReport, DiagnosticStage};
use crate::parser::{parse_file, ParseResult};
use crate::schema::{self, UPSTREAM_REPOSITORY_URL};
use crate::validation::ValidationOptions;
use crate::UPSTREAM_SPEC_VERSION;

/// ODCS command-line tool.
#[derive(Debug, Parser)]
#[command(
    name = "odcs",
    version,
    about = "Validate Open Data Contract Standard documents"
)]
pub struct Cli {
    #[command(subcommand)]
    /// Subcommand to execute.
    pub command: Command,
}

/// Supported CLI commands.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Parse and validate a contract.
    Validate {
        /// Path to an ODCS document.
        path: PathBuf,
        /// Explicit dependency contract paths for cross-file reference resolution.
        #[arg(long = "dep")]
        deps: Vec<PathBuf>,
        /// Directory of dependency contracts (non-recursive `*.yaml`, `*.yml`, `*.json` scan).
        #[arg(long = "include")]
        includes: Vec<PathBuf>,
        /// Registry root directory (`<dir>/.odcs/registry.json` for dependency resolution).
        #[arg(long = "registry")]
        registry_dir: Option<PathBuf>,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
        /// Deprecated no-op retained for compatibility (JSON Schema always runs in validate).
        #[arg(long)]
        strict: bool,
    },
    /// Print a contract summary.
    Inspect {
        /// Path to an ODCS document.
        path: PathBuf,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Print validation diagnostics.
    Diagnostics {
        /// Path to an ODCS document.
        path: PathBuf,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Print pinned ODCS JSON Schema.
    Schema {
        /// Emit JSON output with schema metadata.
        #[arg(long)]
        json: bool,
        /// Print upstream repository URL only.
        #[arg(long)]
        url_only: bool,
    },
    /// Print tool and upstream specification versions.
    Version {
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Compare two contracts for breaking changes.
    Diff {
        /// Path to the older contract.
        old: PathBuf,
        /// Path to the newer contract.
        new: PathBuf,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Local contract registry commands.
    Registry {
        /// Registry subcommand to execute.
        #[command(subcommand)]
        command: RegistryCommand,
    },
}

/// Registry subcommands.
#[derive(Debug, Subcommand)]
pub enum RegistryCommand {
    /// Build or overwrite `.odcs/registry.json` for a directory.
    Index {
        /// Registry root directory (indexed recursively).
        dir: PathBuf,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Look up a contract by id (and optional version).
    Lookup {
        /// Registry root directory.
        dir: PathBuf,
        /// Contract id to look up.
        id: String,
        /// Exact contract revision (`version` field).
        #[arg(long)]
        version: Option<String>,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// List all indexed contracts.
    List {
        /// Registry root directory.
        dir: PathBuf,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
}

/// Run the CLI application.
pub fn run(cli: Cli) -> i32 {
    match cli.command {
        Command::Validate {
            path,
            deps,
            includes,
            registry_dir,
            json,
            strict,
        } => {
            let options = if strict {
                ValidationOptions::strict()
            } else {
                ValidationOptions::default_options()
            };

            let registry = match registry_dir.as_ref() {
                Some(dir) => match crate::registry::load_registry(dir) {
                    Ok(registry) => Some(registry),
                    Err(report) => {
                        if let Err(error) = render_report(&report, json, ReportMode::Diagnostics) {
                            eprintln!("{error}");
                            return 2;
                        }
                        return exit_code_for_report(&report);
                    }
                },
                None => None,
            };

            let report = if deps.is_empty() && includes.is_empty() && registry.is_none() {
                let result = match parse_file(&path) {
                    Ok(result) => result,
                    Err(error) => {
                        eprintln!("{error}");
                        return 2;
                    }
                };
                result.validate_with_options(options)
            } else {
                match crate::contract_set::load_set_with_registry(
                    &path,
                    &deps,
                    &includes,
                    registry.as_ref(),
                ) {
                    Ok(set) => crate::contract_set::validate_set_with_options(&set, options),
                    Err(report) => report,
                }
            };

            if let Err(error) = render_report(&report, json, ReportMode::Validate) {
                eprintln!("{error}");
                return 2;
            }
            exit_code_for_report(&report)
        }
        Command::Inspect { path, json } => {
            let result = match parse_file(&path) {
                Ok(result) => result,
                Err(error) => {
                    eprintln!("{error}");
                    return 2;
                }
            };
            if has_parse_failure(&result) {
                if let Err(error) = render_report(&result.report, json, ReportMode::Diagnostics) {
                    eprintln!("{error}");
                    return 2;
                }
                return 2;
            }
            let ParseResult {
                contract,
                report: parse_report,
            } = result;
            let mut report = parse_report;
            if let Some(ref contract) = contract {
                report.merge(crate::validate(contract));
            }
            if !report.is_valid() {
                if let Err(error) = render_report(&report, json, ReportMode::Diagnostics) {
                    eprintln!("{error}");
                    return 2;
                }
                return 1;
            }
            let Some(contract) = contract else {
                if let Err(error) = render_report(&report, json, ReportMode::Diagnostics) {
                    eprintln!("{error}");
                    return 2;
                }
                return 2;
            };
            if json {
                let summary = serde_json::json!({
                    "id": contract.id,
                    "name": contract.name,
                    "version": contract.version,
                    "apiVersion": contract.api_version,
                    "kind": contract.kind,
                    "status": contract.status,
                    "schemaCount": contract.schema.len(),
                    "qualityCount": contract.quality_rules().len(),
                });
                if let Err(code) = write_json_stdout(&summary) {
                    eprintln!("failed to write JSON output");
                    return code;
                }
            } else if let Err(error) = writeln!(io::stdout(), "{}", inspect_contract(&contract)) {
                eprintln!("{error}");
                return 2;
            }
            0
        }
        Command::Diagnostics { path, json } => {
            let result = match parse_file(&path) {
                Ok(result) => result,
                Err(error) => {
                    eprintln!("{error}");
                    return 2;
                }
            };
            let report = result.validate();
            if let Err(error) = render_report(&report, json, ReportMode::Diagnostics) {
                eprintln!("{error}");
                return 2;
            }
            exit_code_for_report(&report)
        }
        Command::Schema { json, url_only } => {
            if url_only {
                if let Err(error) = writeln!(
                    io::stdout(),
                    "Upstream ODCS JSON Schema: {UPSTREAM_REPOSITORY_URL}"
                ) {
                    eprintln!("{error}");
                    return 2;
                }
                return 0;
            }
            if json {
                let payload = serde_json::json!({
                    "schemaVersion": UPSTREAM_SPEC_VERSION,
                    "upstreamUrl": UPSTREAM_REPOSITORY_URL,
                    "schema": schema::pinned_schema_value(),
                });
                if let Err(code) = write_json_stdout(&payload) {
                    eprintln!("failed to write JSON output");
                    return code;
                }
            } else if let Err(error) = write!(io::stdout(), "{}", schema::PINNED_SCHEMA_JSON) {
                eprintln!("{error}");
                return 2;
            }
            0
        }
        Command::Version { json } => {
            if json {
                let payload = serde_json::json!({
                    "crateVersion": env!("CARGO_PKG_VERSION"),
                    "upstreamSpecVersion": UPSTREAM_SPEC_VERSION,
                });
                if let Err(code) = write_json_stdout(&payload) {
                    eprintln!("failed to write JSON output");
                    return code;
                }
            } else if let Err(error) = writeln!(
                io::stdout(),
                "odcs {} (upstream ODCS {})",
                env!("CARGO_PKG_VERSION"),
                UPSTREAM_SPEC_VERSION
            ) {
                eprintln!("{error}");
                return 2;
            }
            0
        }
        Command::Diff { old, new, json } => {
            let old_contract = match parse_file(&old) {
                Ok(result) => result.contract,
                Err(error) => {
                    eprintln!("{error}");
                    return 2;
                }
            };
            let new_contract = match parse_file(&new) {
                Ok(result) => result.contract,
                Err(error) => {
                    eprintln!("{error}");
                    return 2;
                }
            };
            let (Some(old_contract), Some(new_contract)) = (old_contract, new_contract) else {
                eprintln!("failed to parse one or both contracts");
                return 2;
            };

            let report = crate::compatibility::diff(&old_contract, &new_contract);
            if json {
                let payload = serde_json::json!({
                    "compatible": report.is_compatible(),
                    "hasBreaking": report.has_breaking,
                    "changes": report.changes,
                });
                if let Err(code) = write_json_stdout(&payload) {
                    eprintln!("failed to write JSON output");
                    return code;
                }
            } else if report.changes.is_empty() {
                writeln!(io::stdout(), "no changes").expect("write stdout");
            } else {
                for change in &report.changes {
                    writeln!(
                        io::stdout(),
                        "[{}] {}: {} ({})",
                        format!("{:?}", change.kind).to_lowercase(),
                        change.code,
                        change.message,
                        change.path
                    )
                    .expect("write stdout");
                }
            }

            if report.has_breaking {
                1
            } else {
                0
            }
        }
        Command::Registry { command } => run_registry_command(command),
    }
}

fn run_registry_command(command: RegistryCommand) -> i32 {
    match command {
        RegistryCommand::Index { dir, json } => {
            match crate::registry::index_and_save_registry(&dir) {
                Ok((registry, report)) => {
                    if json {
                        let entries: Vec<_> =
                            registry.list().iter().map(registry_entry_json).collect();
                        let payload = serde_json::json!({
                            "entries": entries,
                            "diagnostics": report.diagnostics,
                        });
                        if let Err(code) = write_json_stdout(&payload) {
                            eprintln!("failed to write JSON output");
                            return code;
                        }
                    } else {
                        for entry in registry.list() {
                            writeln!(
                                io::stdout(),
                                "{} {} ({})",
                                entry.id,
                                entry.version,
                                entry.path.display()
                            )
                            .expect("write stdout");
                        }
                    }
                    0
                }
                Err(report) => {
                    if let Err(error) = render_report(&report, json, ReportMode::Diagnostics) {
                        eprintln!("{error}");
                        return 2;
                    }
                    if report
                        .diagnostics
                        .iter()
                        .any(|d| d.message.contains("duplicate registry entry"))
                    {
                        1
                    } else if report
                        .diagnostics
                        .iter()
                        .any(|d| d.stage == DiagnosticStage::Parse)
                    {
                        2
                    } else {
                        exit_code_for_report(&report)
                    }
                }
            }
        }
        RegistryCommand::Lookup {
            dir,
            id,
            version,
            json,
        } => {
            let registry = match crate::registry::load_registry(&dir) {
                Ok(registry) => registry,
                Err(report) => {
                    if let Err(error) = render_report(&report, json, ReportMode::Diagnostics) {
                        eprintln!("{error}");
                        return 2;
                    }
                    return exit_code_for_report(&report);
                }
            };

            let entry = match version.as_deref() {
                Some(version) => registry.lookup_version(&id, version),
                None => registry.lookup(&id),
            };

            match entry {
                Some(entry) => {
                    if json {
                        if let Err(code) = write_json_stdout(&registry_entry_json(entry)) {
                            eprintln!("failed to write JSON output");
                            return code;
                        }
                    } else {
                        writeln!(
                            io::stdout(),
                            "{} {} {}",
                            entry.id,
                            entry.version,
                            entry.path.display()
                        )
                        .expect("write stdout");
                    }
                    0
                }
                None => {
                    if json {
                        let payload = serde_json::json!({ "entry": null });
                        if let Err(code) = write_json_stdout(&payload) {
                            eprintln!("failed to write JSON output");
                            return code;
                        }
                    } else {
                        writeln!(io::stderr(), "registry entry not found: {id}")
                            .expect("write stderr");
                    }
                    1
                }
            }
        }
        RegistryCommand::List { dir, json } => {
            let registry = match crate::registry::load_registry(&dir) {
                Ok(registry) => registry,
                Err(report) => {
                    if let Err(error) = render_report(&report, json, ReportMode::Diagnostics) {
                        eprintln!("{error}");
                        return 2;
                    }
                    return exit_code_for_report(&report);
                }
            };

            if json {
                let entries: Vec<_> = registry.list().iter().map(registry_entry_json).collect();
                let payload = serde_json::json!({ "entries": entries });
                if let Err(code) = write_json_stdout(&payload) {
                    eprintln!("failed to write JSON output");
                    return code;
                }
            } else {
                for entry in registry.list() {
                    writeln!(
                        io::stdout(),
                        "{} {} ({})",
                        entry.id,
                        entry.version,
                        entry.path.display()
                    )
                    .expect("write stdout");
                }
            }
            0
        }
    }
}

fn registry_entry_json(entry: &crate::registry::RegistryEntry) -> serde_json::Value {
    serde_json::json!({
        "id": entry.id,
        "version": entry.version,
        "path": entry.path,
        "apiVersion": entry.api_version,
        "tags": entry.tags,
        "contentHash": entry.content_hash,
        "indexedAt": entry.indexed_at,
    })
}

fn write_json_stdout(payload: &serde_json::Value) -> Result<(), i32> {
    let rendered = serde_json::to_string_pretty(payload).map_err(|_| 2)?;
    writeln!(io::stdout(), "{rendered}").map_err(|_| 2)
}

#[derive(Debug, Clone, Copy)]
enum ReportMode {
    Validate,
    Diagnostics,
}

fn has_parse_failure(result: &ParseResult) -> bool {
    result.contract.is_none()
        || result
            .report
            .diagnostics
            .iter()
            .any(|d| d.stage == DiagnosticStage::Parse)
}

fn exit_code_for_report(report: &DiagnosticReport) -> i32 {
    if report
        .diagnostics
        .iter()
        .any(|d| d.stage == DiagnosticStage::Parse)
    {
        return 2;
    }
    if report.is_valid() {
        0
    } else {
        1
    }
}

fn render_report(report: &DiagnosticReport, json: bool, mode: ReportMode) -> io::Result<()> {
    if json {
        let payload = match mode {
            ReportMode::Validate => serde_json::json!({
                "valid": report.is_valid(),
                "diagnostics": report.diagnostics,
            }),
            ReportMode::Diagnostics => serde_json::json!({
                "diagnostics": report.diagnostics,
            }),
        };
        writeln!(
            io::stdout(),
            "{}",
            serde_json::to_string_pretty(&payload)
                .map_err(|e| std::io::Error::other(e.to_string()))?
        )?;
        return Ok(());
    }

    if report.is_valid() {
        match mode {
            ReportMode::Validate => writeln!(io::stdout(), "valid")?,
            ReportMode::Diagnostics => writeln!(io::stdout(), "no diagnostics")?,
        }
        return Ok(());
    }

    for diagnostic in &report.diagnostics {
        writeln!(
            io::stdout(),
            "[{}] {}: {}",
            format!("{:?}", diagnostic.severity).to_lowercase(),
            diagnostic.id,
            diagnostic.message
        )?;
        if let Some(object_ref) = &diagnostic.object_ref {
            writeln!(io::stdout(), "  at: {object_ref}")?;
        }
        if let Some(phase) = diagnostic.validation_phase {
            writeln!(io::stdout(), "  phase: {phase}")?;
        }
        if let Some(remediation) = &diagnostic.remediation {
            writeln!(io::stdout(), "  hint: {remediation}")?;
        }
    }
    Ok(())
}