cadmpeg 0.6.5

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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
// SPDX-License-Identifier: Apache-2.0
//! Format-agnostic byte tools under `cadmpeg inspect`.
//!
//! These subcommands read a file as bytes. They know nothing about CAD formats,
//! so they work on a container, on an entry extracted from one, and on a probe
//! variant that no codec accepts yet. `cadmpeg inspect FILE` without a
//! subcommand still runs the codec-aware container summary.
//!
//! Every offset and length argument accepts hexadecimal with an `0x` prefix or
//! decimal, with `_` allowed between digits.

mod container;
mod diff;
mod hexdump;
mod layout;
mod numeric;
mod search;

use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::num::{NonZeroU64, NonZeroUsize};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use crate::application::artifact_store::OptionalFileDestination;
use anyhow::{anyhow, bail, Context, Result};
use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodeDepth, DecodePolicy};
use clap::{Args, Subcommand, ValueEnum};

use crate::LimitProfile;
use numeric::{parse_offset, Endian, ScalarType};

/// Default number of bytes a bare `inspect hex` prints.
const DEFAULT_HEX_LEN: u64 = 256;

/// A container summary or a byte tool with its own input arguments.
#[derive(Debug)]
pub(crate) enum InspectArgs {
    Summary(SummaryArgs),
    Bytes(ByteCommand),
}

/// Arguments for a codec-aware container summary.
#[derive(Debug, Args)]
#[command(mut_arg("output", |arg| arg.long("report").visible_alias("output").help("Write a JSON report to this file")))]
pub(crate) struct SummaryArgs {
    #[command(flatten)]
    pub(crate) file: FileArg,
    /// Write JSON to standard output.
    #[arg(long)]
    pub(crate) json: bool,
    #[command(flatten)]
    pub(crate) report: OptionalFileDestination,
    /// Resource-limit profile applied during inspection.
    #[arg(long, value_enum, default_value_t = LimitProfile::Desktop)]
    pub(crate) limits: LimitProfile,
    /// Override the profile's maximum number of physical input bytes.
    #[arg(long)]
    pub(crate) max_input_bytes: Option<u64>,
    /// Treat the input as this native format.
    #[arg(long, visible_alias = "from", value_parser = crate::input_format::native_input_parser())]
    pub(crate) input_format: Option<&'static cadmpeg_registry::NativeDescriptor>,
}

impl clap::Args for InspectArgs {
    fn augment_args(command: clap::Command) -> clap::Command {
        ByteCommand::augment_subcommands(SummaryArgs::augment_args(command))
    }

    fn augment_args_for_update(command: clap::Command) -> clap::Command {
        Self::augment_args(command)
    }
}

impl clap::FromArgMatches for InspectArgs {
    fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
        if matches.subcommand_name().is_some() {
            ByteCommand::from_arg_matches(matches).map(Self::Bytes)
        } else {
            SummaryArgs::from_arg_matches(matches).map(Self::Summary)
        }
    }

    fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
        *self = Self::from_arg_matches(matches)?;
        Ok(())
    }
}

/// Byte-level subcommands of `cadmpeg inspect`.
///
/// The tools run directly, as `cadmpeg inspect hex FILE`. The hidden `bytes`
/// group accepts the same tools one level deeper, as `cadmpeg inspect bytes hex
/// FILE`, so the guessed spelling reaches the tool and its `--help` instead of
/// a subcommand-conflict error.
#[derive(Debug, Subcommand)]
pub(crate) enum ByteCommand {
    /// One byte tool named directly under `inspect`.
    #[command(flatten)]
    Tool(ByteTool),
    /// The same byte tools under an explicit `bytes` group.
    #[command(hide = true)]
    Bytes {
        /// Byte tool to run.
        #[command(subcommand)]
        tool: ByteTool,
    },
}

/// One format-agnostic byte tool.
#[derive(Debug, Subcommand)]
pub(crate) enum ByteTool {
    /// Dump bytes as hex.
    ///
    /// Prints a hexadecimal dump with absolute offsets and an ASCII gutter.
    Hex(HexArgs),
    /// Read numbers at an offset.
    ///
    /// Reads fixed-width scalars at an offset, optionally striding a record array.
    Read(ReadArgs),
    /// Search for a byte pattern or string.
    Find(FindArgs),
    /// List printable strings.
    Strings(StringsArgs),
    /// Decode records from a layout spec.
    Struct(StructArgs),
    /// List container members (ZIP or CFB).
    Container(ContainerArgs),
    /// Write one ZIP entry or CFB stream.
    Extract(ExtractArgs),
    /// Compare two files as raw bytes.
    ///
    /// Compares byte n of one file with byte n of the other.
    /// `cadmpeg diff` compares decoded models.
    /// Exit status 1 means the files differ.
    Cmp(CmpArgs),
}

/// One resolved input file.
#[derive(Debug)]
pub(crate) struct FileArg {
    path: PathBuf,
}

impl FileArg {
    /// Returns the resolved input path.
    pub(crate) fn path(&self) -> &Path {
        &self.path
    }
}

impl clap::Args for FileArg {
    fn augment_args(command: clap::Command) -> clap::Command {
        let input = clap::Arg::new("input_flag")
            .long("input")
            .value_name("FILE")
            .help("Tolerated spelling of the positional file")
            .hide(true)
            .value_parser(clap::value_parser!(PathBuf));
        let input = input.conflicts_with("file");
        let value_name = if command.get_name() == "inspect" {
            "INPUT"
        } else {
            "FILE"
        };
        command
            .arg(
                clap::Arg::new("file")
                    .value_name(value_name)
                    .help("File to read")
                    .required_unless_present("input_flag")
                    .value_parser(clap::value_parser!(PathBuf)),
            )
            .arg(input)
    }

    fn augment_args_for_update(command: clap::Command) -> clap::Command {
        Self::augment_args(command)
    }
}

impl clap::FromArgMatches for FileArg {
    fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
        matches
            .get_one::<PathBuf>("file")
            .or_else(|| matches.get_one::<PathBuf>("input_flag"))
            .cloned()
            .map(|path| Self { path })
            .ok_or_else(|| {
                clap::Error::raw(
                    clap::error::ErrorKind::MissingRequiredArgument,
                    "file is required",
                )
            })
    }

    fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
        *self = Self::from_arg_matches(matches)?;
        Ok(())
    }
}

/// Arguments for `cadmpeg inspect hex`.
#[derive(Debug, Args)]
pub(crate) struct HexArgs {
    #[command(flatten)]
    file: FileArg,
    /// First byte to print.
    #[arg(long, alias = "start", default_value = "0", value_parser = parse_offset)]
    offset: u64,
    /// Number of bytes to print; the dump stops early at end of file.
    #[arg(long, visible_alias = "length", value_parser = parse_offset)]
    len: Option<u64>,
    /// Bytes per output line.
    #[arg(long, default_value = "16")]
    width: NonZeroUsize,
    #[command(flatten)]
    _reject_json: crate::reject_json::RejectJson,
}

fn parse_stride(text: &str) -> Result<NonZeroU64, String> {
    NonZeroU64::new(parse_offset(text)?).ok_or_else(|| "stride must be at least 1".to_owned())
}

// Zero parses to None (unlimited); clap detects Option syntactically, so do not inline this alias or remove parse_limit without changing argument admission.
type CountLimit = Option<NonZeroUsize>;

fn parse_limit(text: &str) -> Result<CountLimit, std::num::ParseIntError> {
    text.parse::<usize>().map(NonZeroUsize::new)
}

/// Arguments for `cadmpeg inspect read`.
#[derive(Debug, Args)]
pub(crate) struct ReadArgs {
    #[command(flatten)]
    file: FileArg,
    /// Scalar type to decode.
    #[arg(long = "type", value_parser = numeric::ScalarTypeParser)]
    ty: ScalarType,
    /// Offset of the first value.
    #[arg(long, alias = "start", default_value = "0", value_parser = parse_offset)]
    offset: u64,
    /// How many values to read.
    #[arg(short = 'n', long, default_value_t = 1)]
    count: u64,
    /// Byte step between consecutive values; defaults to the scalar width.
    #[arg(long, alias = "step", value_parser = parse_stride)]
    stride: Option<NonZeroU64>,
    /// Byte order for scalar reads.
    #[arg(long, value_enum, default_value_t = Endian::Le)]
    endian: Endian,
    #[command(flatten)]
    _reject_json: crate::reject_json::RejectJson,
}

/// Arguments for `cadmpeg inspect find`.
#[derive(Debug, Args)]
pub(crate) struct FindArgs {
    #[command(flatten)]
    input: FindInput,
    /// Pattern encoding.
    #[arg(long, value_enum)]
    encoding: FindEncoding,
    /// Stop after this many hits; 0 reports every hit.
    #[arg(long, default_value = "100", value_parser = parse_limit)]
    max: CountLimit,
    /// Bytes of context dumped before and after each hit; 0 prints none.
    #[arg(long, default_value = "0", value_parser = parse_offset)]
    context: u64,
    /// Print the hits as JSON instead of the table.
    #[arg(long, conflicts_with = "context")]
    json: bool,
}

/// A resolved search file and pattern.
#[derive(Debug)]
struct FindInput {
    file: PathBuf,
    needle: String,
}

impl clap::Args for FindInput {
    fn augment_args(command: clap::Command) -> clap::Command {
        command
            .arg(clap::Arg::new("search_operands")
                .value_name("FILE NEEDLE")
                .help("File and pattern, or just the pattern with --input; hex accepts ?? wildcards")
                .num_args(1..=2)
                .action(clap::ArgAction::Append)
                .required(true)
                .value_parser(clap::value_parser!(std::ffi::OsString)))
            .arg(clap::Arg::new("input_flag")
                .long("input")
                .value_name("FILE")
                .hide(true)
                .value_parser(clap::value_parser!(PathBuf)))
    }

    fn augment_args_for_update(command: clap::Command) -> clap::Command {
        Self::augment_args(command)
    }
}

impl clap::FromArgMatches for FindInput {
    fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
        let operands: Vec<_> = matches
            .get_many::<std::ffi::OsString>("search_operands")
            .into_iter()
            .flatten()
            .collect();
        let (file, needle) = match (
            matches.get_one::<PathBuf>("input_flag"),
            operands.as_slice(),
        ) {
            (None, [file, needle]) => (PathBuf::from(file), *needle),
            (Some(file), [needle]) => (file.clone(), *needle),
            (Some(_), [_, _, ..]) => {
                return Err(clap::Error::raw(
                    clap::error::ErrorKind::ArgumentConflict,
                    "--input cannot be used with a positional file",
                ));
            }
            (None, [_, _, _, ..]) => {
                return Err(clap::Error::raw(
                    clap::error::ErrorKind::TooManyValues,
                    "expected only FILE and NEEDLE",
                ));
            }
            _ => {
                return Err(clap::Error::raw(
                    clap::error::ErrorKind::MissingRequiredArgument,
                    "required arguments: FILE and NEEDLE",
                ));
            }
        };
        let needle = needle
            .to_str()
            .ok_or_else(|| {
                clap::Error::raw(
                    clap::error::ErrorKind::InvalidUtf8,
                    "NEEDLE must be valid UTF-8",
                )
            })?
            .to_owned();
        Ok(Self { file, needle })
    }

    fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
        *self = Self::from_arg_matches(matches)?;
        Ok(())
    }
}

/// Encoding of a search pattern.
#[derive(Debug, Clone, Copy, ValueEnum)]
enum FindEncoding {
    /// Hexadecimal bytes with optional `??` wildcards.
    Hex,
    /// ASCII text.
    Ascii,
    /// UTF-16LE text.
    Utf16le,
}

/// Arguments for `cadmpeg inspect strings`.
#[derive(Debug, Args)]
pub(crate) struct StringsArgs {
    #[command(flatten)]
    file: FileArg,
    /// Shortest run to report, in characters.
    #[arg(
        long,
        visible_alias = "min-len",
        alias = "min-length",
        default_value = "4"
    )]
    min: NonZeroUsize,
    /// Which encodings to scan for.
    #[arg(long, value_enum, default_value_t = search::StringScan::Ascii)]
    encoding: search::StringScan,
    #[command(flatten)]
    _reject_json: crate::reject_json::RejectJson,
}

/// Arguments for `cadmpeg inspect struct`.
#[derive(Debug, Args)]
pub(crate) struct StructArgs {
    #[command(flatten)]
    file: FileArg,
    /// Record layout, for example `u32le:count,pad4,f64le:x,f64le:y`.
    #[arg(long)]
    layout: String,
    /// Offset of the first record.
    #[arg(long, alias = "start", default_value = "0", value_parser = parse_offset)]
    offset: u64,
    /// How many consecutive records to decode.
    #[arg(short = 'n', long, default_value_t = 1)]
    count: u64,
    #[command(flatten)]
    _reject_json: crate::reject_json::RejectJson,
}

/// Arguments for `cadmpeg inspect container`.
#[derive(Debug, Args)]
pub(crate) struct ContainerArgs {
    #[command(flatten)]
    file: FileArg,
    /// Print the entries as JSON instead of the table.
    #[arg(long)]
    json: bool,
    /// Resource-limit profile applied while reading the central directory.
    #[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>,
}

/// Arguments for `cadmpeg inspect extract`.
#[derive(Debug, Args)]
pub(crate) struct ExtractArgs {
    /// ZIP or CFB file to read.
    file: PathBuf,
    /// Exact entry or stream path (quotes removed).
    member: String,
    /// Extracted-byte destination.
    #[command(flatten)]
    output: ExtractDestination,
    /// Resource-limit profile applied while reading the archive.
    #[arg(long, value_enum, default_value_t = LimitProfile::Desktop)]
    limits: LimitProfile,
    #[command(flatten)]
    _reject_json: crate::reject_json::RejectJson,
}

/// Extracted-byte destination and its file overwrite policy.
#[derive(Debug, Clone, PartialEq, Eq)]
enum ExtractDestination {
    /// Write bytes to standard output.
    Stdout,
    /// Write bytes with the file overwrite policy.
    File(crate::application::artifact_store::FileDestination),
}

impl clap::Args for ExtractDestination {
    fn augment_args(command: clap::Command) -> clap::Command {
        OptionalFileDestination::augment_args(command).mut_arg("output", |arg| {
            arg.help("Output file; omit it or pass - for standard output")
        })
    }

    fn augment_args_for_update(command: clap::Command) -> clap::Command {
        Self::augment_args(command)
    }
}

impl clap::FromArgMatches for ExtractDestination {
    fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
        Ok(
            match OptionalFileDestination::from_arg_matches(matches)?.0 {
                Some(file) if file.path != Path::new("-") => Self::File(file),
                Some(_) | None => Self::Stdout,
            },
        )
    }

    fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
        *self = Self::from_arg_matches(matches)?;
        Ok(())
    }
}

/// Arguments for `cadmpeg inspect cmp`.
#[derive(Debug, Args)]
pub(crate) struct CmpArgs {
    /// First file.
    a: PathBuf,
    /// Second file.
    b: PathBuf,
    /// Merge two differing spans separated by this many equal bytes or fewer.
    #[arg(long, default_value_t = 8)]
    gap: u64,
    /// Stop listing after this many runs; 0 lists every run.
    #[arg(long, default_value = "32", value_parser = parse_limit)]
    max_runs: CountLimit,
    /// Bytes of context dumped on each side of the first difference.
    #[arg(long, default_value = "32", value_parser = parse_offset)]
    context: u64,
    #[command(flatten)]
    _reject_json: crate::reject_json::RejectJson,
}

/// Runs one byte subcommand.
///
/// # Errors
///
/// Returns an operational error when a file cannot be read, an argument does
/// not parse, or a requested offset lies past end of file.
pub(crate) fn run(command: ByteCommand) -> Result<ExitCode> {
    let tool = match command {
        ByteCommand::Tool(tool) | ByteCommand::Bytes { tool } => tool,
    };
    let json_subcommand = match &tool {
        ByteTool::Find(args) if args.json => Some("find"),
        ByteTool::Container(args) if args.json => Some("container"),
        _ => None,
    };
    let result = match &tool {
        ByteTool::Hex(args) => hex(args).map(|()| ExitCode::SUCCESS),
        ByteTool::Read(args) => read(args).map(|()| ExitCode::SUCCESS),
        ByteTool::Find(args) => find(args).map(|()| ExitCode::SUCCESS),
        ByteTool::Strings(args) => strings(args).map(|()| ExitCode::SUCCESS),
        ByteTool::Struct(args) => structure(args).map(|()| ExitCode::SUCCESS),
        ByteTool::Container(args) => container_list(args).map(|()| ExitCode::SUCCESS),
        ByteTool::Extract(args) => extract_entry(args).map(|()| ExitCode::SUCCESS),
        ByteTool::Cmp(args) => cmp_files(args),
    };
    result.inspect_err(|error| {
        let Some(subcommand) = json_subcommand else {
            return;
        };
        let Some(cadmpeg_core::CodecError::ResourceLimit(limit)) =
            error.downcast_ref::<cadmpeg_core::CodecError>()
        else {
            return;
        };
        let refusal = crate::application::refusal::ConversionRefusal::ResourceLimit {
            limit: *limit,
            stage: crate::application::refusal::RefusalStage::Decode,
        };
        let payload = crate::commands::reporting::Payload::Refused(
            serde_json::json!({ "subcommand": subcommand }), &refusal,
        );
        match crate::commands::reporting::payload_report_json("inspect", payload) {
            Ok(report) => println!("{report}"),
            Err(error) => eprintln!("warning: could not serialize inspect refusal report: {error:#}; preserving the original refusal"),
        }
    })
}

/// Returns the file length in bytes.
fn file_len(path: &Path) -> Result<u64> {
    let metadata = std::fs::metadata(path)
        .with_context(|| format!("reading metadata for {}", path.display()))?;
    Ok(metadata.len())
}

/// Reads up to `len` bytes starting at `offset`, returning fewer at end of file.
///
/// Seeking past end of file is an error rather than an empty result, because an
/// offset outside the file is always a mistake worth reporting.
fn read_window(path: &Path, offset: u64, len: u64) -> Result<Vec<u8>> {
    let arena = DecodeArena::new();
    let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &DecodePolicy::default())?;
    let size = file_len(path)?;
    if offset > size {
        bail!(
            "offset 0x{offset:x} ({offset}) is past the end of {}, which is 0x{size:x} ({size}) bytes",
            path.display()
        );
    }
    let available = size - offset;
    let want = usize::try_from(len.min(available))
        .context("the requested length does not fit in memory on this target")?;
    let mut file = File::open(path).with_context(|| format!("opening {}", path.display()))?;
    file.seek(SeekFrom::Start(offset))
        .with_context(|| format!("seeking to 0x{offset:x} in {}", path.display()))?;
    let mut buffer = ctx.alloc_filled(want, 0_u8, "cli inspect read window")?;
    file.read_exact(&mut buffer).with_context(|| {
        format!(
            "reading {want} bytes at 0x{offset:x} from {}",
            path.display()
        )
    })?;
    Ok(buffer)
}

/// Reads a whole file.
fn read_whole(path: &Path) -> Result<Vec<u8>> {
    std::fs::read(path).with_context(|| format!("reading {}", path.display()))
}

fn hex(args: &HexArgs) -> Result<()> {
    let len = args.len.unwrap_or(DEFAULT_HEX_LEN);
    let bytes = read_window(args.file.path(), args.offset, len)?;
    if bytes.is_empty() {
        println!("(no bytes at 0x{:x})", args.offset);
        return Ok(());
    }
    print!("{}", hexdump::render(args.offset, &bytes, args.width)?);
    Ok(())
}

fn read(args: &ReadArgs) -> Result<()> {
    let endian = args.endian;
    let width_usize = args.ty.width();
    let width = cadmpeg_core::decode::u64_from_index(width_usize);
    let stride = args.stride.map_or(width, NonZeroU64::get);
    if args.count == 0 {
        return Ok(());
    }
    let file_path = args.file.path();
    let size = file_len(file_path)?;
    let name = args.ty.display_name(endian);
    let mut file =
        File::open(file_path).with_context(|| format!("opening {}", file_path.display()))?;
    for index in 0..args.count {
        let offset = index
            .checked_mul(stride)
            .and_then(|step| args.offset.checked_add(step))
            .context("the strided offset overflows 64 bits")?;
        let end = offset
            .checked_add(width)
            .context("the read overflows 64 bits")?;
        if end > size {
            bail!(
                "value {index} needs bytes 0x{offset:x}..0x{end:x}, past the end of {} at 0x{size:x}",
                file_path.display()
            );
        }
        file.seek(SeekFrom::Start(offset))?;
        let mut buffer = [0u8; ScalarType::MAX_WIDTH];
        file.read_exact(&mut buffer[..width_usize])?;
        let value = args.ty.window_of(&buffer).read(endian);
        println!(
            "0x{offset:08x}  {name:<6}  {:<24}  {}",
            value.decimal(),
            value.hex()
        );
    }
    Ok(())
}

fn find(args: &FindArgs) -> Result<()> {
    let file = &args.input.file;
    let text = &args.input.needle;
    let (pattern, described) = match args.encoding {
        FindEncoding::Hex => (search::parse_pattern(text), format!("hex {text}")),
        FindEncoding::Ascii => (search::ascii_pattern(text), format!("ascii {text:?}")),
        FindEncoding::Utf16le => (search::utf16le_pattern(text), format!("utf16le {text:?}")),
    };
    let pattern = pattern.map_err(|message| anyhow::anyhow!(message))?;
    let bytes = read_whole(file)?;
    let limit = args.max;
    let hits = search::find_all(&bytes, &pattern, limit);
    let truncated = limit.is_some_and(|max| hits.len() >= max.get());
    if args.json {
        let payload = serde_json::json!({
            "subcommand": "find",
            "pattern": described,
            "pattern_bytes": pattern.len(),
            "truncated": truncated,
            "hits": hits,
        });
        println!(
            "{}",
            crate::commands::reporting::command_report_json("inspect", &payload)?
        );
        return Ok(());
    }
    println!(
        "pattern: {described} ({} bytes)  hits: {}{}",
        pattern.len(),
        hits.len(),
        if truncated {
            " (truncated by --max)"
        } else {
            ""
        }
    );
    for offset in &hits {
        println!("0x{offset:08x}  {offset}");
        if args.context > 0 {
            let len = args
                .context
                .checked_mul(2)
                .and_then(|len| {
                    len.checked_add(cadmpeg_core::decode::u64_from_index(pattern.len()))
                })
                .ok_or_else(|| anyhow!("inspection context length exceeds u64"))?;
            if let Some(start) = offset.checked_sub(args.context) {
                print!("{}", window(&bytes, start, len)?);
            } else {
                print!("{}", window(&bytes, 0, len)?);
            }
        }
    }
    if truncated {
        println!(
            "note: output truncated at {} matches; pass --max 0 for all",
            hits.len()
        );
    }
    Ok(())
}

fn strings(args: &StringsArgs) -> Result<()> {
    let bytes = read_whole(args.file.path())?;
    for found in search::extract_strings(&bytes, args.min, args.encoding) {
        println!(
            "0x{:08x}  {:<8}  \"{}\"",
            found.offset,
            found.encoding.label(),
            search::escape(&found.text)
        );
    }
    Ok(())
}

fn structure(args: &StructArgs) -> Result<()> {
    let layout = layout::Layout::parse(&args.layout)?;
    if args.count == 0 {
        return Ok(());
    }
    let file_path = args.file.path();
    let size = file_len(file_path)?;
    let record_size = cadmpeg_core::decode::u64_from_index(layout.size().get());
    let span = record_size
        .checked_mul(args.count)
        .and_then(|total| args.offset.checked_add(total))
        .context("the requested records overflow a 64-bit offset")?;
    if span > size {
        bail!(
            "{} records of {record_size} bytes at 0x{:x} need 0x{span:x} bytes, \
             but {} is 0x{size:x} bytes",
            args.count,
            args.offset,
            file_path.display()
        );
    }
    let bytes = read_window(file_path, args.offset, span - args.offset)?;
    // `fields()` yields exactly the named fields, so a layout that names none
    // prints no field line. Zero is the identity of a maximum over lengths.
    let name_width = layout.names().map(str::len).fold(0, usize::max);
    for (index, record) in layout.split(&bytes).enumerate() {
        let base = args.offset + cadmpeg_core::decode::u64_from_index(index) * record_size;
        println!("record {index} @ 0x{base:08x} ({record_size} bytes)");
        for field in record.fields() {
            let at = base + cadmpeg_core::decode::u64_from_index(field.offset());
            let decimal = match field.value() {
                layout::DecodedValue::Scalar { value, .. } => value.decimal(),
                layout::DecodedValue::Bytes(_) => String::new(),
            };
            println!(
                "  0x{at:08x}  {:<name_width$}  {:<8}  {:<24}  {}",
                field.name(),
                field.type_name(),
                decimal,
                field.hex()
            );
        }
    }
    Ok(())
}

fn container_list(args: &ContainerArgs) -> Result<()> {
    let file_path = args.file.path();
    let limits = args.limits.limits(args.max_input_bytes);
    let arena = DecodeArena::new();
    let policy = DecodePolicy {
        limits,
        ..DecodePolicy::default()
    };
    let ctx = DecodeContext::new(&arena, &policy, DecodeDepth::Full);
    let mut file =
        File::open(file_path).with_context(|| format!("reading {}", file_path.display()))?;
    let mut bytes = Vec::new();
    ctx.complete_input(&mut file, &mut bytes)?;
    ctx.finish_session()?;
    let listing = container::list(&bytes, limits).with_context(|| {
        format!(
            "cannot list {} as a ZIP or CFB container; `cadmpeg inspect {}` reads \
             the other container families through their codec",
            file_path.display(),
            file_path.display()
        )
    })?;
    if args.json {
        print!("{}", container::render_json(&listing)?);
    } else {
        print!("{}", container::render(&listing));
    }
    Ok(())
}

fn extract_entry(args: &ExtractArgs) -> Result<()> {
    let bytes = read_whole(&args.file)?;
    let payload = container::extract(&bytes, args.limits.limits(None), &args.member)
        .with_context(|| format!("extracting from {}", args.file.display()))?;
    match &args.output {
        ExtractDestination::Stdout => write_payload_to_stdout(&payload),
        ExtractDestination::File(destination) => destination.write(&args.file, &payload),
    }
}

/// Writes extracted bytes to standard output without any rendering.
fn write_payload_to_stdout(payload: &[u8]) -> Result<()> {
    use std::io::Write as _;
    std::io::stdout()
        .lock()
        .write_all(payload)
        .context("writing the entry to standard output")
}

fn cmp_files(args: &CmpArgs) -> Result<ExitCode> {
    let a = read_whole(&args.a)?;
    let b = read_whole(&args.b)?;
    let summary = diff::compare(&a, &b, args.gap);
    println!(
        "a: {} ({} bytes)\nb: {} ({} bytes)",
        args.a.display(),
        summary.len_a(),
        args.b.display(),
        summary.len_b()
    );
    if summary.identical() {
        println!("identical");
        return Ok(ExitCode::SUCCESS);
    }
    if summary.len_a() != summary.len_b() {
        println!(
            "length differs by {} bytes; only the first {} bytes are compared",
            summary.len_a().abs_diff(summary.len_b()),
            summary.compared()
        );
    }
    let Some(first) = summary.first() else {
        println!("the common prefix is identical");
        return Ok(ExitCode::from(1));
    };
    println!(
        "first difference: 0x{first:08x} ({first})\ndiffering bytes: {} of {}\nruns (gap {}): {}",
        summary.differing(),
        summary.compared(),
        args.gap,
        summary.runs().len()
    );
    let shown = args.max_runs.map_or(summary.runs().len(), |max| {
        max.get().min(summary.runs().len())
    });
    for run in &summary.runs()[..shown] {
        println!(
            "  0x{:08x}..0x{:08x}  {} bytes",
            run.start(),
            run.end(),
            run.len()
        );
    }
    if shown < summary.runs().len() {
        println!(
            "  … {} more runs (raise --max-runs)",
            summary.runs().len() - shown
        );
    }
    if args.context > 0 {
        if let Some(window_start) = first.checked_sub(args.context / 2) {
            println!("\na @ 0x{window_start:x}:");
            print!("{}", window(&a, window_start, args.context)?);
            println!("b @ 0x{window_start:x}:");
            print!("{}", window(&b, window_start, args.context)?);
        } else {
            println!("\na @ 0x0:");
            print!("{}", window(&a, 0, args.context)?);
            println!("b @ 0x0:");
            print!("{}", window(&b, 0, args.context)?);
        }
    }
    Ok(ExitCode::from(1))
}

/// Renders a bounded hexadecimal window of an in-memory buffer.
///
/// The window is the intersection of `start..start + len` with the buffer: a
/// bound the buffer does not hold, including one the address space cannot
/// name, selects the end of the buffer.
fn window(bytes: &[u8], start: u64, len: u64) -> Result<String> {
    let begin = match usize::try_from(start) {
        Ok(begin) if begin < bytes.len() => begin,
        _ => bytes.len(),
    };
    let end = match start.checked_add(len).map(usize::try_from) {
        Some(Ok(end)) if end < bytes.len() => end,
        _ => bytes.len(),
    };
    hexdump::render_default_width(
        cadmpeg_core::decode::u64_from_index(begin),
        &bytes[begin..end],
    )
}

#[cfg(test)]
mod tests {
    use super::{find, ExtractArgs, FindArgs, FindEncoding, FindInput};
    use clap::{Args, FromArgMatches};

    #[test]
    fn inspect_rejects_cadir_at_argument_admission() {
        use clap::Parser;
        let error =
            crate::Cli::try_parse_from(["cadmpeg", "inspect", "missing", "--from", "cadir"])
                .unwrap_err();
        assert_eq!(error.kind(), clap::error::ErrorKind::InvalidValue);
    }

    #[test]
    fn extract_stdout_spellings_have_one_destination() {
        let parse = |args: Vec<&str>| {
            let matches = ExtractArgs::augment_args(clap::Command::new("extract"))
                .try_get_matches_from(args)
                .unwrap();
            ExtractArgs::from_arg_matches(&matches).unwrap()
        };
        let omitted = parse(vec!["extract", "input.zip", "entry"]);
        let explicit = parse(vec!["extract", "input.zip", "entry", "-o", "-", "--force"]);
        assert_eq!(omitted.output, explicit.output);
    }

    #[test]
    fn find_refuses_an_unrepresentable_context_length() {
        let file = tempfile::NamedTempFile::new().expect("create test input");
        std::fs::write(file.path(), b"a").expect("write test input");
        let args = FindArgs {
            input: FindInput {
                file: file.path().to_path_buf(),
                needle: "a".into(),
            },
            encoding: FindEncoding::Ascii,
            max: None,
            context: u64::MAX,
            json: false,
        };
        assert!(find(&args).is_err());
    }
}