dtcs 0.4.0

Reference implementation of the Data Transformation Contract Standard (DTCS)
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
//! Command-line interface.

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

use clap::{Parser, Subcommand};

use crate::compatibility::{analyze as analyze_compatibility, analyze_evolution, ComparisonScope};
use crate::diagnostics::{inspect_contract, DiagnosticReport};
use crate::lineage::analyze_with_options;
use crate::model::TransformationContract;
use crate::parser::parse_file;

/// DTCS command-line tool.
#[derive(Debug, Parser)]
#[command(
    name = "dtcs",
    version,
    about = "Validate and analyze DTCS transformation contracts"
)]
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 a DTCS document.
        path: PathBuf,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Print a contract summary.
    Inspect {
        /// Path to a DTCS document.
        path: PathBuf,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Print validation diagnostics.
    Diagnostics {
        /// Path to a DTCS document.
        path: PathBuf,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Compare compatibility between two contracts.
    Compat {
        /// Source (older) contract path.
        source: PathBuf,
        /// Target (newer) contract path.
        target: PathBuf,
        /// Comparison scope (comma-separated: interfaces,types,semantics,lineage,metadata,extensions,all).
        #[arg(long, value_delimiter = ',')]
        scope: Vec<String>,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Analyze evolution between two revisions.
    Evolve {
        /// Older revision path.
        older: PathBuf,
        /// Newer revision path.
        newer: PathBuf,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Analyze lineage for a contract.
    Lineage {
        /// Path to a DTCS document.
        path: PathBuf,
        /// List outputs affected by this input id.
        #[arg(long)]
        impact: Option<String>,
        /// List inputs required by this output id.
        #[arg(long)]
        dependency: Option<String>,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Print tool and specification versions.
    Version {
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Inspect the identifier registry catalog.
    Registry {
        #[command(subcommand)]
        /// Registry subcommand.
        command: RegistryCommand,
    },
}

/// Registry catalog commands.
#[derive(Debug, Subcommand)]
pub enum RegistryCommand {
    /// List registry entries.
    List {
        /// Optional additional registry file to merge.
        #[arg(long)]
        registry: Option<PathBuf>,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
    /// Resolve a registry identifier.
    Resolve {
        /// Identifier to resolve (for example `dtcs:lowercase`).
        id: String,
        /// Optional additional registry file to merge.
        #[arg(long)]
        registry: Option<PathBuf>,
        /// Emit JSON output.
        #[arg(long)]
        json: bool,
    },
}

/// Run the CLI application.
pub fn run(cli: Cli) -> miette::Result<i32> {
    match cli.command {
        Command::Validate { path, json } => {
            let result = parse_file(&path)?;
            let report = result.validate();
            render_report(&report, json, ReportMode::Validate)
                .map_err(|e| miette::miette!("{e}"))?;
            Ok(if report.is_valid() { 0 } else { 1 })
        }
        Command::Inspect { path, json } => {
            let contract = load_valid_contract(&path)?;
            if json {
                let summary = InspectSummary::from_contract(&contract);
                println!(
                    "{}",
                    serde_json::to_string_pretty(&summary).map_err(|e| miette::miette!("{e}"))?
                );
            } else {
                print!("{}", inspect_contract(&contract));
            }
            Ok(0)
        }
        Command::Diagnostics { path, json } => {
            let result = parse_file(&path)?;
            let report = result.validate();
            render_report(&report, json, ReportMode::Diagnostics)
                .map_err(|e| miette::miette!("{e}"))?;
            Ok(if report.is_valid() { 0 } else { 1 })
        }
        Command::Compat {
            source,
            target,
            scope,
            json,
        } => {
            let source_contract = load_valid_contract(&source)?;
            let target_contract = load_valid_contract(&target)?;
            let scope = match ComparisonScope::from_tokens(&scope) {
                Ok(scope) => scope,
                Err(invalid) => {
                    eprintln!("invalid scope token(s): {}", invalid.join(", "));
                    return Ok(2);
                }
            };
            let report = analyze_compatibility(&source_contract, &target_contract, scope);
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&report).map_err(|e| miette::miette!("{e}"))?
                );
            } else {
                println!("compatibility: {:?}", report.level);
                for aspect in &report.aspects {
                    println!("  {}: {}", aspect.aspect, aspect.message);
                }
                for diagnostic in &report.diagnostics {
                    println!(
                        "[{:?}] {} - {}",
                        diagnostic.severity, diagnostic.id, diagnostic.message
                    );
                }
            }
            Ok(if report.is_compatible() { 0 } else { 1 })
        }
        Command::Evolve { older, newer, json } => {
            let older_contract = load_valid_contract(&older)?;
            let newer_contract = load_valid_contract(&newer)?;
            let report = analyze_evolution(&older_contract, &newer_contract);
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&report).map_err(|e| miette::miette!("{e}"))?
                );
            } else {
                println!(
                    "evolution: {:?} (same identity: {})",
                    report.compatibility, report.same_identity
                );
                for change in &report.changes {
                    println!("  [{:?}] {}", change.category, change.message);
                }
                for hint in &report.migration_hints {
                    println!("  hint: {hint}");
                }
            }
            Ok(
                if report.same_identity
                    && report.compatibility != crate::CompatibilityLevel::Incompatible
                {
                    0
                } else {
                    1
                },
            )
        }
        Command::Lineage {
            path,
            impact,
            dependency,
            json,
        } => {
            let contract = load_valid_contract(&path)?;
            let report = analyze_with_options(&contract, impact.as_deref(), dependency.as_deref());
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&report).map_err(|e| miette::miette!("{e}"))?
                );
            } else {
                for edge in &report.graph {
                    println!("{} <- {:?}", edge.output, edge.inputs);
                }
                if let Some(impact) = &report.impact {
                    println!("impact {} -> {:?}", impact.input, impact.outputs);
                }
                if let Some(dep) = &report.dependency {
                    println!("dependency {} <- {:?}", dep.output, dep.inputs);
                }
            }
            Ok(0)
        }
        Command::Version { json } => {
            if json {
                println!(
                    "{}",
                    serde_json::json!({
                        "crateVersion": env!("CARGO_PKG_VERSION"),
                        "specVersion": crate::SPEC_VERSION,
                    })
                );
            } else {
                println!("dtcs {}", env!("CARGO_PKG_VERSION"));
                println!("spec {}", crate::SPEC_VERSION);
            }
            Ok(0)
        }
        Command::Registry { command } => run_registry(command),
    }
}

fn run_registry(command: RegistryCommand) -> miette::Result<i32> {
    match command {
        RegistryCommand::List { registry, json } => {
            let entries = crate::registry::list(registry.as_deref())
                .map_err(|report| registry_report_error(&report))?;
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&entries).map_err(|e| miette::miette!("{e}"))?
                );
            } else {
                for entry in &entries {
                    println!(
                        "{}  [{}]  {}  ({})",
                        entry.id,
                        entry.category.as_str(),
                        entry.name,
                        entry.status.as_str()
                    );
                }
            }
            Ok(0)
        }
        RegistryCommand::Resolve { id, registry, json } => {
            let entry = crate::registry::resolve_with_path(&id, registry.as_deref())
                .map_err(|report| registry_report_error(&report))?;
            match entry {
                Some(entry) => {
                    if json {
                        println!(
                            "{}",
                            serde_json::to_string_pretty(&entry)
                                .map_err(|e| miette::miette!("{e}"))?
                        );
                    } else {
                        println!("id: {}", entry.id);
                        println!("name: {}", entry.name);
                        println!("category: {}", entry.category.as_str());
                        println!("version: {}", entry.version);
                        println!("status: {}", entry.status.as_str());
                        if let Some(definition) = &entry.definition {
                            println!("definition: {definition}");
                        }
                        if let Some(compatibility) = entry.compatibility {
                            println!("compatibility: {}", compatibility.as_str());
                        }
                        println!("supported: {}", entry.supported);
                    }
                    Ok(0)
                }
                None => {
                    if json {
                        println!("null");
                    } else {
                        eprintln!("unresolved registry entry: {id}");
                    }
                    Ok(1)
                }
            }
        }
    }
}

fn registry_report_error(report: &DiagnosticReport) -> miette::Error {
    let messages: Vec<_> = report
        .diagnostics
        .iter()
        .map(|d| d.message.as_str())
        .collect();
    miette::miette!("{}", messages.join("; "))
}

fn load_valid_contract(path: &PathBuf) -> miette::Result<TransformationContract> {
    let result = parse_file(path)?;
    if !result.report.is_valid() {
        return Err(miette::miette!("parse failed for {}", path.display()));
    }
    result
        .contract
        .ok_or_else(|| miette::miette!("no contract in {}", path.display()))
        .and_then(|contract| {
            let report = crate::validate(&contract);
            if !report.is_valid() {
                return Err(miette::miette!("validation failed for {}", path.display()));
            }
            Ok(contract)
        })
}

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

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct InspectSummary {
    id: String,
    name: String,
    version: String,
    dtcs_version: String,
    inputs: usize,
    outputs: usize,
    semantic_actions: usize,
    rules: usize,
    expressions: usize,
    functions: usize,
}

impl InspectSummary {
    fn from_contract(contract: &crate::TransformationContract) -> Self {
        Self {
            id: contract.id.clone(),
            name: contract.name.clone(),
            version: contract.version.clone(),
            dtcs_version: contract.dtcs_version.clone(),
            inputs: contract.inputs.len(),
            outputs: contract.outputs.len(),
            semantic_actions: contract.semantic_actions.len(),
            rules: contract.rules.len(),
            expressions: contract.expressions.len(),
            functions: contract.functions.len(),
        }
    }
}

fn render_report(report: &DiagnosticReport, json: bool, mode: ReportMode) -> std::io::Result<()> {
    let mut stdout = io::stdout().lock();
    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!(
            stdout,
            "{}",
            serde_json::to_string_pretty(&payload)
                .map_err(|e| std::io::Error::other(e.to_string()))?
        )?;
        return Ok(());
    }

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

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

    if matches!(mode, ReportMode::Validate) && report.is_valid() {
        writeln!(stdout, "valid")?;
    }

    Ok(())
}