nwnrs 0.0.1

Command-line inspection, conversion, packing, unpacking, and NWScript tooling for Neverwinter Nights resources
Documentation
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
use std::path::PathBuf;

use argh::FromArgs;

#[derive(FromArgs)]
/// Neverwinter Nights utility CLI.
pub(crate) struct Cli {
    #[argh(subcommand)]
    pub(crate) command: Command,
}

#[derive(FromArgs)]
#[argh(subcommand)]
pub(crate) enum Command {
    Convert(ConvertCmd),
    Inspect(InspectCmd),
    Init(InitCmd),
    New(NewCmd),
    Pack(PackCmd),
    Unpack(UnpackCmd),
    Nwsync(NwsyncCmd),
}

#[derive(FromArgs)]
#[argh(subcommand, name = "convert")]
/// convert supported NWN textures and mdl files
pub(crate) struct ConvertCmd {
    #[argh(switch, short = 'f')]
    /// overwrite existing output files
    pub(crate) force: bool,

    #[argh(option, default = "String::from(\"dxt5\")")]
    /// dds block format when OUTPUT ends in .dds: dxt1 or dxt5
    pub(crate) dds_format: String,

    #[argh(option)]
    /// install root for install-backed conversions such as utc -> obj
    pub(crate) root: Option<PathBuf>,

    #[argh(option)]
    /// user directory for install-backed conversions; defaults to autodetect
    pub(crate) user: Option<PathBuf>,

    #[argh(option, default = "String::from(\"english\")")]
    /// install language for install-backed conversions
    pub(crate) language: String,

    #[argh(switch)]
    /// include the install override directory for install-backed conversions
    pub(crate) load_ovr: bool,

    #[argh(option)]
    /// explicit animation name to snapshot for obj export
    pub(crate) animation: Option<String>,

    #[argh(option)]
    /// animation time in seconds for obj export
    pub(crate) time: Option<f32>,

    #[argh(switch)]
    /// list available animations for mdl or utc input and exit
    pub(crate) list_animations: bool,

    #[argh(positional)]
    /// input file path
    pub(crate) input: PathBuf,

    #[argh(positional)]
    /// output file path when converting to a new file
    pub(crate) output: Option<PathBuf>,
}

#[derive(FromArgs)]
#[argh(subcommand, name = "inspect")]
/// inspect a single NWN resource file by extension
// This struct has 8 bool fields, exceeding clippy::pedantic's threshold of 3.
// They cannot be collapsed into enums or a state machine because argh requires
// bool fields for `#[argh(switch)]`, and each flag is an independent CLI option
// with no mutual exclusivity
#[allow(clippy::struct_excessive_bools)]
pub(crate) struct InspectCmd {
    #[argh(switch)]
    /// for .ncs input, render internal opcode/aux names instead of canonical
    /// mnemonics
    pub(crate) internal_names: bool,

    #[argh(option, default = "15")]
    /// for .ncs input, maximum rendered string length before truncation
    pub(crate) max_string_length: usize,

    #[argh(switch)]
    /// for .ncs input, require a sibling .ndb file
    pub(crate) require_ndb: bool,

    #[argh(switch)]
    /// for .ncs input, ignore a sibling .ndb file
    pub(crate) no_ndb: bool,

    #[argh(switch)]
    /// for .ncs input, suppress source weaving even when .ndb and source files
    /// are available
    pub(crate) no_source_weave: bool,

    #[argh(switch)]
    /// for .ncs input, suppress per-function local offsets
    pub(crate) no_local_offsets: bool,

    #[argh(switch)]
    /// for .ncs input, skip synthetic jump labels
    pub(crate) no_labels: bool,

    #[argh(switch)]
    /// for .ncs input, suppress global offsets
    pub(crate) no_offsets: bool,

    #[argh(switch)]
    /// for .ncs input, skip loading nwscript.nss for builtin action names
    pub(crate) no_langspec: bool,

    #[argh(option)]
    /// for .ncs input, explicit nwscript.nss path instead of sibling lookup
    pub(crate) langspec: Option<PathBuf>,

    #[argh(positional)]
    /// path to the file to inspect
    pub(crate) path: PathBuf,
}

#[derive(FromArgs)]
#[argh(subcommand, name = "unpack")]
/// unpack a resource into a directory
pub(crate) struct UnpackCmd {
    #[argh(option, short = 'd', default = "PathBuf::from(\".\")")]
    /// destination directory
    pub(crate) directory: PathBuf,

    #[argh(switch, short = 'f')]
    /// overwrite existing output files
    pub(crate) force: bool,

    #[argh(positional)]
    /// input file to unpack
    pub(crate) input: PathBuf,
}

#[derive(FromArgs)]
#[argh(subcommand, name = "init")]
/// initialize an NWN project in an existing directory
pub(crate) struct InitCmd {
    #[argh(option)]
    /// project output kind such as utc, 2da, tlk, ssf, mdl, tga, dds, plt, ncs,
    /// mod, hak, nwm, erf, or key
    pub(crate) kind: Option<String>,

    #[argh(positional)]
    /// directory to initialize; defaults to the current directory
    pub(crate) path: Option<PathBuf>,
}

#[derive(FromArgs)]
#[argh(subcommand, name = "new")]
/// create a new NWN project directory
pub(crate) struct NewCmd {
    #[argh(option)]
    /// project output kind such as utc, 2da, tlk, ssf, mdl, tga, dds, plt, ncs,
    /// mod, hak, nwm, erf, or key
    pub(crate) kind: Option<String>,

    #[argh(positional)]
    /// directory to create
    pub(crate) path: PathBuf,
}

#[derive(FromArgs, Clone)]
#[argh(subcommand, name = "pack")]
/// pack resources into NWN binary form, including compiling NWScript source
pub(crate) struct PackCmd {
    #[argh(switch, short = 'f')]
    /// overwrite existing output files
    pub(crate) force: bool,

    #[argh(switch)]
    /// when packing .nss to .ncs, also write debugger output as a sibling .ndb
    /// file
    pub(crate) debug: bool,

    #[argh(switch)]
    /// skip main/StartingConditional entrypoint validation for compiled .nss
    /// inputs
    pub(crate) no_entrypoint_check: bool,

    #[argh(option)]
    /// explicit nwscript.nss path for compiled .nss inputs
    pub(crate) langspec: Option<PathBuf>,

    #[argh(option)]
    /// extra directory to search for #include files in compiled .nss inputs;
    /// may be repeated
    pub(crate) include_dir: Vec<PathBuf>,

    #[argh(option, default = "String::from(\"O0\")")]
    /// optimization level for compiled .nss inputs: O0, O1, O2, or O3
    pub(crate) optimization: String,

    #[argh(option, short = 'j')]
    /// parallel NWScript compile workers; defaults to available CPU parallelism
    pub(crate) jobs: Option<usize>,

    #[argh(option, default = "String::from(\"V1\")")]
    /// data file version to write (V1 or E1)
    pub(crate) data_version: String,

    #[argh(option, default = "String::from(\"none\")")]
    /// compression for E1 (none, zlib, zstd)
    pub(crate) data_compression: String,

    #[argh(switch)]
    /// do not squash bif files into the same directory as the key
    pub(crate) no_squash: bool,

    #[argh(switch)]
    /// don't follow symlinks
    pub(crate) no_symlinks: bool,

    #[argh(option, short = 'e')]
    /// override archive header type when packing erf/mod/hak/nwm
    pub(crate) erf_type: Option<String>,

    #[argh(option)]
    /// package mode: explicit NWN install root override
    pub(crate) root: Option<PathBuf>,

    #[argh(option)]
    /// package mode: language root under root/lang to resolve
    pub(crate) language: Option<String>,

    #[argh(positional)]
    /// explicit pack mode: INPUT OUTPUT; package mode: `KEY_NAME` `OUTPUT_DIR`
    pub(crate) paths: Vec<PathBuf>,
}

pub(crate) struct KeyPackCmd {
    pub(crate) data_version:        String,
    pub(crate) data_compression:    String,
    pub(crate) no_squash:           bool,
    pub(crate) no_symlinks:         bool,
    pub(crate) force:               bool,
    pub(crate) debug:               bool,
    pub(crate) no_entrypoint_check: bool,
    pub(crate) langspec:            Option<PathBuf>,
    pub(crate) include_dir:         Vec<PathBuf>,
    pub(crate) optimization:        String,
    pub(crate) jobs:                Option<usize>,
    pub(crate) key:                 String,
    pub(crate) source:              PathBuf,
    pub(crate) destination:         PathBuf,
}

pub(crate) struct KeyUnpackCmd {
    pub(crate) force:       bool,
    pub(crate) key:         PathBuf,
    pub(crate) destination: PathBuf,
}

#[derive(FromArgs)]
#[argh(subcommand, name = "nwsync")]
/// nwsync repository utilities
pub(crate) struct NwsyncCmd {
    #[argh(subcommand)]
    pub(crate) command: NwsyncCommand,
}

#[derive(FromArgs)]
#[argh(subcommand)]
pub(crate) enum NwsyncCommand {
    Print(NwsyncPrintCmd),
    Fetch(NwsyncFetchCmd),
    Prune(NwsyncPruneCmd),
    Write(NwsyncWriteCmd),
}

#[derive(FromArgs)]
#[argh(subcommand, name = "print")]
/// print manifest contents from a manifest file or nwsync repository
pub(crate) struct NwsyncPrintCmd {
    #[argh(option)]
    /// manifest sha1 to print when INPUT is a nwsync repository
    pub(crate) manifest: Option<String>,

    #[argh(positional)]
    /// manifest file or nwsync repository root
    pub(crate) input: PathBuf,
}

#[derive(FromArgs)]
#[argh(subcommand, name = "fetch")]
/// download a manifest and its resources from a remote nwsync server
pub(crate) struct NwsyncFetchCmd {
    #[argh(positional)]
    /// remote manifest URL to fetch
    pub(crate) url: String,

    #[argh(option, short = 'o')]
    /// output directory for downloaded files
    pub(crate) output: Option<PathBuf>,
}

#[derive(FromArgs)]
#[argh(subcommand, name = "prune")]
/// trim unreferenced data from nwsync repository
pub(crate) struct NwsyncPruneCmd {
    #[argh(positional)]
    /// nwsync repository root
    pub(crate) repository: PathBuf,

    #[argh(switch)]
    /// dry run - show what would be removed without actually removing
    pub(crate) dry_run: bool,
}

#[derive(FromArgs)]
#[argh(subcommand, name = "write")]
/// generate a serverside `NWSync` manifest from directory
pub(crate) struct NwsyncWriteCmd {
    #[argh(positional)]
    /// input directory containing NWN resources
    pub(crate) input: PathBuf,

    #[argh(positional)]
    /// output manifest file path
    pub(crate) output: PathBuf,

    #[argh(switch, short = 'f')]
    /// overwrite existing output file
    pub(crate) force: bool,
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use argh::FromArgs;

    use super::{Cli, Command, InspectCmd, NwsyncCommand};

    #[test]
    fn parses_pack_command_with_repeated_include_dirs() {
        let cli = Cli::from_args(
            &["nwnrs"],
            &[
                "pack",
                "--debug",
                "--no-entrypoint-check",
                "--include-dir",
                "inc/a",
                "--include-dir",
                "inc/b",
                "--optimization",
                "O2",
                "-j",
                "4",
                "scripts/test.nss",
                "out/test.ncs",
            ],
        )
        .unwrap_or_else(|error| panic!("parse pack args: {error:?}"));

        let Command::Pack(cmd) = cli.command else {
            panic!("expected pack command");
        };
        assert!(cmd.debug);
        assert!(cmd.no_entrypoint_check);
        assert_eq!(cmd.optimization, "O2");
        assert_eq!(cmd.jobs, Some(4));
        assert_eq!(
            cmd.include_dir,
            vec![PathBuf::from("inc/a"), PathBuf::from("inc/b")]
        );
        assert_eq!(
            cmd.paths,
            vec![
                PathBuf::from("scripts/test.nss"),
                PathBuf::from("out/test.ncs")
            ]
        );
    }

    #[test]
    fn parses_init_command_with_kind_and_path() {
        let cli = Cli::from_args(&["nwnrs"], &["init", "--kind", "utc", "project"])
            .unwrap_or_else(|error| panic!("parse init args: {error:?}"));

        let Command::Init(cmd) = cli.command else {
            panic!("expected init command");
        };
        assert_eq!(cmd.kind.as_deref(), Some("utc"));
        assert_eq!(cmd.path, Some(PathBuf::from("project")));
    }

    #[test]
    fn parses_new_command_with_kind_and_path() {
        let cli = Cli::from_args(&["nwnrs"], &["new", "--kind", "mod", "my_mod"])
            .unwrap_or_else(|error| panic!("parse new args: {error:?}"));

        let Command::New(cmd) = cli.command else {
            panic!("expected new command");
        };
        assert_eq!(cmd.kind.as_deref(), Some("mod"));
        assert_eq!(cmd.path, PathBuf::from("my_mod"));
    }

    #[test]
    fn parses_nwsync_fetch_command() {
        let cli = Cli::from_args(
            &["nwnrs"],
            &[
                "nwsync",
                "fetch",
                "https://example.invalid/manifest/abcd",
                "-o",
                "repo",
            ],
        )
        .unwrap_or_else(|error| panic!("parse nwsync args: {error:?}"));

        let Command::Nwsync(cmd) = cli.command else {
            panic!("expected nwsync command");
        };
        let NwsyncCommand::Fetch(cmd) = cmd.command else {
            panic!("expected fetch subcommand");
        };
        assert_eq!(cmd.url, "https://example.invalid/manifest/abcd");
        assert_eq!(cmd.output, Some(PathBuf::from("repo")));
    }

    #[test]
    fn parses_convert_command_for_mdl_paths() {
        let cli = Cli::from_args(
            &["nwnrs"],
            &["convert", "-f", "models/input.mdl", "models/output.mdl"],
        )
        .unwrap_or_else(|error| panic!("parse convert args: {error:?}"));

        let Command::Convert(cmd) = cli.command else {
            panic!("expected convert command");
        };
        assert!(cmd.force);
        assert_eq!(cmd.root, None);
        assert_eq!(cmd.user, None);
        assert_eq!(cmd.language, "english");
        assert!(!cmd.load_ovr);
        assert_eq!(cmd.animation, None);
        assert_eq!(cmd.time, None);
        assert!(!cmd.list_animations);
        assert_eq!(cmd.input, PathBuf::from("models/input.mdl"));
        assert_eq!(cmd.output, Some(PathBuf::from("models/output.mdl")));
    }

    #[test]
    fn parses_convert_command_for_animation_listing_without_output() {
        let cli = Cli::from_args(
            &["nwnrs"],
            &[
                "convert",
                "--list-animations",
                "--animation",
                "default",
                "--time",
                "0.0",
                "models/input.mdl",
            ],
        )
        .unwrap_or_else(|error| panic!("parse convert args: {error:?}"));

        let Command::Convert(cmd) = cli.command else {
            panic!("expected convert command");
        };
        assert!(cmd.list_animations);
        assert_eq!(cmd.animation.as_deref(), Some("default"));
        assert_eq!(cmd.time, Some(0.0));
        assert_eq!(cmd.input, PathBuf::from("models/input.mdl"));
        assert_eq!(cmd.output, None);
    }

    #[test]
    fn parses_inspect_command_with_ncs_disassembly_options() {
        let cli = Cli::from_args(
            &["nwnrs"],
            &[
                "inspect",
                "--internal-names",
                "--max-string-length",
                "42",
                "--require-ndb",
                "--no-source-weave",
                "--no-local-offsets",
                "--no-labels",
                "--no-offsets",
                "--no-langspec",
                "--langspec",
                "specs/custom.nss",
                "scripts/test.ncs",
            ],
        )
        .unwrap_or_else(|error| panic!("parse inspect args: {error:?}"));

        let Command::Inspect(InspectCmd {
            internal_names,
            max_string_length,
            require_ndb,
            no_ndb,
            no_source_weave,
            no_local_offsets,
            no_labels,
            no_offsets,
            no_langspec,
            langspec,
            path,
        }) = cli.command
        else {
            panic!("expected inspect command");
        };

        assert!(internal_names);
        assert_eq!(max_string_length, 42);
        assert!(require_ndb);
        assert!(!no_ndb);
        assert!(no_source_weave);
        assert!(no_local_offsets);
        assert!(no_labels);
        assert!(no_offsets);
        assert!(no_langspec);
        assert_eq!(langspec, Some(PathBuf::from("specs/custom.nss")));
        assert_eq!(path, PathBuf::from("scripts/test.ncs"));
    }

    #[test]
    fn parses_pack_command_for_generic_packing() {
        let cli = Cli::from_args(
            &["nwnrs"],
            &["pack", "--data-version", "E1", "input", "output.key"],
        )
        .unwrap_or_else(|error| panic!("parse pack args: {error:?}"));

        let Command::Pack(cmd) = cli.command else {
            panic!("expected pack command");
        };

        assert_eq!(cmd.data_version, "E1");
        assert_eq!(
            cmd.paths,
            vec![PathBuf::from("input"), PathBuf::from("output.key")]
        );
        assert_eq!(cmd.root, None);
        assert_eq!(cmd.language, None);
    }

    #[test]
    fn parses_pack_command_for_install_packaging() {
        let cli = Cli::from_args(
            &["nwnrs"],
            &[
                "pack",
                "-f",
                "--root",
                "/srv/nwn",
                "--language",
                "en",
                "--data-version",
                "E1",
                "--data-compression",
                "zstd",
                "custom_base.key",
                "docker/data/data",
            ],
        )
        .unwrap_or_else(|error| panic!("parse pack args: {error:?}"));

        let Command::Pack(cmd) = cli.command else {
            panic!("expected pack command");
        };

        assert!(cmd.force);
        assert_eq!(cmd.root, Some(PathBuf::from("/srv/nwn")));
        assert_eq!(cmd.language, Some("en".to_string()));
        assert_eq!(cmd.data_version, "E1");
        assert_eq!(cmd.data_compression, "zstd");
        assert_eq!(
            cmd.paths,
            vec![
                PathBuf::from("custom_base.key"),
                PathBuf::from("docker/data/data")
            ]
        );
    }
}