cadmpeg 0.6.3

Convert and inspect native CAD files.
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
// SPDX-License-Identifier: Apache-2.0
//! Command execution, artifact writing, and human-readable reports.

pub(crate) mod reporting;

use reporting::{
    command_body_json, command_report_json, fidelity_diff, fidelity_differs, print_check_report,
    print_decode_report, print_export_emission, print_fidelity_summary, print_id_delta,
    print_source_diff, write_command_report, write_json_report, CommandReportBody, Payload,
};

use cadmpeg_ir::codec::write::target::TargetRequest;
use cadmpeg_ir::codec::Confidence;
use std::fs::File;
use std::io::{self, Write};
use std::path::Path;
use std::process::ExitCode;

use anyhow::{anyhow, Context};
use cadmpeg_core::decode::{DecodeDepth, InspectOptions};
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};

use cadmpeg_registry::{
    build_encoder, resolve_and_inspect_with, ForcedInput, Format, InputCatalog, InspectError,
    Inspected, Selection,
};

use crate::application::artifact_store::{self, FileDestination};
use crate::application::document::{LoadOrigin, LoadedDocument};
use crate::application::refusal::{ApplicationError, ConversionRefusal, RefusalStage};
use crate::application::transcoder::{
    self, emit_export_plan, export_target, ConversionPolicy, DestinationPolicy, LossPolicy,
    SourceRequest, TargetSelection,
};
use crate::application::validators::validate_loaded;
use crate::loader;
use crate::DecodeArgs;

type CommandResult<T> = std::result::Result<T, ApplicationError>;

fn print_load_notice(document: &LoadedDocument) {
    let LoadOrigin::Decoded {
        selection: Selection::Detected { confidence },
        report,
        ..
    } = &document.origin
    else {
        return;
    };
    if *confidence < Confidence::High {
        let format_id = report.format();
        eprintln!(
            "warning: detected {format_id} with {confidence} confidence; use --input-format to override"
        );
    }
}

/// CLI-facing conversion arguments assembled from argv.
pub(crate) struct ConversionArgs {
    /// Decode and export loss refusal.
    pub(crate) losses: LossPolicy,
    /// Permit export when validation reports errors.
    pub(crate) allow_errors: bool,
    /// Permit a geometry export when decode transferred no geometry.
    pub(crate) allow_empty: bool,
    /// Decode at full depth whatever depth the output format needs.
    pub(crate) full_decode: bool,
    /// CAD output destination and its overwrite policy.
    pub(crate) destination: DestinationPolicy,
    /// Optional path for the JSON command report.
    pub(crate) report: Option<FileDestination>,
    /// Explicit input format selected by the user.
    pub(crate) forced_input: Option<ForcedInput>,
}

/// Attempt to persist a semantic refusal without replacing it with a report
/// I/O failure. The original refusal controls the process exit status; report
/// persistence failure remains visible on stderr.
fn write_refusal<P: reporting::ReportBody>(
    input: &Path,
    output: Option<&FileDestination>,
    command: &'static str,
    payload: Payload<'_, P>,
    json: bool,
) {
    if output.is_none() && !json {
        return;
    }
    let report = match reporting::payload_report_json(command, payload) {
        Ok(report) => report,
        Err(error) => {
            eprintln!("warning: could not serialize {command} refusal report: {error:#}; preserving the original refusal");
            return;
        }
    };
    if let Err(error) = reporting::write_report_text(input, output, &report) {
        eprintln!("warning: could not write {command} refusal report: {error:#}; preserving the original refusal");
    }
    if json {
        println!("{report}");
    }
}

/// Report any refusal returned by a command, including early admission and
/// resource failures. Report I/O cannot replace the original exit status.
fn report_failure<T>(
    result: CommandResult<T>,
    input: &Path,
    output: Option<&FileDestination>,
    command: &'static str,
    json: bool,
) -> CommandResult<T> {
    result.inspect_err(|error| {
        let Some(refusal) = error.refusal() else {
            return;
        };
        let reports = refusal.evidence().reports;
        if command == "convert" {
            let mut stderr = io::stderr();
            let diagnostics = (|| -> io::Result<()> {
                if let Some(report) = reports.decode {
                    print_decode_report(&mut stderr, report)?;
                    writeln!(stderr)?;
                }
                if let Some(report) = reports.check {
                    print_check_report(&mut stderr, report)?;
                }
                Ok(())
            })();
            if let Err(error) = diagnostics {
                eprintln!("warning: could not write convert diagnostics: {error}");
            }
        } else if command == "check" && !json {
            if let Some(report) = reports.check {
                if let Err(error) = print_check_report(&mut io::stdout(), report) {
                    eprintln!("warning: could not write check diagnostics: {error}");
                }
            }
        }
        write_refusal(
            input,
            output,
            command,
            CommandReportBody::Refused(refusal).payload(),
            json,
        );
    })
}

/// One input to a structural diff and its optional format override.
#[derive(Clone, Copy)]
pub(crate) struct DiffInput<'a> {
    /// Model path to load.
    pub(crate) path: &'a Path,
    /// Explicit reader selection for this input.
    pub(crate) forced: Option<ForcedInput>,
}

/// How the codec that read the inspected input was chosen.
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum InputSelection {
    /// The caller forced the codec, so no detection ran.
    Forced,
    /// Content detection named the codec at this confidence.
    Detected {
        confidence: cadmpeg_ir::codec::Confidence,
    },
}

impl From<cadmpeg_registry::Selection> for InputSelection {
    fn from(selection: cadmpeg_registry::Selection) -> Self {
        match selection {
            cadmpeg_registry::Selection::Forced => Self::Forced,
            cadmpeg_registry::Selection::Detected { confidence } => Self::Detected { confidence },
        }
    }
}

impl InputSelection {
    /// Renders the selection the way the plain-text report states it.
    fn label(self) -> String {
        match self {
            Self::Forced => " (forced)".to_string(),
            Self::Detected { confidence } => format!(" (detected {confidence})"),
        }
    }
}

/// `inspect` payload. `summary` is `null` on a refusal, where no container
/// summary was produced.
#[derive(Serialize)]
struct InspectPayload<'a> {
    selection: InputSelection,
    summary: Option<&'a cadmpeg_ir::ContainerSummary>,
}

struct DiffReportPayload<'a> {
    diff: &'a cadmpeg_ir::IrDiff,
    source_fidelity: &'a reporting::FidelitySummary,
}

impl DiffReportPayload<'_> {
    fn different(&self) -> bool {
        !self.diff.is_empty() || fidelity_differs(self.source_fidelity)
    }
}

impl Serialize for DiffReportPayload<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        let mut state = serializer.serialize_struct("DiffReportPayload", 3)?;
        state.serialize_field("different", &self.different())?;
        state.serialize_field("diff", self.diff)?;
        state.serialize_field("source_fidelity", self.source_fidelity)?;
        state.end()
    }
}

/// Inspect a native container and print its entries.
pub(crate) fn inspect(
    inputs: &InputCatalog,
    path: &Path,
    forced: Option<&'static cadmpeg_registry::NativeDescriptor>,
    json: bool,
    report_path: Option<&FileDestination>,
    limits: cadmpeg_core::decode::ResourceLimits,
) -> CommandResult<()> {
    let mut refusal_selection = None;
    let result: CommandResult<()> = (|| {
        let mut file = File::open(path).with_context(|| format!("opening {}", path.display()))?;
        let Inspected {
            selection, summary, ..
        } = match resolve_and_inspect_with(
            inputs,
            &mut file,
            forced.map(ForcedInput::Codec),
            &InspectOptions { limits },
        ) {
            Ok(inspected) => inspected,
            Err(InspectError::Io(error)) => {
                return Err(inspect_io_error(path, limits.max_input_bytes, error).into());
            }
            Err(InspectError::Detection(error)) => return Err(error.into()),
            Err(InspectError::Unresolved(cadmpeg_registry::ResolveSourceError::Codec(error))) => {
                return Err(error.into())
            }
            Err(InspectError::Unresolved(error)) => {
                return Err(loader::detection_failure(&error).into());
            }
            Err(InspectError::Cadir | InspectError::Unrecognized) => {
                return Err(inspect_unrecognized(path).into());
            }
            Err(InspectError::Codec {
                format,
                selection: selected,
                error,
            }) => {
                refusal_selection = Some(selected.into());
                return Err(ApplicationError::from_codec_failure(
                    path,
                    format,
                    "inspecting",
                    error,
                ));
            }
        };
        let selection = InputSelection::from(selection);
        let payload = InspectPayload {
            selection,
            summary: Some(&summary),
        };
        write_json_report(path, report_path, "inspect", &payload)?;
        if json {
            println!("{}", command_report_json("inspect", &payload)?);
            return Ok(());
        }
        println!(
            "format: {}{}\ncontainer: {}\nentries: {}",
            summary.format(),
            selection.label(),
            summary.container_kind,
            summary.entries.len()
        );
        for line in crate::registry_view::dialect_lines(summary.dialects())? {
            println!("{line}");
        }
        println!();
        for entry in &summary.entries {
            let size =
                |size: Option<u64>| size.map_or_else(|| "-".to_string(), |size| size.to_string());
            println!(
                "  {:<14} {:>10} → {:<10}  {}",
                entry.role,
                size(entry.stored_size()),
                size(entry.expanded_size()),
                entry.name
            );
            for (key, value) in &entry.attributes {
                println!("        {key} = {value}");
            }
        }
        if !summary.notes.is_empty() {
            println!("\nnotes:");
            for note in &summary.notes {
                println!("  - {note}");
            }
        }
        Ok(())
    })();
    result.inspect_err(|error| {
        if let Some(refusal) = error.refusal() {
            if let Some(selection) = refusal_selection {
                let payload = InspectPayload {
                    selection,
                    summary: None,
                };
                write_refusal(
                    path,
                    report_path,
                    "inspect",
                    Payload::Refused(&payload, refusal),
                    json,
                );
            } else {
                write_refusal(
                    path,
                    report_path,
                    "inspect",
                    Payload::Refused(serde_json::json!({ "summary": null }), refusal),
                    json,
                );
            }
        }
    })
}

fn inspect_unrecognized(path: &Path) -> anyhow::Error {
    anyhow!(
        "no codec recognized {}; inspect supports container inputs only, not .cadir.json IR documents; supported: FCStd, f3d, Inventor IPT/IAM, sldprt, CATPart, NX/Creo prt, Rhino 3DM, IGES, STEP; use --input-format to override detection",
        path.display()
    )
}

fn inspect_io_error(path: &Path, max_input_bytes: u64, error: io::Error) -> anyhow::Error {
    if error.kind() == io::ErrorKind::FileTooLarge {
        anyhow!(
            "{} exceeds the configured {}-byte input limit",
            path.display(),
            max_input_bytes
        )
    } else {
        anyhow!(error).context(format!("inspecting {}", path.display()))
    }
}

/// Dump a native CAD file and write CADIR JSON.
pub(crate) fn dump(
    inputs: &InputCatalog,
    path: &Path,
    destination: &DestinationPolicy,
    report_path: Option<&FileDestination>,
    forced: Option<ForcedInput>,
    args: &DecodeArgs,
) -> CommandResult<()> {
    let result = (|| {
        let destination = destination.resolve(path)?;
        if let Some(report_path) = report_path {
            report_path.check(path)?;
            if let Some(out) = destination.path() {
                artifact_store::check_distinct_output_paths(
                    out,
                    "CADIR output",
                    &report_path.path,
                    "command report",
                )?;
            }
        }
        let loaded = loader::load_artifact(inputs, path, args.options(), forced)?;
        print_load_notice(&loaded);
        let encoder = build_encoder(Format::Cadir);
        let plan = encoder
            .plan(
                cadmpeg_ir::codec::write::EncodeInput::new(&loaded.ir, loaded.fidelity()),
                TargetRequest::Inherit,
            )
            .map_err(|error| ApplicationError::from(error).at_stage(RefusalStage::Plan))?;
        let emission = emit_export_plan(plan, Format::Cadir, &destination, &loaded.origin)
            .map_err(|error| ApplicationError::from(error).at_stage(RefusalStage::Export))?;
        print_export_emission(&mut io::stderr(), &emission)?;
        if let Some(report) = loaded.decode_report() {
            print_decode_report(&mut io::stderr(), report)?;
        }
        // Dump does not check. Convert/check compose validate_neutral +
        // fidelity + native; salvage mode may emit IR with findings.
        eprintln!("check: not run (a successful dump is not a checked model; run `cadmpeg check`)");
        write_command_report(
            path,
            report_path,
            "dump",
            CommandReportBody::Ok {
                decode_report: loaded.decode_report(),
                check_report: None,
                export: None,
            },
        )?;
        Ok(())
    })();
    report_failure(result, path, report_path, "dump", false)
}

/// Load and check CADIR, printing a human-readable or JSON report.
pub(crate) fn check_cmd(
    inputs: &InputCatalog,
    path: &Path,
    forced: Option<ForcedInput>,
    args: &DecodeArgs,
    json: bool,
    report_path: Option<&FileDestination>,
) -> CommandResult<()> {
    let result = (|| {
        let loaded = loader::load_artifact(inputs, path, args.options(), forced)?;
        print_load_notice(&loaded);
        let mut stdout = io::stdout();
        if let Some(report) = loaded.decode_report() {
            print_decode_report(&mut io::stderr(), report)?;
        }
        let report = validate_loaded(inputs, &loaded, &args.options().policy)?;
        let check_refusal = (!report.is_ok()).then(|| ConversionRefusal::CheckFailed {
            operation: crate::application::refusal::CheckOperation::Check,
            decode_report: loaded.decode_report().cloned(),
            validation: report.clone(),
        });
        if let Some(refusal) = check_refusal {
            return Err(refusal.into());
        }
        let body = CommandReportBody::Ok {
            decode_report: loaded.decode_report(),
            check_report: Some(&report),
            export: None,
        };
        write_command_report(path, report_path, "check", body)?;
        if json {
            writeln!(stdout, "{}", command_body_json("check", body)?)?;
        } else {
            print_check_report(&mut stdout, &report)?;
        }
        Ok(())
    })();
    report_failure(result, path, report_path, "check", json)
}

/// Convert a CAD file to another format.
pub(crate) fn convert(
    inputs: &InputCatalog,
    path: &Path,
    to: Option<&str>,
    conversion: &ConversionArgs,
    args: &DecodeArgs,
) -> CommandResult<()> {
    let result = (|| {
        let policy = ConversionPolicy {
            losses: conversion.losses,
            allow_errors: conversion.allow_errors,
            allow_empty: conversion.allow_empty,
            destination: conversion.destination.clone(),
        };
        let selection = TargetSelection::resolve(to, policy.destination.path())?;
        let target = export_target(selection);
        if let Some(report_path) = conversion.report.as_ref() {
            report_path.check(path)?;
            if let Some(destination) = policy.destination.path() {
                artifact_store::check_distinct_output_paths(
                    destination,
                    "CAD output",
                    &report_path.path,
                    "command report",
                )?;
            }
        }

        let depth = if conversion.full_decode || conversion.losses.needs_full_decode() {
            DecodeDepth::Full
        } else {
            target.needs().request()
        };
        let source = SourceRequest {
            path,
            forced: conversion.forced_input,
            options: args.options_at(depth),
        };
        let prepared = transcoder::prepare(inputs, &source, target, &policy)?;
        let planned = prepared.plan()?;

        let (decode_report, validation) = {
            let prepared = planned.prepared();
            print_load_notice(&prepared.document);
            let mut stderr = io::stderr();
            if let Some(report) = prepared.document.decode_report() {
                print_decode_report(&mut stderr, report)?;
                writeln!(stderr)?;
            }
            print_check_report(&mut stderr, &prepared.validation)?;
            let total = prepared.validation.error_count();
            if total > 0 {
                writeln!(
                    stderr,
                    "check: {} of {total} error(s) in what the {} output writes",
                    planned.carried_errors(),
                    prepared.format().name()
                )?;
            }
            (
                prepared.document.decode_report().cloned(),
                prepared.validation.clone(),
            )
        };
        let emission = planned
            .write()
            .map_err(|error| ApplicationError::from(error).at_stage(RefusalStage::Export))?;
        print_export_emission(&mut io::stderr(), &emission)?;
        if let Err(error) = write_command_report(
            path,
            conversion.report.as_ref(),
            "convert",
            CommandReportBody::Ok {
                decode_report: decode_report.as_ref(),
                check_report: Some(&validation),
                export: Some(&emission.report),
            },
        ) {
            eprintln!(
                "warning: CAD output was written, but the convert report could not be written: {error:#}"
            );
        }
        Ok(())
    })();
    report_failure(result, path, conversion.report.as_ref(), "convert", false)
}

/// Compare two CAD files.
pub(crate) fn diff(
    inputs: &InputCatalog,
    a: DiffInput<'_>,
    b: DiffInput<'_>,
    args: &DecodeArgs,
    json: bool,
    report_path: Option<&FileDestination>,
) -> CommandResult<ExitCode> {
    let result = (|| {
        if let Some(report_path) = report_path {
            report_path.check(a.path)?;
            report_path.check(b.path)?;
        }
        let left = loader::load_artifact(inputs, a.path, args.options(), a.forced)?;
        print_load_notice(&left);
        let right = loader::load_artifact(inputs, b.path, args.options(), b.forced)?;
        print_load_notice(&right);
        let result = cadmpeg_ir::diff(&left.ir, &right.ir);
        let fidelity = fidelity_diff(left.fidelity(), right.fidelity());
        let payload = DiffReportPayload {
            diff: &result,
            source_fidelity: &fidelity,
        };
        write_json_report(a.path, report_path, "diff", &payload)?;
        if json {
            println!("{}", command_report_json("diff", &payload)?);
            return Ok(if payload.different() {
                ExitCode::from(1)
            } else {
                ExitCode::SUCCESS
            });
        }
        println!("diff {} vs {}", a.path.display(), b.path.display());
        if let Some((before, after)) = &result.tolerance_change {
            println!("  tolerances: {before:?} → {after:?}");
        }
        print_source_diff(&result.source)?;
        for arena in &result.per_arena {
            if arena.added.is_empty() && arena.removed.is_empty() && arena.modified.is_empty() {
                continue;
            }
            println!(
                "  {}: +{} -{} ~{}",
                arena.kind,
                arena.added.len(),
                arena.removed.len(),
                arena.modified.len()
            );
            print_id_delta("removed", &arena.removed);
            print_id_delta("added", &arena.added);
            let modified: Vec<String> = arena
                .modified
                .iter()
                .map(|item| format!("{} ({})", item.id, item.fields.join(", ")))
                .collect();
            print_id_delta("modified", &modified);
        }
        print_fidelity_summary(&fidelity);
        if payload.different() {
            Ok(ExitCode::from(1))
        } else {
            println!("  identical");
            Ok(ExitCode::SUCCESS)
        }
    })();
    report_failure(result, a.path, report_path, "diff", json)
}

#[cfg(test)]
mod tests {
    use super::{inspect, inspect_io_error};
    use cadmpeg_core::decode::ResourceLimits;
    use cadmpeg_registry::InputCatalog;
    use std::io;
    use std::path::Path;

    #[test]
    fn inspect_open_errors_name_the_path() {
        let path = Path::new("missing-inspect-input.3dm");
        let error = inspect(
            &InputCatalog::with_builtins(),
            path,
            None,
            false,
            None,
            ResourceLimits::desktop(),
        )
        .unwrap_err();

        assert_eq!(error.to_string(), "opening missing-inspect-input.3dm");
    }

    #[test]
    fn inspect_input_limit_errors_name_the_path_and_limit() {
        let path = Path::new("oversize.3dm");
        let error = inspect_io_error(
            path,
            2,
            io::Error::new(io::ErrorKind::FileTooLarge, "input limit exceeded"),
        );

        assert_eq!(
            error.to_string(),
            format!(
                "{} exceeds the configured 2-byte input limit",
                path.display()
            )
        );
    }
}