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
// SPDX-License-Identifier: GPL-3.0-or-later
use std::io::Write;
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::{
AddOptions, AddPlan, ArchiveEntry, ArchiveFormat, CreateOptions, CreatePlan, DiffOptions,
DiffReport, ExtractAllOptions, ExtractAllPlan, ExtractOptions, ExtractSummary, Result,
VerifyOptions, VerifyReport,
};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Basic metadata about an archive.
#[non_exhaustive]
pub struct ArchiveInfo {
/// Path that was opened, formatted for display.
pub path: String,
/// Detected archive family.
pub format: ArchiveFormat,
/// Number of file entries in the archive.
pub file_count: usize,
/// Number of entries with recoverable path names.
pub named_entry_count: usize,
/// Whether any entries do not have recoverable path names.
pub has_unnameable_entries: bool,
/// Whether this tool can rewrite the archive without known lossy behavior.
pub rewritable: bool,
/// Explanation when `rewritable` is false.
#[serde(skip_serializing_if = "Option::is_none")]
pub rewrite_blocker: Option<String>,
/// TES4-family metadata when `format` is [`ArchiveFormat::Tes4`].
#[serde(skip_serializing_if = "Option::is_none")]
pub tes4: Option<Tes4Info>,
/// BA2 metadata when `format` is [`ArchiveFormat::Ba2`].
#[serde(skip_serializing_if = "Option::is_none")]
pub ba2: Option<Ba2Info>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// TES4-family archive metadata that affects rewrite behavior.
#[non_exhaustive]
pub struct Tes4Info {
/// Human-readable TES4 archive version reported by the backend.
pub version: String,
/// Human-readable archive type flags.
pub archive_types: String,
/// Raw archive type flag bits.
pub archive_types_bits: u16,
/// Human-readable archive flag names.
pub archive_flags: Vec<String>,
/// Raw archive flag bits.
pub archive_flags_bits: u32,
/// Raw archive flag bits this tool does not know how to preserve during rewrite.
pub unsupported_archive_flags_bits: u32,
/// Path/name storage mode reported by the backend.
pub name_mode: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// BA2 archive metadata that affects rewrite behavior.
#[non_exhaustive]
pub struct Ba2Info {
/// Human-readable BA2 archive version reported by the backend.
pub version: String,
/// Human-readable BA2 payload format, such as general or texture payloads.
pub payload_format: String,
/// Human-readable compression format reported by the backend.
pub compression_format: String,
/// Whether the archive contains a string table.
pub strings: bool,
}
/// Opened archive handle for batch inspection and extraction without reopening the file.
pub struct OpenArchive {
path: String,
archive: crate::loaded::LoadedArchive,
}
impl OpenArchive {
/// Open an archive once and keep its index available for repeated operations.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened or parsed.
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
let archive = crate::loaded::LoadedArchive::open(path)?;
Ok(Self {
path: path.display().to_string(),
archive,
})
}
/// Return archive format plus file-count metadata.
#[must_use]
pub fn info(&self) -> ArchiveInfo {
archive_info(&self.path, &self.archive)
}
/// Return the detected archive family.
#[must_use]
pub fn format(&self) -> ArchiveFormat {
self.archive.format()
}
/// Return the number of file entries in the archive.
#[must_use]
pub fn file_count(&self) -> usize {
self.archive.file_count()
}
/// List all entries in the archive.
///
/// # Errors
///
/// Returns an error if the archive index cannot be read into entry metadata.
pub fn list(&self) -> Result<Vec<ArchiveEntry>> {
self.archive.list_entries()
}
/// Read a single archive entry into memory.
///
/// # Errors
///
/// Returns an error if the entry cannot be found or its payload cannot be read.
pub fn read_entry(&self, entry: &str) -> Result<Vec<u8>> {
self.archive.read_entry_bytes(entry)
}
/// Read a single archive entry selected by normalized archive path bytes into memory.
///
/// # Errors
///
/// Returns an error if the entry cannot be found or its payload cannot be read.
pub fn read_entry_by_path_bytes(&self, entry: &[u8]) -> Result<Vec<u8>> {
self.archive.read_entry_bytes_by_path(entry)
}
/// Read a single archive entry selected by normalized archive path bytes into memory.
///
/// Prefer [`Self::read_entry_by_path_bytes`] in new code; this name predates the explicit
/// distinction between display paths, filesystem paths, and archive path bytes.
///
/// # Errors
///
/// Returns an error if the entry cannot be found or its payload cannot be read.
pub fn read_entry_by_path(&self, entry: &[u8]) -> Result<Vec<u8>> {
self.read_entry_by_path_bytes(entry)
}
/// Extract a single archive entry into a writer without materializing the whole payload.
///
/// # Errors
///
/// Returns an error if the entry cannot be found, the payload cannot be read, or the writer fails.
pub fn extract_entry_to_writer(&self, entry: &str, out: &mut dyn Write) -> Result<u64> {
self.archive.extract_entry_to_writer(entry, out)
}
/// Extract a single archive entry selected by normalized archive path bytes into a writer.
///
/// # Errors
///
/// Returns an error if the entry cannot be found, the payload cannot be read, or the writer fails.
pub fn extract_entry_by_path_bytes_to_writer(
&self,
entry: &[u8],
out: &mut dyn Write,
) -> Result<u64> {
self.archive.extract_entry_path_to_writer(entry, out)
}
/// Extract a single archive entry selected by normalized archive path bytes into a writer.
///
/// Prefer [`Self::extract_entry_by_path_bytes_to_writer`] in new code; this name predates the
/// explicit byte-path API naming convention.
///
/// # Errors
///
/// Returns an error if the entry cannot be found, the payload cannot be read, or the writer fails.
pub fn extract_entry_path_to_writer(&self, entry: &[u8], out: &mut dyn Write) -> Result<u64> {
self.extract_entry_by_path_bytes_to_writer(entry, out)
}
}
pub(crate) fn archive_info(path: &str, archive: &crate::loaded::LoadedArchive) -> ArchiveInfo {
archive_info_ref(path, archive.as_ref())
}
pub(crate) fn archive_info_ref(
path: &str,
archive: crate::loaded::LoadedArchiveRef<'_>,
) -> ArchiveInfo {
let rewrite_blocker = crate::rewrite_policy::rewrite_blocker(archive).map(str::to_string);
ArchiveInfo {
path: path.to_string(),
format: archive.format(),
file_count: archive.file_count(),
named_entry_count: archive.named_entry_count(),
has_unnameable_entries: archive.has_unnameable_entries(),
rewritable: rewrite_blocker.is_none(),
rewrite_blocker,
tes4: tes4_info(archive),
ba2: ba2_info(archive),
}
}
fn tes4_info(archive: crate::loaded::LoadedArchiveRef<'_>) -> Option<Tes4Info> {
let dream_archive::Archive::Tes4Bsa(archive) = archive.as_dream_archive() else {
return None;
};
let info = archive.info();
let flags = info.archive_flags;
let directory_strings =
flags.contains(dream_archive::bsa::tes4::ArchiveFlags::DIRECTORY_STRINGS);
let file_strings = flags.contains(dream_archive::bsa::tes4::ArchiveFlags::FILE_STRINGS);
let embedded_file_names =
flags.contains(dream_archive::bsa::tes4::ArchiveFlags::EMBEDDED_FILE_NAMES);
Some(Tes4Info {
version: format!("{:?}", info.version),
archive_types: format!("{:?}", info.archive_types),
archive_types_bits: info.archive_types.bits(),
archive_flags: tes4_archive_flags(flags),
archive_flags_bits: flags.bits(),
unsupported_archive_flags_bits: crate::rewrite_policy::tes4_unsupported_archive_flag_bits(
flags,
),
name_mode: tes4_name_mode(directory_strings, file_strings, embedded_file_names).to_string(),
})
}
fn tes4_archive_flags(flags: dream_archive::bsa::tes4::ArchiveFlags) -> Vec<String> {
let mut names = Vec::new();
if flags.contains(dream_archive::bsa::tes4::ArchiveFlags::DIRECTORY_STRINGS) {
names.push("directory-strings".to_string());
}
if flags.contains(dream_archive::bsa::tes4::ArchiveFlags::FILE_STRINGS) {
names.push("file-strings".to_string());
}
if flags.contains(dream_archive::bsa::tes4::ArchiveFlags::COMPRESSED) {
names.push("compressed".to_string());
}
if flags.contains(dream_archive::bsa::tes4::ArchiveFlags::EMBEDDED_FILE_NAMES) {
names.push("embedded-file-names".to_string());
}
names
}
fn tes4_name_mode(
directory_strings: bool,
file_strings: bool,
embedded_file_names: bool,
) -> &'static str {
match (directory_strings && file_strings, embedded_file_names) {
(true, true) => "strings-and-embedded",
(true, false) => "strings",
(false, true) => "embedded",
(false, false) => "hash-only",
}
}
fn ba2_info(archive: crate::loaded::LoadedArchiveRef<'_>) -> Option<Ba2Info> {
let dream_archive::Archive::BA2(archive) = archive.as_dream_archive() else {
return None;
};
let info = archive.info();
Some(Ba2Info {
version: format!("{:?}", info.version),
payload_format: format!("{:?}", info.format).to_ascii_lowercase(),
compression_format: format!("{:?}", info.compression_format).to_ascii_lowercase(),
strings: info.strings,
})
}
/// Stateless facade for archive inspection, extraction, creation, and update operations.
///
/// This type exists to provide a compact public API shared by the CLI and Luau bindings. Each method
/// opens the archive it operates on; callers that need repeated list/read/extract operations should
/// use [`OpenArchive`] to avoid reopening and rebuilding archive indexes.
#[derive(Debug, Default, Clone, Copy)]
pub struct ArchiveTool;
impl ArchiveTool {
/// Open an archive handle for repeated list/read/extract operations.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened or parsed.
pub fn open(path: impl AsRef<Path>) -> Result<OpenArchive> {
OpenArchive::open(path)
}
/// Detect an archive format from its file header without opening it as a full archive.
///
/// # Errors
///
/// Returns an error if the file cannot be read or its header is not a supported archive format.
pub fn guess_format(path: impl AsRef<Path>) -> Result<ArchiveFormat> {
crate::format::guess_format(path.as_ref())
}
/// Open an archive and return format plus file-count metadata.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened or parsed.
pub fn info(path: impl AsRef<Path>) -> Result<ArchiveInfo> {
let path = path.as_ref();
let archive = crate::loaded::LoadedArchive::open(path)?;
Ok(archive_info(&path.display().to_string(), &archive))
}
/// List all entries in an archive.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened or its entries cannot be listed.
pub fn list(path: impl AsRef<Path>) -> Result<Vec<ArchiveEntry>> {
crate::entry::list_entries(path.as_ref())
}
/// Read a single archive entry into memory.
///
/// Entry path matching is case-insensitive and treats `\` as `/`.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, the entry cannot be found, or its payload cannot be read.
pub fn read_entry(path: impl AsRef<Path>, entry: &str) -> Result<Vec<u8>> {
crate::extract::read_entry_bytes(path.as_ref(), entry)
}
/// Read a single archive entry selected by normalized archive path bytes into memory.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, the entry cannot be found, or its payload cannot be read.
pub fn read_entry_by_path_bytes(path: impl AsRef<Path>, entry: &[u8]) -> Result<Vec<u8>> {
crate::extract::read_entry_bytes_by_path(path.as_ref(), entry)
}
/// Read a single archive entry selected by normalized archive path bytes into memory.
///
/// Prefer [`Self::read_entry_by_path_bytes`] in new code; this name predates the explicit
/// distinction between display paths, filesystem paths, and archive path bytes.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, the entry cannot be found, or its payload cannot be read.
pub fn read_entry_by_path(path: impl AsRef<Path>, entry: &[u8]) -> Result<Vec<u8>> {
Self::read_entry_by_path_bytes(path, entry)
}
/// Extract a single archive entry into a writer without materializing the whole payload.
///
/// Entry path matching is case-insensitive and treats `\` as `/`.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, the entry cannot be found, the payload cannot be read, or the writer fails.
pub fn extract_entry_to_writer(
path: impl AsRef<Path>,
entry: &str,
out: &mut dyn Write,
) -> Result<u64> {
crate::extract::extract_entry_to_writer(path.as_ref(), entry, out)
}
/// Extract a single archive entry selected by normalized archive path bytes into a writer.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, the entry cannot be found, the payload cannot be read, or the writer fails.
pub fn extract_entry_by_path_bytes_to_writer(
path: impl AsRef<Path>,
entry: &[u8],
out: &mut dyn Write,
) -> Result<u64> {
crate::extract::extract_entry_path_to_writer(path.as_ref(), entry, out)
}
/// Extract a single archive entry selected by normalized archive path bytes into a writer.
///
/// Prefer [`Self::extract_entry_by_path_bytes_to_writer`] in new code; this name predates the
/// explicit byte-path API naming convention.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, the entry cannot be found, the payload cannot be read, or the writer fails.
pub fn extract_entry_path_to_writer(
path: impl AsRef<Path>,
entry: &[u8],
out: &mut dyn Write,
) -> Result<u64> {
Self::extract_entry_by_path_bytes_to_writer(path, entry, out)
}
/// Extract a single archive entry to disk according to `options`.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, the entry cannot be found, extraction is unsafe, or filesystem writes fail.
pub fn extract(
path: impl AsRef<Path>,
entry: &str,
options: &ExtractOptions,
) -> Result<ExtractSummary> {
crate::extract::extract_entry(path.as_ref(), entry, options)
}
/// Extract a single archive entry selected by normalized archive path bytes to disk.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, the entry cannot be found, extraction is unsafe, or filesystem writes fail.
pub fn extract_by_path_bytes(
path: impl AsRef<Path>,
entry: &[u8],
options: &ExtractOptions,
) -> Result<ExtractSummary> {
crate::extract::extract_entry_by_path(path.as_ref(), entry, options)
}
/// Extract a single archive entry selected by normalized archive path bytes to disk.
///
/// Prefer [`Self::extract_by_path_bytes`] in new code; this name predates the explicit
/// byte-path API naming convention.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, the entry cannot be found, extraction is unsafe, or filesystem writes fail.
pub fn extract_by_path(
path: impl AsRef<Path>,
entry: &[u8],
options: &ExtractOptions,
) -> Result<ExtractSummary> {
Self::extract_by_path_bytes(path, entry, options)
}
/// Extract selected archive entries by normalized archive path bytes.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, a requested entry cannot be found, extraction is unsafe, or filesystem writes fail.
pub fn extract_many_by_path_bytes(
path: impl AsRef<Path>,
entries: &[Vec<u8>],
options: &ExtractOptions,
) -> Result<ExtractSummary> {
crate::extract::extract_entries_by_path(path.as_ref(), entries, options)
}
/// Plan selected archive entry extraction without writing files.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, a requested entry cannot be found, or the extraction plan is unsafe.
pub fn plan_extract_many_by_path_bytes(
path: impl AsRef<Path>,
entries: &[Vec<u8>],
options: &ExtractOptions,
) -> Result<ExtractAllPlan> {
crate::extract::plan_extract_entries_by_path(path.as_ref(), entries, options)
}
/// Extract every archive entry to disk according to `options`.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, planned targets are unsafe, or filesystem writes fail.
pub fn extract_all(
path: impl AsRef<Path>,
options: &ExtractAllOptions,
) -> Result<ExtractSummary> {
crate::extract::extract_all(path.as_ref(), options)
}
/// Plan full archive extraction without writing files.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened or planned targets are unsafe.
pub fn plan_extract_all(
path: impl AsRef<Path>,
options: &ExtractAllOptions,
) -> Result<ExtractAllPlan> {
crate::extract::plan_extract_all(path.as_ref(), options)
}
/// Create a new archive from a file or directory.
///
/// Returns the number of entries written. Existing output is replaced only after a successful
/// write to a temporary file in the output directory.
///
/// # Errors
///
/// Returns an error if inputs cannot be read, archive options are unsupported, paths are invalid, or output writes fail.
pub fn create(
output: impl AsRef<Path>,
input: impl AsRef<Path>,
options: &CreateOptions,
) -> Result<usize> {
crate::create::create_archive(output.as_ref(), input.as_ref(), options)
}
/// Plan archive creation without writing output.
///
/// # Errors
///
/// Returns an error if inputs cannot be read, archive options are unsupported, or paths are invalid.
pub fn plan_create(
output: impl AsRef<Path>,
input: impl AsRef<Path>,
options: &CreateOptions,
) -> Result<CreatePlan> {
crate::create::plan_create_archive(output.as_ref(), input.as_ref(), options)
}
/// Add or replace entries by rewriting an archive.
///
/// When `options.output` is omitted, the source archive is replaced after a successful full
/// rewrite. New inputs replace existing archive entries with the same archive path.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, rewrite is unsupported, inputs are invalid, or output writes fail.
pub fn add(path: impl AsRef<Path>, options: &AddOptions) -> Result<usize> {
crate::create::add_to_archive(path.as_ref(), options)
}
/// Plan archive add/update without writing output.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened, rewrite is unsupported, or inputs are invalid.
pub fn plan_add(path: impl AsRef<Path>, options: &AddOptions) -> Result<AddPlan> {
crate::create::plan_add_to_archive(path.as_ref(), options)
}
/// Verify archive index health and, optionally, payload readability.
///
/// # Errors
///
/// Returns an error if the archive cannot be opened or verification cannot inspect the requested payloads.
pub fn verify(path: impl AsRef<Path>, options: &VerifyOptions) -> Result<VerifyReport> {
crate::verify::verify_archive(path.as_ref(), options)
}
/// Compare two archives by normalized path bytes and optional payload hashes.
///
/// # Errors
///
/// Returns an error if either archive cannot be opened or requested payload hashes cannot be read.
pub fn diff(
old: impl AsRef<Path>,
new: impl AsRef<Path>,
options: &DiffOptions,
) -> Result<DiffReport> {
crate::diff::diff_archives(old.as_ref(), new.as_ref(), options)
}
}
#[cfg(test)]
mod tests {
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};
use super::*;
#[test]
fn reports_tes3_info() {
let dir = std::env::temp_dir().join(format!(
"dream_archivetool-info-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&dir).unwrap();
let archive_path = dir.join("test.bsa");
let mut builder = dream_archive::Tes3BsaBuilder::new();
builder.add_bytes("meshes/example.nif", b"payload").unwrap();
builder.write_path(&archive_path).unwrap();
let info = ArchiveTool::info(&archive_path).unwrap();
assert_eq!(info.format, ArchiveFormat::Tes3);
assert_eq!(info.file_count, 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn open_archive_reuses_loaded_index() {
let dir = std::env::temp_dir().join(format!(
"dream_archivetool-open-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&dir).unwrap();
let archive_path = dir.join("test.bsa");
let mut builder = dream_archive::Tes3BsaBuilder::new();
builder.add_bytes("icons/gold.dds", b"gold").unwrap();
builder.write_path(&archive_path).unwrap();
let archive = ArchiveTool::open(&archive_path).unwrap();
assert_eq!(archive.info().file_count, 1);
assert_eq!(archive.list().unwrap()[0].path, "icons/gold.dds");
assert_eq!(archive.read_entry("icons/gold.dds").unwrap(), b"gold");
fs::remove_dir_all(dir).unwrap();
}
}