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
// SPDX-License-Identifier: Apache-2.0
#![cfg_attr(test, allow(clippy::unwrap_used))]
//! The `cadmpeg` command-line interface.
//!
//! Convert native CAD files between formats, inspect their contents, and
//! compare two files. See the package README for workflows, format limits,
//! loss reporting, and exit-status semantics.
mod application;
mod commands;
mod input_format;
mod inspect;
mod loader;
mod query;
mod registry_view;
mod reject_json;
use std::path::PathBuf;
use std::process::ExitCode;
use cadmpeg_registry::{ForcedInput, InputCatalog};
use clap::{Args, Parser, Subcommand, ValueEnum};
use registry_view::{print_dialects, print_formats};
use crate::application::artifact_store::{OptionalFileDestination, OutputDestinations};
use crate::application::transcoder::{ConversionDestinations, DestinationPolicy, LossPolicy};
#[derive(Debug, Parser)]
#[command(
name = "cadmpeg",
version,
about = "Convert and inspect native CAD files.",
long_about = "Convert and inspect native CAD files.\n\n\
Reads vendor CAD files and writes them in another format.",
after_help = "Examples:\n \
cadmpeg convert part.sldprt -o part.step\n \
cadmpeg inspect part.sldprt\n \
cadmpeg diff a.sldprt b.step\n\n\
Exit codes: 0 success, 1 negative verdict (failed check, refused write, files differ), 2 operational error."
)]
struct Cli {
/// Operation to perform.
#[command(subcommand)]
command: Command,
}
#[derive(Debug, Clone, Args)]
struct InputArgs {
/// Treat the input as this format.
#[arg(
long,
visible_alias = "from",
value_parser = crate::input_format::input_format_parser()
)]
input_format: Option<ForcedInput>,
}
#[derive(Debug, Clone, Args)]
struct DecodeArgs {
/// Read the container only; do not decode geometry. `convert` then writes
/// CADIR only and refuses every other output format.
#[arg(long)]
container_only: bool,
/// Fail if required content cannot be decoded. Salvage is off.
#[arg(long)]
no_salvage: bool,
/// Resource-limit profile: `desktop` (generous, the default) or `service`
/// (tight ceilings for unattended use).
#[arg(long, value_enum, default_value_t = LimitProfile::Desktop)]
limits: LimitProfile,
/// Override the profile's maximum number of physical input bytes.
#[arg(long)]
max_input_bytes: Option<u64>,
}
/// Which caller-owned resource-limit profile a decode runs under.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum LimitProfile {
/// Generous ceilings for interactive desktop use.
Desktop,
/// Tight ceilings for unattended service use.
Service,
}
impl DecodeArgs {
/// Options for a full decode, or a container-only one on request.
fn options(&self) -> cadmpeg_ir::DecodeOptions {
self.options_at(cadmpeg_core::decode::DecodeDepth::Full)
}
/// Options for a decode at `depth`, or a container-only one on request.
fn options_at(&self, depth: cadmpeg_core::decode::DecodeDepth) -> cadmpeg_ir::DecodeOptions {
let limits = self.limits.limits(self.max_input_bytes);
let mode = if self.no_salvage {
cadmpeg_core::decode::DecodeMode::Strict
} else {
cadmpeg_core::decode::DecodeMode::Salvage
};
let depth = if self.container_only {
cadmpeg_core::decode::DecodeDepth::Container
} else {
depth
};
cadmpeg_ir::DecodeOptions {
depth,
policy: cadmpeg_core::decode::DecodePolicy { mode, limits },
}
}
}
impl LimitProfile {
const fn limits(self, max_input_bytes: Option<u64>) -> cadmpeg_core::decode::ResourceLimits {
let mut limits = match self {
LimitProfile::Desktop => cadmpeg_core::decode::ResourceLimits::desktop(),
LimitProfile::Service => cadmpeg_core::decode::ResourceLimits::service(),
};
if let Some(max_input_bytes) = max_input_bytes {
limits.max_input_bytes = max_input_bytes;
}
limits
}
}
#[derive(Debug, Subcommand)]
enum Command {
/// Convert a CAD file to another format.
///
/// Reads a CAD file, checks it, and writes another format.
/// The output path's extension selects the format. Pass `--to` when writing to stdout.
///
/// `--to FORMAT:DIALECT` names the output dialect as well as the format.
/// With no `--to`, a same-format conversion keeps the dialect the input
/// already is, and a cross-format conversion writes the format's default.
///
/// Convert refuses when the check finds an error in what the output writes. `--allow-errors` writes the file anyway.
#[command(
display_order = 1,
after_help = "Examples:\n cadmpeg convert part.sldprt -o part.step\n cadmpeg convert part.sldprt -o out.3dm --to rhino:archive-80\n cadmpeg convert part.f3d -o out.igs --to 5.1\n cadmpeg convert part.f3d --to step"
)]
Convert {
#[command(flatten)]
file: inspect::FileArg,
#[command(flatten)]
_reject_json: crate::reject_json::RejectJson,
/// Output format and dialect: `FORMAT`, `FORMAT:DIALECT`, or a bare
/// dialect of the format the output path implies. Inferred from the
/// output extension when omitted.
#[arg(short, long, visible_alias = "to", value_name = "FORMAT[:DIALECT]")]
format: Option<String>,
#[command(flatten)]
destinations: ConversionDestinations,
/// Write output even if the check finds errors in what the output writes. The check runs and prints every finding.
#[arg(long)]
allow_errors: bool,
/// Write output even if no geometry was decoded.
#[arg(long)]
allow_empty: bool,
/// Decode the whole source, design intent included, even when the
/// output format needs only its geometry.
#[arg(long, conflicts_with = "container_only")]
full_decode: bool,
/// Do not write if a loss was reported. `--reject-lossy=decode` refuses
/// only on decode loss, `=export` only on export loss, and the bare
/// flag on either. Every scope decodes the whole source, as
/// `--full-decode` does, so a loss in its design intent counts.
#[arg(
long,
value_enum,
num_args = 0..=1,
require_equals = true,
default_missing_value = "any",
value_name = "SCOPE"
)]
reject_lossy: Option<LossPolicy>,
#[command(flatten)]
input_args: InputArgs,
#[command(flatten)]
decode: DecodeArgs,
},
/// List the formats this build reads and writes.
#[command(display_order = 7)]
Formats,
/// List the dialects of each format, and what this build does with them.
///
/// The identity registry crossed with the capability registry: which
/// dialects exist, how well each is read, and which are write targets of
/// this build's encoders.
#[command(
display_order = 8,
after_help = "Examples:\n cadmpeg dialects\n cadmpeg dialects rhino"
)]
Dialects {
/// Show only this format's rows.
format: Option<String>,
},
/// Show what is inside a CAD file.
///
/// Prints the format, container layout, and stored streams.
///
/// Byte tools (hex, find, extract, ...) dump raw bytes. They work on any file.
///
/// `query` prints tables from JSON that `convert` and `dump` write. `inspect` reads the CAD file.
#[command(
display_order = 2,
args_conflicts_with_subcommands = true,
subcommand_negates_reqs = true,
subcommand_help_heading = "Byte tools",
after_help = "Examples:\n cadmpeg inspect part.sldprt"
)]
Inspect(inspect::InspectArgs),
/// Write a CAD file as CADIR JSON.
///
/// CADIR is cadmpeg's JSON form of a model. dump does not check.
///
/// `convert` checks and writes another CAD format. Use dump when you want the JSON.
#[command(
display_order = 5,
after_help = "Examples:\n cadmpeg dump part.sldprt -o part.cadir.json"
)]
Dump {
#[command(flatten)]
file: inspect::FileArg,
#[command(flatten)]
_reject_json: crate::reject_json::RejectJson,
#[command(flatten)]
destinations: OutputDestinations,
#[command(flatten)]
input_args: InputArgs,
#[command(flatten)]
decode: DecodeArgs,
},
/// Print a table from a report or CADIR JSON.
///
/// Reads JSON from `--report`, from dump, or from a decode sidecar.
#[command(
display_order = 6,
subcommand_help_heading = "Views",
after_help = "Examples:\n cadmpeg query losses part.convert.json\n cadmpeg query counts part.cadir.json\n cadmpeg query graph part.cadir.json model.features ID\n cadmpeg query join part.cadir.json model.features native.rhino.unknowns --left-key native_ref --right-key id"
)]
Query {
/// Table to print.
#[command(subcommand)]
view: query::QueryView,
},
/// Check a CAD file for errors.
///
/// Accepts a native CAD file or CADIR JSON.
#[command(
mut_arg("output", |arg| arg.long("report").visible_alias("output").help("Write a JSON report to this file")),
display_order = 4,
after_help = "Examples:\n cadmpeg check part.sldprt"
)]
Check {
#[command(flatten)]
file: inspect::FileArg,
/// Write JSON to standard output.
#[arg(long)]
json: bool,
#[command(flatten)]
report: OptionalFileDestination,
#[command(flatten)]
input_args: InputArgs,
#[command(flatten)]
decode: DecodeArgs,
},
/// Compare two CAD files.
///
/// Compares decoded geometry and topology of two files.
/// Accepts native CAD files or CADIR JSON.
#[command(
mut_arg("output", |arg| arg.long("report").visible_alias("output").help("Write a JSON report to this file")),
display_order = 3,
after_help = "Examples:\n cadmpeg diff a.sldprt b.step\n cadmpeg diff before.f3d after.f3d\n\n\
Exit status 1 means the models differ.\n\
`inspect cmp` compares raw bytes, not decoded models."
)]
Diff {
/// First CAD file.
a: PathBuf,
/// Second CAD file.
b: PathBuf,
/// Treat the first file as this format.
#[arg(
long,
value_parser = crate::input_format::input_format_parser()
)]
input_format_a: Option<ForcedInput>,
/// Treat the second file as this format.
#[arg(
long,
value_parser = crate::input_format::input_format_parser()
)]
input_format_b: Option<ForcedInput>,
/// Write JSON to standard output.
#[arg(long)]
json: bool,
#[command(flatten)]
report: OptionalFileDestination,
#[command(flatten)]
decode: DecodeArgs,
},
}
/// Restore `SIG_DFL` so a closed stdout pipe delivers SIGPIPE instead of a
/// `print!` panic (`failed printing to stdout: Broken pipe`).
#[cfg(unix)]
fn reset_sigpipe() {
const SIGPIPE: i32 = 13;
const SIG_DFL: usize = 0;
unsafe extern "C" {
fn signal(signum: i32, handler: usize) -> usize;
}
// SAFETY: one call on the main thread, before any I/O or spawned threads.
// POSIX `SIG_DFL` is a null handler; `signal` is in the C library already
// linked into a Unix Rust binary.
unsafe {
signal(SIGPIPE, SIG_DFL);
}
}
fn main() -> ExitCode {
#[cfg(unix)]
reset_sigpipe();
let command = Cli::parse().command;
let inputs = InputCatalog::with_builtins();
let result: Result<ExitCode, application::refusal::ApplicationError> = match command {
Command::Inspect(inspect::InspectArgs::Bytes(byte_command)) => {
inspect::run(byte_command).map_err(application::refusal::ApplicationError::from)
}
Command::Inspect(inspect::InspectArgs::Summary(args)) => commands::inspect(
&inputs,
args.file.path(),
args.input_format,
args.json,
args.report.0.as_ref(),
args.limits.limits(args.max_input_bytes),
)
.map(|()| ExitCode::SUCCESS),
Command::Dump {
file,
_reject_json: _,
destinations,
input_args,
decode,
} => commands::dump(
&inputs,
file.path(),
&match destinations.output.0 {
Some(file) => DestinationPolicy::File(file),
None => DestinationPolicy::Stdout {
allow_binary: false,
},
},
destinations.report.as_ref(),
input_args.input_format,
&decode,
)
.map(|()| ExitCode::SUCCESS),
Command::Query { view } => query::run(&view)
.map(|()| ExitCode::SUCCESS)
.map_err(application::refusal::ApplicationError::from),
Command::Check {
file,
json,
report,
input_args,
decode,
} => commands::check_cmd(
&inputs,
file.path(),
input_args.input_format,
&decode,
json,
report.0.as_ref(),
)
.map(|()| ExitCode::SUCCESS),
Command::Diff {
a,
b,
input_format_a,
input_format_b,
json,
report,
decode,
} => commands::diff(
&inputs,
commands::DiffInput {
path: &a,
forced: input_format_a,
},
commands::DiffInput {
path: &b,
forced: input_format_b,
},
&decode,
json,
report.0.as_ref(),
),
Command::Convert {
file,
_reject_json: _,
format,
destinations,
allow_errors,
allow_empty,
full_decode,
reject_lossy,
input_args,
decode,
} => {
let conversion_args = commands::ConversionArgs {
losses: reject_lossy.unwrap_or_default(),
allow_errors,
allow_empty,
full_decode,
destination: destinations.destination,
report: destinations.report,
forced_input: input_args.input_format,
};
commands::convert(
&inputs,
file.path(),
format.as_deref(),
&conversion_args,
&decode,
)
}
.map(|()| ExitCode::SUCCESS),
Command::Formats => print_formats(&inputs)
.map(|()| ExitCode::SUCCESS)
.map_err(application::refusal::ApplicationError::from),
Command::Dialects { format } => print_dialects(format.as_deref())
.map(|()| ExitCode::SUCCESS)
.map_err(anyhow::Error::new)
.map_err(application::refusal::ApplicationError::from),
};
result.unwrap_or_else(|err| {
eprintln!("error: {err:#}");
ExitCode::from(err.exit_code())
})
}