nord-cli 0.1.0

Command-line tool for inspecting Clavia / Nord keyboard files (dogfoods nord-format)
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
//! `nord` — a thin CLI over [`nord_format`] and `nord_usb` to interact with
//! your Clavia / Nord projects and files.
//!
//! > This is an unofficial, community project: **not affiliated with, endorsed
//! > by, or supported by Clavia DMI AB**. "Nord" and the instrument names are
//! > Clavia's trademarks, used here only to identify which files this crate
//! > reads.
//!
//! The nouns are the protocol's object classes: `nord program`, `nord sample`,
//! `nord setlist` and `nord live` are [`slot_action`] with the class fixed, `nord
//! settings` carries the one verb its singleton needs (`edit`), and the hidden
//! `nord raw --class N` is [`slot_action`] with the class given as a number.
//! `inspect`/`verify` dispatch on the CBIN format tag rather than on a class, so they sit
//! at the top level.
//!
//! ⚠️ `raw` is hidden but supported: it is the only way to reach a class with no noun of
//! its own, which today is pianos (1).

mod device;
mod edit;
mod file;
mod note;
mod sample;
mod slot;
mod summary;
mod ui;

use clap::{Args, Parser, Subcommand};
use nord_usb::ObjectClass;
use std::path::PathBuf;
use std::process::ExitCode;

use ui::{ColorChoice, Ui};

#[derive(Parser)]
#[command(name = "nord", about = "Inspect Clavia / Nord keyboard files", version)]
struct Cli {
    /// When to color output. `auto` means "stdout is a terminal"; `NO_COLOR` in the
    /// environment forces it off.
    #[arg(long, global = true, value_name = "WHEN", value_enum, default_value_t)]
    color: ColorChoice,

    /// Mirror every frame exchanged with the instrument into a replay script at PATH.
    ///
    /// The script is what `--replay` and the golden tests read back. An operation that
    /// transfers a body writes that body into it in full.
    ///
    /// Bulk traffic only: `device info` reads endpoint 0, which never reaches the script.
    #[arg(long, global = true, value_name = "PATH")]
    record: Option<PathBuf>,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Parse Nord file(s) and print a summary of the decoded contents.
    Inspect {
        /// Files to read (.ne5p program, .ne5l live slot, .ne5t song, .ne5s
        /// settings, .npno piano, .nsmp sample, or a ZIP backup bundle).
        #[arg(required = true)]
        files: Vec<PathBuf>,

        /// Dump the full `Debug` representation instead of the summary.
        #[arg(long)]
        raw: bool,
    },

    /// Re-encode file(s) and check the result is byte-identical to the input.
    ///
    /// Checks `nord-format`'s central invariant: decoded values are read-only views over
    /// a verbatim body, so a parse followed by a re-emit cannot drift.
    Verify {
        /// Files to round-trip. Bundles are archives, not re-emittable entities.
        #[arg(required = true)]
        files: Vec<PathBuf>,
    },

    /// The attached instrument itself: what is on the bus, and what it holds.
    Device {
        #[command(subcommand)]
        action: DeviceAction,
    },

    /// Programs on the instrument (object class 4). Slots are `BANK:SLOT`, as the
    /// instrument displays them; the read-only verbs and `edit` take a file instead.
    Program {
        #[command(subcommand)]
        action: ProgramAction,
    },

    /// Set lists on the instrument (object class 5). Same verbs as `nord program`.
    Setlist {
        #[command(subcommand)]
        action: SlotAction,
    },

    /// The live buffer — the panel as it stands (object class 6), in slots 1:1 to 1:3.
    Live {
        #[command(subcommand)]
        action: LiveAction,
    },

    /// The global settings singleton (object class 7): the System, MIDI and Sound
    /// menus, plus the panel state the instrument restores at power-up.
    Settings {
        #[command(subcommand)]
        action: SettingsAction,
    },

    /// Sample instruments — the library on the instrument (object class 3), or
    /// `.nsmp` files.
    Sample {
        #[command(subcommand)]
        action: SampleAction,
    },

    /// The class-generic primitives, addressed by object-class number.
    ///
    /// Every typed noun above is this with the class fixed. Use it for a class with no
    /// noun — pianos are `--class 1`.
    #[command(hide = true)]
    Raw {
        /// Object class: 1 pianos, 3 samples, 4 programs, 5 set lists, 6 live.
        #[arg(long, global = true, value_name = "N", default_value_t = 4)]
        class: u32,

        #[command(subcommand)]
        action: SlotAction,
    },
}

#[derive(Subcommand)]
enum DeviceAction {
    /// Sweep the vendor control requests on endpoint 0 and print what answers. For RE.
    ///
    /// Endpoint 0 is outside the bulk protocol: these are reads that cannot open,
    /// desync, or wedge a session, and an unrecognised request stalls the endpoint
    /// rather than doing anything. Reported externally to carry the model, firmware
    /// version, build and maximum transfer size.
    Controls {
        /// Lowest bRequest to try.
        #[arg(long, default_value_t = 0)]
        from: u8,

        /// Highest bRequest to try, inclusive.
        #[arg(long, default_value_t = 15)]
        to: u8,

        /// Bytes to ask each request for.
        #[arg(long, default_value_t = 64)]
        len: usize,

        /// Address the interface rather than the device.
        #[arg(long)]
        interface: bool,

        /// wValue sent with each request.
        #[arg(long, default_value_t = 0)]
        value: u16,

        /// wIndex sent with each request. For --interface this is the interface number.
        #[arg(long, default_value_t = 0)]
        index: u16,
    },

    /// Report what is stored on the instrument, per object class.
    ///
    /// Read-only: this sends one query per class and reads counters back. Nothing
    /// on the instrument is modified.
    Status {
        /// Replay a recorded exchange instead of opening a device. Useful for
        /// demos and for exercising the whole path without hardware.
        #[arg(long, value_name = "SCRIPT")]
        replay: Option<PathBuf>,

        /// Emit JSON instead of a table.
        #[arg(long)]
        json: bool,
    },

    /// Identify the attached instrument, from its USB descriptors. Read-only, and opens
    /// no transaction — the first thing to run when nothing else answers.
    Info,

    /// Clear a session an interrupted run left open on the instrument.
    ///
    /// Two faults look like a broken instrument and each is one frame to cure: an
    /// abandoned UI session makes every slot read as empty — a wrong answer that looks
    /// right — and an abandoned class session makes operations fail with status 0x12.
    /// Safe to run on a healthy instrument.
    Recover,

    /// Report the instrument's storage layout: partitions, banks and slot capacity.
    ///
    /// Read from the device rather than assumed, so it is correct for models this tool
    /// has never seen. Partition indices are the object class numbers.
    Geometry,

    /// Deliberately wedge the instrument by abandoning a session. Test tool.
    ///
    /// Reproduces the abandoned session on purpose, so recovery can be tested against a
    /// known wedge. Nothing stored is harmed, but every slot then reads as empty —
    /// successfully, which is worse than an error — until `nord device recover` clears it.
    #[cfg(feature = "wedge")]
    #[command(hide = true)]
    Wedge {
        /// Object class to open the doomed session on.
        #[arg(long, value_name = "N", default_value_t = 4)]
        class: u32,

        /// Confirm. Without this nothing is sent.
        #[arg(long)]
        yes: bool,
    },
}

/// `nord program`: every class-generic verb, plus the one that only programs have.
#[derive(Subcommand)]
enum ProgramAction {
    #[command(flatten)]
    Slot(SlotAction),

    /// Change fields inside a program, in a file or in a slot.
    ///
    /// Field paths are `nord-format`'s own — `center_panel.transpose`,
    /// `effects_panel.fx1_rate`. `--fields` lists them.
    ///
    /// With no target the program is a fresh default one, so `--fields` needs nothing to
    /// read and `-o` writes a blank `.ne5p` to start from.
    Edit(EditArgs),
}

/// `nord sample`: every class-generic verb, plus the one that edits files.
#[derive(Subcommand)]
enum SampleAction {
    #[command(flatten)]
    Slot(SlotAction),

    /// Change fields inside a sample instrument, in a file or in a slot.
    ///
    /// A sample is mostly encoded audio; what is settable is what the format can
    /// patch in place — the name, and each zone's root key and top note. `--fields`
    /// lists them.
    Edit(sample::EditArgs),
}

/// `nord live`: the verbs that mean anything for the live buffer.
///
/// The live buffer is the panel as it stands, not a library — there is nothing to name,
/// nothing to delete, and `select` is what the *other* classes do to it. What is left is
/// the read-only subset, spelled exactly as [`SlotAction`] spells it, plus `edit`,
/// whose output stops at a file.
#[derive(Subcommand)]
enum LiveAction {
    #[command(flatten)]
    Slot(LiveSlotAction),

    /// Change fields inside a live slot, in a `.ne5l` file.
    ///
    /// The live buffer is the program body under another tag, so the fields are exactly
    /// `nord program edit`'s. A slot target is read off the instrument but never
    /// written back — the edit needs `-o`.
    Edit(EditArgs),
}

/// `nord settings`: the instrument holds exactly one of these, so there is nothing to
/// move, copy, name or delete, and `edit` is the whole verb set. The class-generic
/// verbs remain reachable as `raw --class 7`.
#[derive(Subcommand)]
enum SettingsAction {
    /// Change fields inside the global settings, in a `.ne5s` file.
    ///
    /// Fields are the menu settings plus the `startup_*` state the instrument restores
    /// at power-up; `--fields` lists them. A slot target is read off the instrument but
    /// never written back — the edit needs `-o`.
    Edit(EditArgs),
}

/// The [`SlotAction`] verbs the live buffer keeps, spelled identically.
#[derive(Subcommand)]
enum LiveSlotAction {
    /// Read a live slot off the instrument, or a `.ne5l` file. Read-only.
    ///
    /// Prints a summary by default; with `--out` writes the file instead.
    Get {
        /// Slot to read: 1:1, 1:2 or 1:3 — or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,

        /// Write the object to this file instead of printing a summary. With `--sweep`,
        /// the directory every capture lands in.
        #[arg(short, long, value_name = "FILE|DIR")]
        out: Option<PathBuf>,

        /// Save the wire body verbatim instead of wrapping it in a CBIN header.
        /// Needs `--out`.
        #[arg(long)]
        body: bool,

        /// Read the slot over and over, once per prompt, into the `--out` directory.
        ///
        /// The live slot is the panel itself, so this captures a change-one-knob corpus
        /// without saving a program between steps.
        #[arg(long, requires = "out")]
        sweep: bool,
    },

    /// Report everything the instrument knows about a live slot, or a `.ne5l` file's
    /// header. Read-only.
    Info {
        /// Slot to describe: 1:1, 1:2 or 1:3 — or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,
    },

    /// List the piano/sample library objects the live panel depends on. Read-only.
    Deps {
        /// Slot to inspect: 1:1, 1:2 or 1:3 — or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,
    },
}

/// The verb vocabulary, identical for every object class.
#[derive(Subcommand)]
enum SlotAction {
    /// Read an object off the instrument, or from a file. Read-only.
    ///
    /// Prints a summary by default; with `--out` writes the file instead.
    Get {
        /// Slot to read, e.g. 7:4, or a file to read with no instrument attached.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,

        /// Write the object to this file instead of printing a summary. With `--sweep`,
        /// the directory every capture lands in.
        #[arg(short, long, value_name = "FILE|DIR")]
        out: Option<PathBuf>,

        /// Save the wire body verbatim instead of wrapping it in a CBIN header. For
        /// classes whose header layout is not yet known, where wrapping it would
        /// fabricate a wrong file. On a file, strips the header instead. Needs `--out`.
        #[arg(long)]
        body: bool,

        /// Read the slot over and over, once per prompt, into the `--out` directory.
        ///
        /// Change one thing on the instrument, say what you changed, and that capture is
        /// filed under your answer; repeat until a blank line. For building the
        /// one-field-at-a-time corpus that pins down where a field lives.
        #[arg(long, requires = "out")]
        sweep: bool,
    },

    /// Write a file into a slot, OVERWRITING it. Requires --yes.
    Put {
        /// The file to send.
        file: PathBuf,

        /// Destination slot, e.g. 7:4.
        #[arg(value_name = "BANK:SLOT")]
        at: String,

        /// Confirm the overwrite. Without this the command stops after reporting what
        /// currently occupies the slot.
        #[arg(long)]
        yes: bool,
    },

    /// Move an object between slots, SWAPPING with any occupant. Requires --yes.
    Move {
        /// Source slot, e.g. 8:13.
        #[arg(value_name = "FROM")]
        from: String,

        /// Destination slot, e.g. 7:16.
        #[arg(value_name = "TO")]
        to: String,

        #[arg(long)]
        yes: bool,
    },

    /// Rename the object in a slot. Requires --yes.
    Rename {
        /// Slot to rename, e.g. 6:13.
        #[arg(value_name = "BANK:SLOT")]
        at: String,

        /// The new name.
        name: String,

        #[arg(long)]
        yes: bool,
    },

    /// Duplicate an object into another slot (device-internal deep copy). Requires --yes.
    Duplicate {
        /// Source slot, e.g. 7:2.
        #[arg(value_name = "FROM")]
        from: String,

        /// Destination slot, e.g. 7:3.
        #[arg(value_name = "TO")]
        to: String,

        #[arg(long)]
        yes: bool,
    },

    /// Delete one or more slots. Requires --yes.
    Delete {
        /// Slots to delete, e.g. 7:50 (repeatable).
        #[arg(value_name = "BANK:SLOT", required = true)]
        slots: Vec<String>,

        #[arg(long)]
        yes: bool,
    },

    /// Load an object live on the instrument (double-click in NSM). Non-destructive.
    Select {
        /// Slot to load, e.g. 2:12.
        #[arg(value_name = "BANK:SLOT")]
        at: String,
    },

    /// Report everything the instrument knows about one slot, or a file's header.
    /// Read-only.
    ///
    /// Shows the fields the CBIN header carries but the wire never transmits — format
    /// tag, version, CRC-32 — plus the slot name, which no file stores at all.
    Info {
        /// Slot to describe, e.g. 7:4, or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,
    },

    /// List the piano/sample library objects an entity depends on. Read-only.
    ///
    /// A file yields the stored ids alone; the slot form asks the instrument, which
    /// attaches the names.
    Deps {
        /// Slot to inspect, e.g. 7:3, or a file.
        #[arg(value_name = "FILE|BANK:SLOT")]
        at: String,
    },

    /// Report which object the panel currently has loaded in this class. Read-only.
    ///
    /// The read half of `select`: it answers what the player is looking at, rather than
    /// telling the instrument what to load.
    Focus,

    /// List everything the instrument holds in this class. Read-only.
    ///
    /// Walks the device's own slot cursor, so it reports what is actually stored rather
    /// than probing every address: occupied slots are sparse, and their indices run past
    /// the class's item count.
    List {
        /// Stop after this many slots. A guard against a walk that fails to advance.
        #[arg(long, default_value_t = 1024)]
        cap: usize,
    },

    /// Send a raw command code and print whatever the device answers. For RE only.
    ///
    /// Nothing about the reply is interpreted: the status word and payload are printed
    /// as-is, because on an unknown command an error status is the finding. A command
    /// the device ignores is reported as a timeout rather than hanging.
    ///
    /// DANGER: these are bytes no capture has shown the device being sent. Unknown
    /// commands can leave the instrument needing a power cycle, and anything
    /// write-shaped will destroy whatever object it reaches. Read-shaped codes only,
    /// and back up first.
    Probe {
        /// Command code, decimal or 0x-prefixed, e.g. 0x20.
        #[arg(value_name = "OP", value_parser = parse_u32)]
        op: u32,

        /// Argument words, appended in order as big-endian u32s: --arg 1 --arg 0.
        #[arg(long = "arg", value_name = "N", value_parser = parse_u32)]
        args: Vec<u32>,

        /// Seconds to wait for a reply before giving up.
        #[arg(long, default_value_t = 5)]
        wait: u64,

        /// Required. Probing is not a read-only operation in the sense the other
        /// read verbs are — the device's response to an unknown code is unknown.
        #[arg(long)]
        yes: bool,

        /// Send with no session around it: no HELLO, no session open, no close.
        ///
        /// The only way to reach a command when the session machinery itself is what
        /// is broken — a wedged instrument refuses to open one, so every ordinary
        /// probe fails before its command is sent.
        #[arg(long)]
        bare: bool,

        /// Service number. 12 is the object/file service, 6 the UI session.
        #[arg(long, default_value_t = 12)]
        service: u32,

        /// Subsystem number. 10 for service 12, 1 for service 6.
        #[arg(long, default_value_t = 10)]
        subsystem: u32,
    },
}

/// Accept `0x2a` as readily as `42`: command codes are quoted in hex everywhere in the
/// protocol notes, and retyping them in decimal invites transcription errors.
fn parse_u32(s: &str) -> Result<u32, String> {
    let s = s.trim();
    match s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
        Some(hex) => u32::from_str_radix(hex, 16),
        None => s.parse(),
    }
    .map_err(|e| format!("{s}: {e}"))
}

#[derive(Args)]
pub struct EditArgs {
    /// A file (`.ne5p` under `nord program`, `.ne5l` under `nord live`, `.ne5s` under
    /// `nord settings`), or a slot on the instrument (`7:4`). A slot makes this a
    /// read-modify-write over USB, so it is a mutation and obeys `--yes`. Omit it to
    /// start from a fresh default, which then needs `-o`.
    #[arg(
        value_name = "FILE|BANK:SLOT",
        required_unless_present_any = ["fields", "out"],
    )]
    pub target: Option<String>,

    /// `path=value`, repeatable. Paths are `nord-format`'s field names.
    #[arg(long = "set", value_name = "PATH=VALUE")]
    pub set: Vec<String>,

    /// Report what would change — including which bytes — and write nothing.
    #[arg(long)]
    pub dry_run: bool,

    /// List every settable field with its placement and current value, then exit. With
    /// no target, lists the fields of a fresh default.
    #[arg(long)]
    pub fields: bool,

    /// Write the edit here instead of over the input file.
    #[arg(short, long, value_name = "FILE")]
    pub out: Option<PathBuf>,

    /// Confirm the write. Editing a slot, or a file in place, needs it.
    #[arg(long)]
    pub yes: bool,
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    let ui = Ui::new(cli.color);
    device::set_recording(cli.record);

    let result = match cli.command {
        Command::Inspect { files, raw } => inspect(&ui, &files, raw),
        Command::Verify { files } => verify(&ui, &files),
        Command::Device { action } => match action {
            DeviceAction::Status { replay, json } => {
                let source = match replay {
                    Some(path) => device::Source::Replay(path),
                    None => device::Source::Usb,
                };
                device::status(&ui, source, json)
            }
            DeviceAction::Info => device::info(&ui),
            DeviceAction::Recover => device::recover(&ui),
            DeviceAction::Geometry => device::geometry(&ui),
            #[cfg(feature = "wedge")]
            DeviceAction::Wedge { class, yes } => {
                device::wedge(&ui, ObjectClass::from_raw(class), yes)
            }
            DeviceAction::Controls {
                from,
                to,
                len,
                interface,
                value,
                index,
            } => device::controls(&ui, from, to, len, interface, value, index),
        },
        Command::Program { action } => match action {
            ProgramAction::Slot(action) => slot_action(&ui, action, ObjectClass::Program),
            ProgramAction::Edit(args) => edit::run(&ui, args, ObjectClass::Program),
        },
        Command::Sample { action } => match action {
            SampleAction::Slot(action) => slot_action(&ui, action, ObjectClass::Sample),
            SampleAction::Edit(args) => sample::run(&ui, args),
        },
        Command::Setlist { action } => slot_action(&ui, action, ObjectClass::SetList),
        Command::Live { action } => match action {
            LiveAction::Slot(action) => slot_action(&ui, action.into(), ObjectClass::Live),
            LiveAction::Edit(args) => edit::run(&ui, args, ObjectClass::Live),
        },
        Command::Settings { action } => match action {
            SettingsAction::Edit(args) => edit::run(&ui, args, ObjectClass::Settings),
        },
        Command::Raw { class, action } => slot_action(&ui, action, ObjectClass::from_raw(class)),
    };

    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            ui.note(format!("{}: {e}", ui.danger("error")));
            ExitCode::FAILURE
        }
    }
}

impl From<LiveSlotAction> for SlotAction {
    fn from(action: LiveSlotAction) -> SlotAction {
        match action {
            LiveSlotAction::Get {
                at,
                out,
                body,
                sweep,
            } => SlotAction::Get {
                at,
                out,
                body,
                sweep,
            },
            LiveSlotAction::Info { at } => SlotAction::Info { at },
            LiveSlotAction::Deps { at } => SlotAction::Deps { at },
        }
    }
}

/// Dispatch one verb against a fixed object class, whichever noun asked for it.
///
/// The read-only verbs take a file as well as a slot ([`slot::Target`]); the rest name
/// device storage, which no file stands in for.
fn slot_action(ui: &Ui, action: SlotAction, class: ObjectClass) -> Result<(), String> {
    match action {
        SlotAction::Get {
            at,
            out,
            body,
            sweep,
        } => match slot::target(&at)? {
            slot::Target::File(path) if sweep => Err(format!(
                "--sweep re-reads the instrument as the panel changes; {} has only one state",
                path.display()
            )),
            slot::Target::File(path) => file::get(ui, &path, out, class, body),
            slot::Target::Slot(at) => match (sweep, out) {
                (true, Some(dir)) => device::sweep(ui, at, dir, class, body),
                (true, None) => Err("--sweep fills a directory; give -o a path".into()),
                (false, out) => device::get(ui, at, out, class, body),
            },
        },
        SlotAction::Put { file, at, yes } => device::put(ui, file, slot::parse(&at)?, class, yes),
        SlotAction::Move { from, to, yes } => {
            device::move_object(ui, slot::parse(&from)?, slot::parse(&to)?, class, yes)
        }
        SlotAction::Rename { at, name, yes } => {
            device::rename(ui, slot::parse(&at)?, name, class, yes)
        }
        SlotAction::Duplicate { from, to, yes } => {
            device::duplicate(ui, slot::parse(&from)?, slot::parse(&to)?, class, yes)
        }
        SlotAction::Delete { slots, yes } => {
            device::delete(ui, &slot::parse_all(&slots)?, class, yes)
        }
        SlotAction::Select { at } => device::select(ui, slot::parse(&at)?, class),
        SlotAction::Info { at } => match slot::target(&at)? {
            slot::Target::File(path) => file::info(ui, &path, class),
            slot::Target::Slot(at) => device::slot_info(ui, at, class),
        },
        SlotAction::Deps { at } => match slot::target(&at)? {
            slot::Target::File(path) => file::deps(ui, &path, class),
            slot::Target::Slot(at) => device::deps(ui, at, class),
        },
        SlotAction::Focus => device::focus(ui, class),
        SlotAction::List { cap } => device::list(ui, class, cap),
        SlotAction::Probe {
            op,
            args,
            wait,
            yes,
            bare,
            service,
            subsystem,
        } => device::probe(ui, class, op, &args, wait, yes, bare, service, subsystem),
    }
}

fn inspect(ui: &Ui, files: &[PathBuf], raw: bool) -> Result<(), String> {
    let mut failed = 0usize;
    for (i, path) in files.iter().enumerate() {
        if i > 0 {
            ui.out("");
        }
        ui.out(path.display());
        match nord_format::from_path(path) {
            Ok(entity) if raw => ui.out(format!("{entity:#?}")),
            Ok(entity) => summary::print(ui, &entity),
            Err(e) => {
                ui.note(format!("  error: {e}"));
                failed += 1;
            }
        }
    }
    match failed {
        0 => Ok(()),
        n => Err(format!("{n} of {} file(s) did not parse", files.len())),
    }
}

/// Parse each file and re-emit it, checking the bytes come back identical.
///
/// Reports the offset of the first difference, which in a bit-packed format is usually
/// enough to name the field on its own.
fn verify(ui: &Ui, files: &[PathBuf]) -> Result<(), String> {
    let mut failed = 0usize;
    for path in files {
        let original = match std::fs::read(path) {
            Ok(b) => b,
            Err(e) => {
                ui.out(format!("error  {} ({e})", path.display()));
                failed += 1;
                continue;
            }
        };
        let reencoded =
            nord_format::from_path(path).and_then(|entity| nord_format::to_bytes(&entity));
        match reencoded {
            Ok(bytes) if bytes == original => {
                ui.out(format!(
                    "ok     {} ({} bytes)",
                    path.display(),
                    original.len()
                ));
            }
            Ok(bytes) => {
                failed += 1;
                let at = bytes
                    .iter()
                    .zip(&original)
                    .position(|(a, b)| a != b)
                    .map(|i| format!("{i:#x}"))
                    .unwrap_or_else(|| "the end (length differs)".to_string());
                ui.out(format!(
                    "DIFFER {} (in {} bytes, out {}; first difference at {at})",
                    path.display(),
                    original.len(),
                    bytes.len(),
                ));
            }
            Err(e) => {
                failed += 1;
                ui.out(format!("error  {} ({e})", path.display()));
            }
        }
    }
    match failed {
        0 => Ok(()),
        n => Err(format!("{n} of {} file(s) did not round-trip", files.len())),
    }
}