cadmpeg 0.6.1

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
#[cfg(feature = "rhino")]
use cadmpeg_test_support::wire;

#[cfg(any(feature = "iges", feature = "step"))]
use std::path::Path;
use std::path::PathBuf;

#[cfg(any(feature = "iges", feature = "rhino", feature = "step"))]
use cadmpeg_ir::codec::write::target::TargetRequest;
use cadmpeg_ir::codec::write::{EncodeInput, Encoder};
use cadmpeg_ir::CadIr;
use cadmpeg_registry::Format;

use crate::application::artifact_store::FileDestination;
use crate::application::document::LoadedDocument;
#[cfg(any(feature = "iges", feature = "rhino", feature = "step"))]
use crate::application::refusal::ConversionRefusal;

#[cfg(any(feature = "iges", feature = "rhino", feature = "step"))]
use super::export_target;
use super::{
    DestinationPolicy, LossPolicy, PreparedConversion, ResolvedDestination, TargetSelection,
};

#[test]
fn loss_policy_assigns_each_refusal_phase() {
    assert_eq!(
        [
            (LossPolicy::Allow, false, false),
            (LossPolicy::RejectDecode, true, false),
            (LossPolicy::RejectExport, false, true),
            (LossPolicy::RejectAny, true, true),
        ],
        [
            (
                LossPolicy::Allow,
                LossPolicy::Allow.rejects_decode(),
                LossPolicy::Allow.rejects_export(),
            ),
            (
                LossPolicy::RejectDecode,
                LossPolicy::RejectDecode.rejects_decode(),
                LossPolicy::RejectDecode.rejects_export(),
            ),
            (
                LossPolicy::RejectExport,
                LossPolicy::RejectExport.rejects_decode(),
                LossPolicy::RejectExport.rejects_export(),
            ),
            (
                LossPolicy::RejectAny,
                LossPolicy::RejectAny.rejects_decode(),
                LossPolicy::RejectAny.rejects_export(),
            ),
        ]
    );
}

#[test]
fn convert_file_destination_discards_binary_stdout_at_clap_admission() {
    use clap::Parser;
    let command = crate::Cli::try_parse_from([
        "cadmpeg",
        "convert",
        "input.step",
        "-o",
        "out.step",
        "--binary-stdout",
    ])
    .unwrap()
    .command;
    let crate::Command::Convert { destinations, .. } = command else {
        panic!("expected convert command");
    };
    assert_eq!(
        destinations.destination,
        DestinationPolicy::File(FileDestination {
            path: PathBuf::from("out.step"),
            overwrite: false,
        })
    );
}

fn prepared(
    ir: CadIr,
    format: Format,
    encoder: Box<dyn Encoder>,
    loss_policy: LossPolicy,
) -> PreparedConversion {
    let validation =
        cadmpeg_ir::validate_neutral(&ir, Vec::new()).expect("resource allocation did not fail");
    PreparedConversion {
        document: LoadedDocument::neutral(ir, 0),
        validation,
        encoder,
        selection: TargetSelection::new(format, None),
        destination: ResolvedDestination::Stdout,
        loss_policy,
    }
}

#[cfg(feature = "iges")]
#[test]
fn encoder_planning_owns_unknown_explicit_target_admission() {
    let mut conversion = prepared(
        CadIr::empty(),
        Format::Iges,
        Box::new(cadmpeg_codec_iges::IgesCodec),
        LossPolicy::Allow,
    );
    conversion.selection.request = Some("nonesuch".into());

    let Err(error) = conversion.plan() else {
        panic!("the encoder must reject an unknown target");
    };
    assert!(matches!(
        error.refusal(),
        Some(ConversionRefusal::UnsupportedTarget { .. })
    ));
}

#[cfg(feature = "step")]
fn step_ir_with_unrepresentable_native_content() -> CadIr {
    let mut ir = CadIr::empty();
    ir.native.namespace_mut("f3d").arenas_mut().insert(
        "asm_histories".into(),
        vec![cadmpeg_ir::NativeRecord::new(
            cadmpeg_ir::ids::Identity::new("f3d:test:asm-history#0").expect("valid identity"),
            serde_json::Map::default(),
        )
        .expect("valid native identity")],
    );
    ir.finalize(&cadmpeg_test_support::service_decode_context())
        .expect("fixture ordering is admitted");
    ir
}

/// STEP planning returns concrete loss rows, and the shared application
/// gate names them when export-loss rejection is active.
#[cfg(feature = "step")]
#[test]
fn step_export_losses_are_rejected_by_the_shared_plan_gate() {
    let conversion = prepared(
        step_ir_with_unrepresentable_native_content(),
        Format::Step,
        Box::new(cadmpeg_codec_step::StepCodec::default()),
        LossPolicy::RejectExport,
    );
    let Err(error) = conversion.plan() else {
        panic!("the plan loss must refuse");
    };
    let refusal = error
        .refusal()
        .expect("the shared gate returns a typed refusal");
    assert!(
        matches!(refusal, ConversionRefusal::ExportLossRejected { .. }),
        "{refusal:?}"
    );
    let message = refusal.evidence().message;
    assert!(message.contains("source-native record(s)"), "{message}");
    let report = refusal
        .evidence()
        .reports
        .export
        .expect("the refusal retains the completed export plan report");
    assert!(
        report
            .losses
            .iter()
            .any(|loss| loss.message.contains("source-native record(s)")),
        "{:?}",
        report.losses
    );
}

/// Without export-loss rejection the same STEP plan succeeds and retains
/// the loss rows for the caller and report.
#[cfg(feature = "step")]
#[test]
fn step_export_losses_remain_on_the_plan_without_rejection() {
    let conversion = prepared(
        step_ir_with_unrepresentable_native_content(),
        Format::Step,
        Box::new(cadmpeg_codec_step::StepCodec::default()),
        LossPolicy::Allow,
    );
    let planned = conversion.plan().expect("loss reporting is not refusal");
    assert!(
        planned
            .plan
            .report()
            .losses
            .iter()
            .any(|loss| loss.message.contains("source-native record(s)")),
        "{:?}",
        planned.plan.report().losses
    );
}

/// A Rhino write omits product structure it cannot represent. The wrapper
/// charges that omission as an export loss, so the shared gate refuses it.
#[cfg(feature = "rhino")]
#[test]
fn rhino_omitted_product_structure_is_rejected_by_the_shared_plan_gate() {
    let mut ir = CadIr::empty();
    ir.model.points.push(cadmpeg_ir::topology::Point::new(
        cadmpeg_ir::ids::PointId::mint("cadir:model:point#pin").expect("identity grammar"),
        cadmpeg_ir::features::FinitePoint3::new(cadmpeg_ir::math::Point3::new(0.0, 0.0, 0.0))
            .expect("finite position"),
        None,
    ));
    ir.model
        .product_definitions
        .push(cadmpeg_ir::products::ProductDefinition {
            id: "cadir:model:product#group"
                .try_into()
                .expect("valid identity"),
            kind: cadmpeg_ir::products::ProductDefinitionKind::Group,
            source_name: Some("Group".into()),
            label: None,
            description: None,
            part_number: None,
            bom_properties: std::collections::BTreeMap::new(),
            bodies: Vec::new(),
            native_ref: None,
        });
    let conversion = prepared(
        ir,
        Format::Rhino,
        Box::new(cadmpeg_codec_rhino::RhinoCodec),
        LossPolicy::RejectExport,
    );
    let Err(error) = conversion.plan() else {
        panic!("the omitted product definition must refuse");
    };
    let refusal = error
        .refusal()
        .expect("the shared gate returns a typed refusal");
    let ConversionRefusal::ExportLossRejected { export_report, .. } = refusal else {
        panic!("{refusal:?}");
    };
    assert!(
        export_report
            .losses
            .iter()
            .any(|loss| loss.message.contains("model arena `product_definitions`")),
        "{:?}",
        export_report.losses
    );
}

struct NotImplementedEncoder;

impl cadmpeg_ir::codec::write::EncoderBackend for NotImplementedEncoder {
    const FORMAT: cadmpeg_ir::codec::FormatId =
        cadmpeg_ir::codec::FormatId::new("not-implemented-test");
    type Target = cadmpeg_ir::codec::write::target::DialectFree;
    const TARGET: Self::Target = cadmpeg_ir::codec::write::target::DialectFree;

    fn plan_resolved(
        &self,
        _input: EncodeInput<'_>,
        _target: (),
    ) -> Result<cadmpeg_ir::codec::write::ExportBody, cadmpeg_core::CodecError> {
        Err(cadmpeg_core::CodecError::NotImplemented(
            "writer path is not implemented".into(),
        ))
    }
}

/// A writer implementation failure is not evidence of an export loss,
/// even when the application would reject real plan losses.
#[test]
fn not_implemented_plan_failure_is_not_reclassified_as_export_loss() {
    let conversion = prepared(
        CadIr::empty(),
        Format::Cadir,
        Box::new(NotImplementedEncoder),
        LossPolicy::RejectExport,
    );
    let Err(error) = conversion.plan() else {
        panic!("the synthetic writer is not implemented");
    };
    assert_eq!(
        error.to_string(),
        "not implemented yet: writer path is not implemented"
    );
    assert!(error.refusal().is_none());
}

/// Flag absence is always `Inherit`; the encoder decides what that means.
///
/// The selection is an owned-string adapter and nothing else. The
/// cross-format catalog default is owned by write resolution, so the command
/// line does not decide it a second time.
#[cfg(feature = "iges")]
#[test]
fn flag_absence_is_always_an_inherit_request() {
    assert_eq!(
        TargetSelection::new(Format::Iges, None).request(),
        TargetRequest::Inherit
    );
    let named = TargetSelection::new(Format::Iges, Some("iges:5.1-fixed-ascii".to_owned()));
    assert_eq!(
        named.request(),
        TargetRequest::Explicit("iges:5.1-fixed-ascii")
    );
}

#[cfg(feature = "iges")]
#[test]
fn target_selection_owns_format_and_dialect_grammar() {
    let format_only = TargetSelection::resolve(Some("iges"), None).expect("format resolves");
    assert_eq!(format_only.format, Format::Iges);
    assert_eq!(format_only.request(), TargetRequest::Inherit);

    let qualified = TargetSelection::resolve(Some("iges:5.1"), None).expect("alias resolves");
    assert_eq!(qualified.format, Format::Iges);
    assert_eq!(qualified.request(), TargetRequest::Explicit("5.1"));

    let inferred = TargetSelection::resolve(Some("5.1"), Some(Path::new("part.iges")))
        .expect("output extension supplies the format");
    assert_eq!(inferred.format, Format::Iges);
    assert_eq!(inferred.request(), TargetRequest::Explicit("5.1"));
}

#[cfg(feature = "step")]
#[test]
fn a_format_alias_does_not_become_a_dialect_request() {
    let selection = TargetSelection::resolve(Some("stp"), Some(Path::new("part.stp")))
        .expect("the identity registry owns the STEP alias");
    assert_eq!(selection.format, Format::Step);
    assert_eq!(selection.request(), TargetRequest::Inherit);
}

#[test]
fn target_selection_rejects_an_empty_qualified_dialect() {
    let error = TargetSelection::resolve(Some("cadir:"), None).unwrap_err();
    assert!(error.to_string().contains("nothing after the colon"));
    assert!(error.refusal().is_none());
}

/// Export-loss rejection is not a target.
///
/// A loss flag that also named a target would turn `convert a.step -o
/// b.step --reject-lossy=export` into an explicit AP214 request and lose
/// the identity default. Only `--to` may say what to write.
#[cfg(feature = "step")]
#[test]
fn rejecting_export_losses_does_not_name_a_target() {
    let target = export_target(TargetSelection::new(Format::Step, None));

    assert!(target.selection.request.is_none(), "{:?}", target.selection);
    assert_eq!(target.selection.request(), TargetRequest::Inherit);

    let named = export_target(TargetSelection::new(
        Format::Step,
        Some("step:ap242-e3".to_owned()),
    ));
    assert_eq!(
        named.selection.request(),
        TargetRequest::Explicit("step:ap242-e3")
    );
}

/// `--to` carries the dialect half verbatim; the encoder resolves it.
///
/// Both spellings the grammar admits reach `plan` unchanged, and both
/// resolve, because catalog lookup matches a row by id or by alias.
/// Resolving here instead would put a second copy of every catalog in the
/// CLI, which is the drift the registries exist to kill.
#[cfg(feature = "rhino")]
#[test]
fn an_alias_and_an_id_reach_the_encoder_unresolved_and_both_resolve() {
    use cadmpeg_core::dialect::DialectId;

    let ir = CadIr::empty();
    for spelling in ["archive-60", "60"] {
        let target = export_target(TargetSelection::new(
            Format::Rhino,
            Some(spelling.to_owned()),
        ));
        assert_eq!(
            target.selection.request(),
            TargetRequest::Explicit(spelling)
        );
        let plan = target
            .encoder
            .plan(
                EncodeInput::new(&ir, None),
                TargetRequest::Explicit(spelling),
            )
            .expect("the catalog carries the row under both spellings");
        assert_eq!(
            wire::field_or_default::<Option<cadmpeg_core::dialect::DialectId>>(
                plan.report(),
                "identity/target"
            )
            .as_ref()
            .map(DialectId::as_str),
            Some("rhino:archive-60")
        );
    }
}

/// A dialect outside the catalog reaches the encoder and is refused by the
/// sealed planning boundary.
#[cfg(feature = "iges")]
#[test]
fn an_unknown_dialect_is_refused_by_plan_with_its_catalog() {
    let target = export_target(TargetSelection::new(
        Format::Iges,
        Some("ap242e3".to_owned()),
    ));
    let error = target
        .encoder
        .plan(
            EncodeInput::new(&CadIr::empty(), None),
            target.selection.request(),
        )
        .expect_err("a STEP alias is not an IGES target");
    let message = error.to_string();
    assert!(message.contains("ap242e3"), "{message}");
    assert!(message.contains("iges:5.3-fixed-ascii"), "{message}");
}

#[test]
fn loss_policy_cli_preserves_omission_and_rejects_allow_spelling() {
    use clap::Parser;
    for (flag, expected) in [
        (None, LossPolicy::Allow),
        (Some("--reject-lossy"), LossPolicy::RejectAny),
        (Some("--reject-lossy=decode"), LossPolicy::RejectDecode),
        (Some("--reject-lossy=export"), LossPolicy::RejectExport),
        (Some("--reject-lossy=any"), LossPolicy::RejectAny),
    ] {
        let mut args = vec!["cadmpeg", "convert", "input.step"];
        args.extend(flag);
        let crate::Command::Convert { reject_lossy, .. } =
            crate::Cli::try_parse_from(args).unwrap().command
        else {
            panic!("expected convert command");
        };
        assert_eq!(reject_lossy.unwrap_or_default(), expected);
    }
    let error =
        crate::Cli::try_parse_from(["cadmpeg", "convert", "input.step", "--reject-lossy=allow"])
            .unwrap_err();
    assert_eq!(error.kind(), clap::error::ErrorKind::InvalidValue);
}