cadmpeg 0.6.6

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
652
653
654
655
656
657
658
659
// SPDX-License-Identifier: Apache-2.0
//! Refusals and exit statuses: what the CLI declines to do, and how it says so.

use std::fs;

use assert_cmd::Command;
use cadmpeg_ir::examples::unit_cube;
use predicates::prelude::{predicate, PredicateBooleanExt};
use tempfile::tempdir;

use crate::support::{fixture, geometryless_creo, minimal_rhino_archive};

#[test]
fn garbage_reports_supported_formats() {
    let dir = tempdir().unwrap();
    let input = dir.path().join("garbage.bin");
    fs::write(&input, b"not a CAD file").unwrap();
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args(["check", input.to_str().unwrap()])
        .assert()
        .code(2)
        .stderr(predicate::str::contains(
            "supported: FCStd, f3d, Inventor IPT/IAM, sldprt, CATPart, NX/Creo prt, Rhino 3DM, IGES, STEP",
        ));
}

#[test]
fn exit_codes_distinguish_semantic_and_operational_failures() {
    let dir = tempdir().unwrap();
    let garbage = dir.path().join("garbage");
    fs::write(&garbage, b"garbage").unwrap();
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args(["dump", garbage.to_str().unwrap()])
        .assert()
        .code(2);
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args(["diff", garbage.to_str().unwrap(), garbage.to_str().unwrap()])
        .assert()
        .code(2);

    let mut invalid = unit_cube().expect("unit cube fixture is admitted");
    invalid.model.faces[0].surface = cadmpeg_ir::ids::SurfaceId::mint("test:model:surface#missing")
        .expect("valid identity for an absent surface");
    let invalid = fixture(dir.path(), "invalid.json", &invalid);
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args(["check", invalid.to_str().unwrap()])
        .assert()
        .code(1);
}

#[test]
fn reject_lossy_refuses_lossy_export_as_a_model_refusal() {
    let dir = tempdir().unwrap();
    let lossy = geometryless_creo(dir.path(), "lossy.prt");

    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            lossy.to_str().unwrap(),
            "-f",
            "step",
            "--allow-empty",
            "--reject-lossy",
        ])
        .assert()
        .code(1)
        .stderr(predicate::str::contains("refusing to write a lossy"));

    let report = dir.path().join("lossy-report.json");
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            lossy.to_str().unwrap(),
            "-f",
            "step",
            "--allow-empty",
            "--reject-lossy",
            "--report",
            report.to_str().unwrap(),
        ])
        .assert()
        .code(1);
    let value: serde_json::Value = serde_json::from_slice(&fs::read(report).unwrap()).unwrap();
    assert!(value["decode_report"].is_object());
    assert!(value["export"].is_null());

    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            lossy.to_str().unwrap(),
            "-f",
            "step",
            "--allow-empty",
        ])
        .assert()
        .success();
}

#[test]
fn strict_decode_refusal_is_semantic_and_serializes_the_completed_report() {
    let dir = tempdir().unwrap();
    let input = minimal_rhino_archive(dir.path(), "undeclared.3dm", "100");

    for (command, extra) in [
        ("dump", Vec::<&str>::new()),
        ("convert", vec!["--to", "cadir", "--reject-lossy"]),
    ] {
        let report = dir.path().join(format!("{command}-strict-report.json"));
        let mut args = vec![command, input.to_str().unwrap(), "--no-salvage"];
        args.extend(extra);
        args.extend(["--report", report.to_str().unwrap()]);

        Command::cargo_bin("cadmpeg")
            .unwrap()
            .args(args)
            .assert()
            .code(1)
            .stderr(predicate::str::contains("strict mode rejects"));

        let value: serde_json::Value = serde_json::from_slice(&fs::read(&report).unwrap()).unwrap();
        assert_eq!(value["status"], "refused");
        assert_eq!(value["refusal"]["stage"], "decode");
        assert_eq!(value["refusal"]["code"], "strict_decode_rejected");
        let decode_report = value["decode_report"]
            .as_object()
            .expect("strict refusal keeps its completed decode report");
        assert!(decode_report["losses"]
            .as_array()
            .unwrap()
            .iter()
            .any(|loss| {
                loss["code"]["namespace"] == "rhino"
                    && loss["code"]["code"] == "source.dialect-unverified"
            }));
    }
}

#[test]
fn convert_rejects_empty_native_geometry_unless_allowed() {
    let dir = tempdir().unwrap();
    let input = geometryless_creo(dir.path(), "empty.prt");
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args(["convert", input.to_str().unwrap(), "-f", "step"])
        .assert()
        .code(1)
        .stderr(predicate::str::contains("--allow-empty"));
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            input.to_str().unwrap(),
            "-f",
            "step",
            "--allow-empty",
        ])
        .assert()
        .success()
        .stdout(predicate::str::starts_with("ISO-10303-21"));
}

/// A container-only document is shallower than a geometry encoder plans from,
/// so the refusal names the depth and `--allow-empty` does not override it.
#[test]
fn convert_refuses_container_only_geometry_at_its_depth() {
    let dir = tempdir().unwrap();
    let input = geometryless_creo(dir.path(), "empty.prt");
    for allow_empty in [false, true] {
        let report = dir.path().join(format!("depth-{allow_empty}.json"));
        let mut args = vec![
            "convert",
            input.to_str().unwrap(),
            "-f",
            "step",
            "--container-only",
            "--report",
            report.to_str().unwrap(),
        ];
        if allow_empty {
            args.push("--allow-empty");
        }
        Command::cargo_bin("cadmpeg")
            .unwrap()
            .args(args)
            .assert()
            .code(1)
            .stdout(predicate::str::is_empty())
            .stderr(predicate::str::contains(
                "the step encoder needs a geometry-depth decode, but the document records container depth",
            ));
        let value: serde_json::Value = serde_json::from_slice(&fs::read(&report).unwrap()).unwrap();
        assert_eq!(value["refusal"]["stage"], "plan");
        assert_eq!(value["refusal"]["code"], "insufficient_depth");
        assert_eq!(value["refusal"]["depth"]["needed"], "geometry");
        assert_eq!(value["refusal"]["depth"]["recorded"], "container");
    }
}

/// The format half of `--to` is checked before the input is opened.
///
/// A format this build cannot write is wrong whatever the source turns out to
/// be, so it fails against an absent path as a typed plan refusal. A dialect
/// token is admitted by the selected encoder's catalog at the same static
/// boundary.
#[test]
fn an_unwritable_output_format_refuses_before_reading_input() {
    let dir = tempdir().unwrap();
    let missing = dir.path().join("does-not-exist.cadir.json");
    let path = missing.to_str().unwrap();

    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args(["convert", path, "--to", "catia:v5"])
        .assert()
        .code(1)
        .stderr(
            predicate::str::contains("catia is not an output format of this build")
                .and(predicate::str::contains("step")),
        );

    let output = dir.path().join("out.igs");
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            path,
            "--to",
            "catia",
            "-o",
            output.to_str().unwrap(),
        ])
        .assert()
        .code(1)
        .stderr(predicate::str::contains(
            "catia is not an output format of this build",
        ));

    let input = fixture(
        dir.path(),
        "cube.cadir.json",
        &unit_cube().expect("unit cube fixture is admitted"),
    );
    let report = dir.path().join("unwritable-format-report.json");
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            input.to_str().unwrap(),
            "--to",
            "catia:v5",
            "--report",
            report.to_str().unwrap(),
        ])
        .assert()
        .code(1);
    let value: serde_json::Value = serde_json::from_slice(&fs::read(report).unwrap()).unwrap();
    assert_eq!(value["refusal"]["stage"], "plan");
    assert_eq!(value["refusal"]["code"], "unsupported_output_format");
    assert!(value["decode_report"].is_null());

    let missing_report = dir.path().join("missing-input-report.json");
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            path,
            "--to",
            "5.1",
            "-o",
            output.to_str().unwrap(),
            "--report",
            missing_report.to_str().unwrap(),
        ])
        .assert()
        .code(2)
        .stderr(
            predicate::str::contains(format!("opening {}", missing.display()))
                .and(predicate::str::contains("not an output format").not()),
        );

    // A bare value that names neither a format nor an inferable one: there is
    // no output path to read a format from, so nothing can be resolved.
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args(["convert", path, "--to", "ap242e3"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains(
            "no output path to read a format from",
        ));

    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args(["convert", path, "--to", "step:"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("nothing after the colon"));
}

/// A dialect outside the encoder's catalog is refused with that catalog by the
/// encoder plan.
///
/// This is the whole error surface the deleted `--iges-target requires IGES
/// output` strings used to hand-write. The catalog in the message comes from
/// `Encoder::targets()`, so it reflects the build's own feature set.
#[test]
fn an_unknown_dialect_is_refused_with_the_encoder_catalog() {
    let dir = tempdir().unwrap();
    let input = fixture(
        dir.path(),
        "cube.cadir.json",
        &unit_cube().expect("unit cube fixture is admitted"),
    );
    let output = dir.path().join("cube.igs");

    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            input.to_str().unwrap(),
            "-o",
            output.to_str().unwrap(),
            "--to",
            "ap242e3",
            "--allow-errors",
        ])
        .assert()
        .code(1)
        .stderr(
            predicate::str::contains("ap242e3")
                .and(predicate::str::contains("iges:5.3-fixed-ascii"))
                .and(predicate::str::contains("iges:4.0-fixed-ascii")),
        );
    assert!(!output.exists());

    let native_input = dir.path().join("native-cube.igs");
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            input.to_str().unwrap(),
            "-o",
            native_input.to_str().unwrap(),
            "--allow-errors",
        ])
        .assert()
        .success();
    let report = dir.path().join("unsupported-target-report.json");
    let refused_output = dir.path().join("refused.igs");
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            native_input.to_str().unwrap(),
            "-o",
            refused_output.to_str().unwrap(),
            "--to",
            "9.9",
            "--report",
            report.to_str().unwrap(),
            "--allow-errors",
        ])
        .assert()
        .code(1)
        .stderr(predicate::str::contains("iges cannot write 9.9"));
    let value: serde_json::Value = serde_json::from_slice(&fs::read(&report).unwrap()).unwrap();
    assert_eq!(value["refusal"]["code"], "unsupported_target");
    assert_eq!(
        value["refusal"]["target"]["refusal"]["kind"],
        "unknown_explicit"
    );
    assert_eq!(value["refusal"]["target"]["format"], "iges");
    assert_eq!(value["refusal"]["target"]["refusal"]["requested"], "9.9");
    assert!(value["refusal"]["target"]["available"]
        .as_array()
        .is_some_and(|available| !available.is_empty()));
    assert!(value["decode_report"].is_object());
    assert!(value["decode_report"]["identity"]["dialects"].is_object());
    assert!(value["check_report"].is_object());

    // Destination safety is checked before input work or planning. An existing
    // report path therefore wins before dialect admission.
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            native_input.to_str().unwrap(),
            "-o",
            refused_output.to_str().unwrap(),
            "--to",
            "8.8",
            "--report",
            report.to_str().unwrap(),
            "--allow-errors",
        ])
        .assert()
        .code(2)
        .stderr(
            predicate::str::contains("exists; pass --force")
                .and(predicate::str::contains("iges cannot write 8.8").not()),
        );

    // Dialect admission follows input loading because the encoder plan is its
    // only owner. A missing input therefore fails before dialect resolution.
    let missing_input = dir.path().join("missing.cadir.json");
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            missing_input.to_str().unwrap(),
            "-o",
            refused_output.to_str().unwrap(),
            "--to",
            "9.9",
        ])
        .assert()
        .code(2)
        .stderr(
            predicate::str::contains("error: opening")
                .and(predicate::str::contains("missing.cadir.json"))
                .and(predicate::str::contains("iges cannot write 9.9").not()),
        );

    // A format-qualified token outside the catalog is the same refusal. The
    // encoder receives the token after the colon unchanged.
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            input.to_str().unwrap(),
            "-f",
            "step:ap999",
            "--allow-errors",
        ])
        .assert()
        .code(1)
        .stderr(
            predicate::str::contains("step cannot write ap999")
                .and(predicate::str::contains("step:ap242-e3")),
        );
}

/// Archive word 5 is a read-only dialect, not shorthand for archive 50.
#[test]
fn rhino_word_5_is_refused_with_the_encoder_catalog() {
    let dir = tempdir().unwrap();
    let input = fixture(
        dir.path(),
        "cube.cadir.json",
        &unit_cube().expect("unit cube fixture is admitted"),
    );
    let output = dir.path().join("cube.3dm");

    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            input.to_str().unwrap(),
            "-o",
            output.to_str().unwrap(),
            "--to",
            "5",
            "--allow-errors",
        ])
        .assert()
        .code(1)
        .stderr(
            predicate::str::contains("rhino cannot write 5")
                .and(predicate::str::contains("rhino:archive-50"))
                .and(predicate::str::contains("rhino:archive-80")),
        );
    assert!(!output.exists());
}

/// `--reject-lossy` takes an optional scope, and each scope refuses on its own
/// half of the loss surface.
///
/// The same Creo file loses content on both sides, and the two scopes name
/// different stages for it: `decode` reports what the reader could not carry,
/// `export` what the writer will not emit. Both are negative verdicts, so both
/// exit 1 rather than 2. A file that loses nothing is written under every
/// scope, which is what proves the scope is a predicate and not a switch that
/// refuses on sight.
#[test]
fn reject_lossy_scopes_select_which_losses_refuse() {
    let dir = tempdir().unwrap();
    let lossy = geometryless_creo(dir.path(), "lossy.prt");
    let path = lossy.to_str().unwrap();
    let export_report = dir.path().join("export-loss-refusal.json");

    for scope in [
        "--reject-lossy",
        "--reject-lossy=decode",
        "--reject-lossy=any",
    ] {
        Command::cargo_bin("cadmpeg")
            .unwrap()
            .args(["convert", path, "-f", "step", "--allow-empty", scope])
            .assert()
            .code(1)
            .stderr(predicate::str::contains("decode reported"));
    }

    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            path,
            "-f",
            "step",
            "--allow-empty",
            "--reject-lossy=export",
            "--report",
            export_report.to_str().unwrap(),
        ])
        .assert()
        .code(1)
        .stderr(
            predicate::str::contains("export planning reported 1 loss(es)")
                .and(predicate::str::contains(
                    "uninterpreted passthrough record(s)",
                ))
                .and(predicate::str::contains("decode reported").not()),
        );
    let report: serde_json::Value =
        serde_json::from_slice(&fs::read(export_report).unwrap()).unwrap();
    assert_eq!(report["refusal"]["code"], "export_loss_rejected");
    assert!(report["export"].is_object());
    assert_eq!(report["export"]["identity"]["payload"], "native");
    assert_eq!(report["export"]["losses"].as_array().unwrap().len(), 1);

    let lossless = fixture(
        dir.path(),
        "cube.cadir.json",
        &unit_cube().expect("unit cube fixture is admitted"),
    );
    for scope in [
        "--reject-lossy",
        "--reject-lossy=decode",
        "--reject-lossy=export",
    ] {
        Command::cargo_bin("cadmpeg")
            .unwrap()
            .args(["convert", lossless.to_str().unwrap(), "-f", "step", scope])
            .assert()
            .success();
    }

    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "convert",
            path,
            "-f",
            "step",
            "--allow-empty",
            "--reject-lossy=nonesuch",
        ])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("invalid value"));
}

#[test]
fn json_on_artifact_commands_is_a_teaching_error() {
    let dir = tempdir().unwrap();
    let ir = unit_cube().expect("unit cube fixture is admitted");
    let model = fixture(dir.path(), "cube.cadir.json", &ir);
    let path = model.to_str().unwrap();

    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args(["dump", path, "--json"])
        .assert()
        .code(2)
        .stderr(
            predicate::str::contains("already JSON").and(predicate::str::contains("cadmpeg query")),
        );

    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args(["convert", path, "--json"])
        .assert()
        .code(2)
        .stderr(
            predicate::str::contains("not an output selector")
                .and(predicate::str::contains("--report")),
        );
}

#[test]
fn report_to_an_unwritable_path_is_an_operational_error() {
    let dir = tempdir().unwrap();
    let input = fixture(
        dir.path(),
        "cube.cadir.json",
        &unit_cube().expect("unit cube fixture is admitted"),
    );
    let report = dir.path().join("missing-subdir").join("report.json");
    Command::cargo_bin("cadmpeg")
        .unwrap()
        .args([
            "check",
            input.to_str().unwrap(),
            "--report",
            report.to_str().unwrap(),
        ])
        .assert()
        .code(2);
    assert!(!report.exists());
}

#[cfg(unix)]
#[test]
fn closed_stdout_pipe_exits_on_sigpipe_without_panic() {
    use std::io::Read;
    use std::os::unix::process::ExitStatusExt;
    use std::process::{Command as ProcessCommand, Stdio};

    // Hex of 64 KiB exceeds the typical pipe buffer, so the writer is still
    // printing when the reader closes.
    let dir = tempdir().unwrap();
    let input = dir.path().join("zeros.bin");
    fs::write(&input, vec![0u8; 64 * 1024]).unwrap();

    let mut child = ProcessCommand::new(assert_cmd::cargo::cargo_bin("cadmpeg"))
        .args(["inspect", "hex", input.to_str().unwrap(), "--len", "65536"])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();

    let mut stdout = child.stdout.take().unwrap();
    let mut first = [0u8; 1];
    stdout.read_exact(&mut first).unwrap();
    drop(stdout);

    let mut stderr = child.stderr.take().unwrap();
    let status = child.wait().unwrap();
    let mut err = String::new();
    stderr.read_to_string(&mut err).unwrap();

    assert!(
        !err.contains("panicked"),
        "closed stdout pipe panicked:\n{err}"
    );
    assert_eq!(
        status.signal(),
        Some(13),
        "expected SIGPIPE, got {status:?}; stderr={err}"
    );
}