use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use dream_archive::ByteSlice as _;
use dream_archive::CompressionOverride;
use dream_archive::ba2::{
ArchiveVersion as Ba2ArchiveVersion, Ba2CompressionFormat, PayloadFormat,
};
use dream_archive::bsa::tes4::{ArchiveVersion as Tes4ArchiveVersion, NameMode};
use serde::{Deserialize, Serialize};
mod input;
mod temp_output;
use crate::ArchiveFormat;
pub use crate::archive_plan::{
AddPlan, ArchivePlanAction, ArchivePlanEntry, ArchivePlanOperation, CreatePlan,
};
use crate::host_file::{keep_permissions, parent_directory};
use crate::paths::{
archive_path_bytes_to_display, archive_path_bytes_to_hex, normalize_archive_path_bytes,
};
use crate::{ArchiveError, Result};
use input::{collect_input_entry_paths, insert_input_path};
use temp_output::{persist_temp_output, with_temp_output, write_temp_output};
#[derive(Debug, Clone)]
pub struct CreateOptions {
pub format: ArchiveFormat,
pub tes4_version: Tes4Version,
pub ba2_kind: Ba2ArchiveKind,
pub ba2_version: Ba2Version,
pub compress: bool,
pub fsync: bool,
pub follow_symlinks: bool,
}
impl Default for CreateOptions {
fn default() -> Self {
Self {
format: ArchiveFormat::Tes3,
tes4_version: Tes4Version::Oblivion,
ba2_kind: Ba2ArchiveKind::Gnrl,
ba2_version: Ba2Version::Fallout4,
compress: false,
fsync: false,
follow_symlinks: false,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct AddOptions {
pub inputs: Vec<PathBuf>,
pub output: Option<PathBuf>,
pub fsync: bool,
pub follow_symlinks: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum Tes4Version {
Oblivion,
Fallout3,
Skyrim,
SkyrimSe,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum Ba2ArchiveKind {
Gnrl,
Dx10,
Gnmf,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum Ba2Version {
Fallout4,
Starfield,
Fallout4NextGen,
}
pub fn create_archive(output: &Path, input: &Path, options: &CreateOptions) -> Result<usize> {
reject_unsupported_create_options(options)?;
let input_entries = collect_input_entry_paths(input, options.follow_symlinks)?;
preflight_create_paths(input_entries.keys(), options)?;
write_entries(output, input_entries, options)
}
pub fn plan_create_archive(
output: &Path,
input: &Path,
options: &CreateOptions,
) -> Result<CreatePlan> {
reject_unsupported_create_options(options)?;
let input_entries = collect_input_entry_paths(input, options.follow_symlinks)?;
preflight_create_paths(input_entries.keys(), options)?;
let entries = input_entries
.iter()
.map(|(path, source)| plan_entry(ArchivePlanAction::Add, path, Some(source)))
.collect::<Result<Vec<_>>>()?;
Ok(CreatePlan {
operation: ArchivePlanOperation::Create,
format: options.format,
output: output.display().to_string(),
files: entries.len(),
entries,
})
}
fn reject_unsupported_create_options(options: &CreateOptions) -> Result<()> {
if options.format == ArchiveFormat::Tes3 && options.compress {
return Err(ArchiveError::Archive(
"compress is not valid with TES3 BSA archives".to_string(),
));
}
if options.format == ArchiveFormat::Ba2 && options.ba2_kind == Ba2ArchiveKind::Gnmf {
return Err(ArchiveError::Archive(
crate::rewrite_policy::GNMF_BLOCKER.to_string(),
));
}
Ok(())
}
pub fn add_to_archive(archive_path: &Path, options: &AddOptions) -> Result<usize> {
if options.inputs.is_empty() {
return Err(ArchiveError::Archive("no input files supplied".to_string()));
}
reject_explicit_same_archive_output(archive_path, options)?;
let output = add_output_path(archive_path, options);
let archive = crate::loaded::LoadedArchive::open(archive_path)?;
crate::rewrite_policy::ensure_rewritable(archive.as_ref())?;
let mut input_entries = BTreeMap::new();
for input in &options.inputs {
for (path, source) in collect_input_entry_paths(input, options.follow_symlinks)? {
insert_input_path(&mut input_entries, &path, source)?;
}
}
preflight_add_paths(input_entries.keys(), &archive)?;
let (temp, count) = write_entries_like_temp(
parent_directory(output),
input_entries,
&archive,
options.fsync,
)?;
drop(archive);
if options.output.is_none() {
keep_permissions(&temp, archive_path)?;
}
persist_temp_output(temp, output, options.fsync)?;
Ok(count)
}
pub fn plan_add_to_archive(archive_path: &Path, options: &AddOptions) -> Result<AddPlan> {
if options.inputs.is_empty() {
return Err(ArchiveError::Archive("no input files supplied".to_string()));
}
reject_explicit_same_archive_output(archive_path, options)?;
let output = add_output_path(archive_path, options);
let archive = crate::loaded::LoadedArchive::open(archive_path)?;
crate::rewrite_policy::ensure_rewritable(archive.as_ref())?;
let mut input_entries = BTreeMap::new();
for input in &options.inputs {
for (path, source) in collect_input_entry_paths(input, options.follow_symlinks)? {
insert_input_path(&mut input_entries, &path, source)?;
}
}
preflight_add_paths(input_entries.keys(), &archive)?;
let existing = existing_archive_paths(&archive)?;
let mut entries = Vec::new();
let mut added = 0;
let mut replaced = 0;
let mut preserved = 0;
for path in &existing {
if input_entries.contains_key(path) {
replaced += 1;
} else {
preserved += 1;
entries.push(plan_entry(ArchivePlanAction::Preserve, path, None)?);
}
}
for (path, source) in &input_entries {
let action = if existing.contains(path) {
ArchivePlanAction::Replace
} else {
added += 1;
ArchivePlanAction::Add
};
entries.push(plan_entry(action, path, Some(source))?);
}
Ok(AddPlan {
operation: ArchivePlanOperation::Add,
archive: archive_path.display().to_string(),
output: output.display().to_string(),
format: archive.format(),
files: entries.len(),
added,
replaced,
preserved,
entries,
})
}
fn add_output_path<'a>(archive_path: &'a Path, options: &'a AddOptions) -> &'a Path {
options.output.as_deref().unwrap_or(archive_path)
}
fn reject_explicit_same_archive_output(archive_path: &Path, options: &AddOptions) -> Result<()> {
let Some(output) = &options.output else {
return Ok(());
};
if comparable_path(archive_path)? == comparable_path(output)? {
return Err(ArchiveError::Archive(
"explicit output archive path must differ from input archive path; omit output to replace the input archive".to_string(),
));
}
Ok(())
}
fn comparable_path(path: &Path) -> Result<PathBuf> {
if path.exists() {
return Ok(path.canonicalize()?);
}
let parent = parent_directory(path).canonicalize()?;
Ok(path
.file_name()
.map_or(parent.clone(), |name| parent.join(name)))
}
fn write_entries(
output: &Path,
entries: BTreeMap<Vec<u8>, PathBuf>,
options: &CreateOptions,
) -> Result<usize> {
let count = entries.len();
with_temp_output(output, options.fsync, |file| {
write_entries_to_file(file, entries, options)
})?;
Ok(count)
}
fn write_entries_like_temp(
parent: &Path,
entries: BTreeMap<Vec<u8>, PathBuf>,
archive: &crate::loaded::LoadedArchive,
fsync: bool,
) -> Result<(tempfile::NamedTempFile, usize)> {
let mut count = 0;
let temp = write_temp_output(parent, fsync, |file| match archive.as_dream_archive() {
dream_archive::Archive::Tes3Bsa(archive) => {
count = write_tes3_like(file, entries, archive)?;
Ok(())
}
dream_archive::Archive::Tes4Bsa(archive) => {
count = write_tes4_like(file, entries, archive)?;
Ok(())
}
dream_archive::Archive::BA2(archive) => {
count = write_ba2_like(file, entries, archive)?;
Ok(())
}
})?;
Ok((temp, count))
}
fn existing_archive_paths(archive: &crate::loaded::LoadedArchive) -> Result<BTreeSet<Vec<u8>>> {
let mut existing = BTreeMap::new();
match archive.as_dream_archive() {
dream_archive::Archive::Tes3Bsa(archive) => {
for entry in archive.entries() {
let raw_path = entry.path().as_bytes();
insert_existing_archive_path(
&mut existing,
&normalize_archive_path_bytes(raw_path),
raw_path,
)?;
}
}
dream_archive::Archive::Tes4Bsa(archive) => {
for entry in archive.entries() {
let Some(path) = entry.path() else { continue };
let raw_path = path.as_bytes();
insert_existing_archive_path(
&mut existing,
&normalize_archive_path_bytes(raw_path),
raw_path,
)?;
}
}
dream_archive::Archive::BA2(archive) => {
for entry in archive.entries() {
if entry.name().is_empty() {
continue;
}
let raw_path = entry.name().as_bytes();
insert_existing_archive_path(
&mut existing,
&normalize_archive_path_bytes(raw_path),
raw_path,
)?;
}
}
}
Ok(existing.into_keys().collect())
}
fn plan_entry(
action: ArchivePlanAction,
path: &[u8],
source: Option<&PathBuf>,
) -> Result<ArchivePlanEntry> {
let size = source
.map(fs::metadata)
.transpose()?
.map(|metadata| metadata.len());
Ok(ArchivePlanEntry {
action,
source: source.map(|path| path.display().to_string()),
path: archive_path_bytes_to_display(path),
path_bytes_hex: archive_path_bytes_to_hex(path),
size,
})
}
fn write_entries_to_file(
file: &mut fs::File,
entries: BTreeMap<Vec<u8>, PathBuf>,
options: &CreateOptions,
) -> Result<()> {
match options.format {
ArchiveFormat::Tes3 => write_tes3(file, entries),
ArchiveFormat::Tes4 => write_tes4(file, entries, options.tes4_version, options.compress),
ArchiveFormat::Ba2 => write_ba2(
file,
entries,
options.ba2_kind,
options.ba2_version,
options.compress,
),
}
}
fn preflight_create_paths<'a>(
paths: impl IntoIterator<Item = &'a Vec<u8>>,
options: &CreateOptions,
) -> Result<()> {
if options.format == ArchiveFormat::Ba2 {
validate_ba2_paths(paths, options.ba2_kind)?;
}
Ok(())
}
fn preflight_add_paths<'a>(
paths: impl IntoIterator<Item = &'a Vec<u8>>,
archive: &crate::loaded::LoadedArchive,
) -> Result<()> {
if let dream_archive::Archive::BA2(archive) = archive.as_dream_archive() {
let kind = ba2_kind_from_payload_format(archive.info().format);
crate::rewrite_policy::ensure_ba2_payload_format_writable(archive.info().format)?;
validate_ba2_paths(paths, kind)?;
}
Ok(())
}
fn validate_ba2_paths<'a>(
paths: impl IntoIterator<Item = &'a Vec<u8>>,
kind: Ba2ArchiveKind,
) -> Result<()> {
let (extension, label) = match kind {
Ba2ArchiveKind::Gnrl => return Ok(()),
Ba2ArchiveKind::Dx10 => (
b"dds".as_slice(),
"DX10 BA2 archives can only contain .dds files",
),
Ba2ArchiveKind::Gnmf => (
b"gnf".as_slice(),
"GNMF BA2 archives can only contain .gnf files",
),
};
for path in paths {
if !has_extension(path, extension) {
return Err(ArchiveError::Archive(format!(
"{}: {}",
label,
archive_path_bytes_to_display(path)
)));
}
}
Ok(())
}
fn has_extension(path: &[u8], expected: &[u8]) -> bool {
dream_archive::dream_path::NormalizedPath::new(path)
.extension()
.is_some_and(|extension| extension == expected)
}
fn insert_existing_archive_path(
existing: &mut BTreeMap<Vec<u8>, Vec<u8>>,
path: &[u8],
raw_path: &[u8],
) -> Result<()> {
if let Some(previous_raw_path) = existing.get(path) {
return Err(ArchiveError::Archive(format!(
"archive contains duplicate normalized path: {} (first raw path hex: {}, duplicate raw path hex: {})",
archive_path_bytes_to_display(path),
archive_path_bytes_to_hex(previous_raw_path),
archive_path_bytes_to_hex(raw_path)
)));
}
existing.insert(path.to_vec(), raw_path.to_vec());
Ok(())
}
fn write_tes3(output: &mut fs::File, entries: BTreeMap<Vec<u8>, PathBuf>) -> Result<()> {
let mut builder = dream_archive::Tes3BsaBuilder::new();
for (path, source) in entries {
builder.add_file(&path, source).map_err(archive_error)?;
}
builder.write_seek(output).map_err(archive_error)
}
fn write_tes3_like(
output: &mut fs::File,
entries: BTreeMap<Vec<u8>, PathBuf>,
archive: &dream_archive::bsa::tes3::Archive,
) -> Result<usize> {
let input_count = entries.len();
let mut preserved = 0;
let mut builder = dream_archive::Tes3BsaBuilder::new();
let source_archive = Arc::new(archive.clone());
let mut existing_keys = BTreeMap::new();
for (id, entry) in archive.entries_with_ids() {
let raw_path = entry.path().as_bytes();
let key = normalize_archive_path_bytes(raw_path);
insert_existing_archive_path(&mut existing_keys, &key, raw_path)?;
if !entries.contains_key(&key) {
preserved += 1;
builder
.add_archive_entry(&key, Arc::clone(&source_archive), id)
.map_err(archive_error)?;
}
}
for (path, source) in entries {
builder.add_file(&path, source).map_err(archive_error)?;
}
builder.write_seek(output).map_err(archive_error)?;
Ok(preserved + input_count)
}
fn write_tes4(
output: &mut fs::File,
entries: BTreeMap<Vec<u8>, PathBuf>,
version: Tes4Version,
compress: bool,
) -> Result<()> {
let mut builder = dream_archive::Tes4BsaBuilder::new();
builder.set_version(match version {
Tes4Version::Oblivion => Tes4ArchiveVersion::v103,
Tes4Version::Fallout3 | Tes4Version::Skyrim => Tes4ArchiveVersion::v104,
Tes4Version::SkyrimSe => Tes4ArchiveVersion::v105,
});
if compress {
builder.set_compressed(true);
}
write_tes4_builder(output, entries, builder)
}
fn write_tes4_like(
output: &mut fs::File,
entries: BTreeMap<Vec<u8>, PathBuf>,
archive: &dream_archive::bsa::tes4::Archive,
) -> Result<usize> {
let input_count = entries.len();
let mut preserved = 0;
let info = archive.info();
let unsupported_flag_bits =
crate::rewrite_policy::tes4_unsupported_archive_flag_bits(info.archive_flags);
if unsupported_flag_bits != 0 {
return Err(ArchiveError::Archive(format!(
"TES4 archive uses header flag bits this tool cannot preserve (0x{unsupported_flag_bits:08x}); refusing to rewrite it lossy"
)));
}
let mut builder = dream_archive::Tes4BsaBuilder::new();
builder.set_version(info.version);
builder.set_archive_types(info.archive_types);
builder.set_compressed(
info.archive_flags
.contains(dream_archive::bsa::tes4::ArchiveFlags::COMPRESSED),
);
let has_directory_strings = info
.archive_flags
.contains(dream_archive::bsa::tes4::ArchiveFlags::DIRECTORY_STRINGS);
let has_file_strings = info
.archive_flags
.contains(dream_archive::bsa::tes4::ArchiveFlags::FILE_STRINGS);
let has_embedded_names = info
.archive_flags
.contains(dream_archive::bsa::tes4::ArchiveFlags::EMBEDDED_FILE_NAMES);
builder.set_name_mode(
match (
has_directory_strings && has_file_strings,
has_embedded_names,
) {
(true, true) => NameMode::StringsAndEmbedded,
(true, false) => NameMode::Strings,
(false, true) => NameMode::Embedded,
(false, false) => {
return Err(ArchiveError::Archive(
"TES4 hash-only archives do not have recoverable path names; refusing to rewrite them lossy".to_string(),
));
}
},
);
let source_archive = Arc::new(archive.clone());
let mut existing_keys = BTreeMap::new();
for (id, entry) in archive.entries_with_ids() {
let Some(path) = entry.path() else { continue };
let raw_path = path.as_bytes();
let key = normalize_archive_path_bytes(raw_path);
insert_existing_archive_path(&mut existing_keys, &key, raw_path)?;
if !entries.contains_key(&key) {
preserved += 1;
builder
.add_archive_entry(&key, Arc::clone(&source_archive), id)
.map_err(archive_error)?;
}
}
for (path, source) in entries {
builder.add_file(&path, source).map_err(archive_error)?;
}
builder.write_seek(output).map_err(archive_error)?;
Ok(preserved + input_count)
}
fn write_tes4_builder(
output: &mut fs::File,
entries: BTreeMap<Vec<u8>, PathBuf>,
mut builder: dream_archive::Tes4BsaBuilder,
) -> Result<()> {
for (path, source) in entries {
builder.add_file(&path, source).map_err(archive_error)?;
}
builder.write_seek(output).map_err(archive_error)
}
fn write_ba2(
output: &mut fs::File,
entries: BTreeMap<Vec<u8>, PathBuf>,
kind: Ba2ArchiveKind,
version: Ba2Version,
compress: bool,
) -> Result<()> {
let format = match kind {
Ba2ArchiveKind::Gnrl => PayloadFormat::GNRL,
Ba2ArchiveKind::Dx10 => PayloadFormat::DX10,
Ba2ArchiveKind::Gnmf => PayloadFormat::GNMF,
};
let version = match version {
Ba2Version::Fallout4 => Ba2ArchiveVersion::v1,
Ba2Version::Starfield => Ba2ArchiveVersion::v2,
Ba2Version::Fallout4NextGen => Ba2ArchiveVersion::v8,
};
write_ba2_with_format(output, entries, format, version, compress)
}
fn write_ba2_like(
output: &mut fs::File,
entries: BTreeMap<Vec<u8>, PathBuf>,
archive: &dream_archive::ba2::Archive,
) -> Result<usize> {
let input_count = entries.len();
let info = archive.info();
if info.format == PayloadFormat::DX10 {
return write_dx10_ba2_like(output, entries, archive, info.version);
}
let mut preserved = 0;
crate::rewrite_policy::ensure_ba2_payload_format_writable(info.format)?;
let mut builder = dream_archive::Ba2Builder::new();
builder.set_version(info.version);
builder.set_compression(ba2_rewrite_compression(archive));
let source_archive = Arc::new(archive.clone());
let mut existing_keys = BTreeMap::new();
for (id, entry) in archive.entries_with_ids() {
if entry.name().is_empty() {
continue;
}
let raw_path = entry.name().as_bytes();
let key = normalize_archive_path_bytes(raw_path);
insert_existing_archive_path(&mut existing_keys, &key, raw_path)?;
if !entries.contains_key(&key) {
preserved += 1;
let compression = if ba2_entry_is_compressed(entry) {
CompressionOverride::Compress
} else {
CompressionOverride::Store
};
builder
.add_archive_entry_with_compression(
&key,
Arc::clone(&source_archive),
id,
compression,
)
.map_err(archive_error)?;
}
}
for (path, source) in entries {
builder.add_file(&path, source).map_err(archive_error)?;
}
builder.write_seek(output).map_err(archive_error)?;
Ok(preserved + input_count)
}
fn ba2_rewrite_compression(archive: &dream_archive::ba2::Archive) -> Option<Ba2CompressionFormat> {
let format = archive.info().compression_format;
let compressed = archive.entries().iter().any(ba2_entry_is_compressed);
(compressed || format == Ba2CompressionFormat::LZ4).then_some(format)
}
fn ba2_entry_is_compressed(entry: &dream_archive::ba2::Entry) -> bool {
entry
.file()
.chunks()
.iter()
.any(dream_archive::ba2::Chunk::is_compressed)
}
fn write_ba2_with_format(
output: &mut fs::File,
entries: BTreeMap<Vec<u8>, PathBuf>,
format: PayloadFormat,
version: Ba2ArchiveVersion,
compress: bool,
) -> Result<()> {
validate_ba2_paths(entries.keys(), ba2_kind_from_payload_format(format))?;
if format == PayloadFormat::DX10 {
return write_dx10_ba2(output, entries, version, compress);
}
crate::rewrite_policy::ensure_ba2_payload_format_writable(format)?;
let mut builder = dream_archive::Ba2Builder::new();
builder.set_version(version);
if compress {
builder.set_compression(Some(Ba2CompressionFormat::Zip));
}
for (path, source) in entries {
builder.add_file(&path, source).map_err(archive_error)?;
}
builder.write_seek(output).map_err(archive_error)
}
fn write_dx10_ba2(
output: &mut fs::File,
entries: BTreeMap<Vec<u8>, PathBuf>,
version: Ba2ArchiveVersion,
compress: bool,
) -> Result<()> {
let mut builder = dream_archive::Ba2Dx10Builder::new();
builder.set_version(version);
if compress {
builder.set_compression(Some(Ba2CompressionFormat::Zip));
}
for (path, source) in entries {
builder.add_dds_file(&path, source).map_err(archive_error)?;
}
builder.write_seek(output).map_err(archive_error)
}
fn write_dx10_ba2_like(
output: &mut fs::File,
entries: BTreeMap<Vec<u8>, PathBuf>,
archive: &dream_archive::ba2::Archive,
version: Ba2ArchiveVersion,
) -> Result<usize> {
let input_count = entries.len();
let mut preserved = 0;
let mut builder = dream_archive::Ba2Dx10Builder::new();
builder.set_version(version);
builder.set_compression(ba2_rewrite_compression(archive));
let source_archive = Arc::new(archive.clone());
let mut existing_keys = BTreeMap::new();
for (id, entry) in archive.entries_with_ids() {
if entry.name().is_empty() {
continue;
}
let raw_path = entry.name().as_bytes();
let key = normalize_archive_path_bytes(raw_path);
insert_existing_archive_path(&mut existing_keys, &key, raw_path)?;
if !entries.contains_key(&key) {
preserved += 1;
builder
.add_archive_entry(&key, Arc::clone(&source_archive), id)
.map_err(archive_error)?;
}
}
for (path, source) in entries {
builder.add_dds_file(&path, source).map_err(archive_error)?;
}
builder.write_seek(output).map_err(archive_error)?;
Ok(preserved + input_count)
}
fn archive_error(err: impl std::fmt::Display) -> ArchiveError {
ArchiveError::Archive(err.to_string())
}
fn ba2_kind_from_payload_format(format: PayloadFormat) -> Ba2ArchiveKind {
match format {
PayloadFormat::GNRL => Ba2ArchiveKind::Gnrl,
PayloadFormat::DX10 => Ba2ArchiveKind::Dx10,
PayloadFormat::GNMF => Ba2ArchiveKind::Gnmf,
}
}
#[cfg(test)]
mod tests {
use std::time::{SystemTime, UNIX_EPOCH};
use super::*;
use crate::ArchiveTool;
fn unique_dir(name: &str) -> PathBuf {
std::env::temp_dir().join(format!(
"dream_archivetool-{name}-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
))
}
fn write_input_tree(dir: &Path) {
fs::create_dir_all(dir.join("textures")).unwrap();
fs::write(dir.join("textures/example.dds"), b"payload").unwrap();
}
fn push_u32(out: &mut Vec<u8>, value: u32) {
out.extend_from_slice(&value.to_le_bytes());
}
fn push_zeros(out: &mut Vec<u8>, count: usize) {
out.resize(out.len() + count, 0);
}
fn dx10_dds(payload: &[u8]) -> Vec<u8> {
const DDSD_CAPS: u32 = 0x0000_0001;
const DDSD_HEIGHT: u32 = 0x0000_0002;
const DDSD_WIDTH: u32 = 0x0000_0004;
const DDSD_PIXELFORMAT: u32 = 0x0000_1000;
const DDSD_MIPMAPCOUNT: u32 = 0x0002_0000;
const DDSD_LINEARSIZE: u32 = 0x0008_0000;
const DDPF_FOURCC: u32 = 0x0000_0004;
const DDSCAPS_TEXTURE: u32 = 0x0000_1000;
const DDS_DIMENSION_TEXTURE2D: u32 = 3;
const DXGI_FORMAT_BC7_UNORM: u32 = 98;
let mut bytes = Vec::new();
bytes.extend_from_slice(b"DDS ");
push_u32(&mut bytes, 124);
push_u32(
&mut bytes,
DDSD_CAPS
| DDSD_HEIGHT
| DDSD_WIDTH
| DDSD_PIXELFORMAT
| DDSD_MIPMAPCOUNT
| DDSD_LINEARSIZE,
);
push_u32(&mut bytes, 4);
push_u32(&mut bytes, 4);
push_u32(&mut bytes, payload.len().try_into().unwrap());
push_u32(&mut bytes, 0);
push_u32(&mut bytes, 1);
push_zeros(&mut bytes, 44);
push_u32(&mut bytes, 32);
push_u32(&mut bytes, DDPF_FOURCC);
push_u32(&mut bytes, u32::from_le_bytes(*b"DX10"));
push_zeros(&mut bytes, 20);
push_u32(&mut bytes, DDSCAPS_TEXTURE);
push_zeros(&mut bytes, 16);
push_u32(&mut bytes, DXGI_FORMAT_BC7_UNORM);
push_u32(&mut bytes, DDS_DIMENSION_TEXTURE2D);
push_u32(&mut bytes, 0);
push_u32(&mut bytes, 1);
push_u32(&mut bytes, 0);
bytes.extend_from_slice(payload);
bytes
}
#[test]
fn creates_tes3_archive() {
let dir = unique_dir("create-tes3");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
write_input_tree(&input);
let archive = dir.join("out.bsa");
let count = create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Tes3,
..Default::default()
},
)
.unwrap();
assert_eq!(count, 1);
assert_eq!(
ArchiveTool::read_entry(&archive, "textures/example.dds").unwrap(),
b"payload"
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn creates_tes4_archive() {
let dir = unique_dir("create-tes4");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
write_input_tree(&input);
let archive = dir.join("out.bsa");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Tes4,
..Default::default()
},
)
.unwrap();
assert_eq!(
ArchiveTool::read_entry(&archive, "textures/example.dds").unwrap(),
b"payload"
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn creates_compressed_tes4_archive() {
let dir = unique_dir("create-tes4-compressed");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("hello.txt"), b"hello hello hello hello").unwrap();
let archive = dir.join("out.bsa");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Tes4,
compress: true,
..Default::default()
},
)
.unwrap();
let created = dream_archive::bsa::tes4::Archive::open_path(&archive).unwrap();
assert!(
created
.info()
.archive_flags
.contains(dream_archive::bsa::tes4::ArchiveFlags::COMPRESSED)
);
assert_eq!(
ArchiveTool::read_entry(&archive, "hello.txt").unwrap(),
b"hello hello hello hello"
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn creates_ba2_gnrl_archive() {
let dir = unique_dir("create-ba2");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
write_input_tree(&input);
let archive = dir.join("out.ba2");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Ba2,
..Default::default()
},
)
.unwrap();
assert_eq!(
ArchiveTool::read_entry(&archive, "textures/example.dds").unwrap(),
b"payload"
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn creates_compressed_ba2_gnrl_archive() {
let dir = unique_dir("create-ba2-compressed");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
let payload = vec![b'a'; 1024];
fs::write(input.join("hello.txt"), &payload).unwrap();
let archive = dir.join("out.ba2");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Ba2,
compress: true,
..Default::default()
},
)
.unwrap();
let entries = ArchiveTool::list(&archive).unwrap();
assert_eq!(entries.len(), 1);
assert!(entries[0].compressed_size.is_some());
assert_eq!(
ArchiveTool::read_entry(&archive, "hello.txt").unwrap(),
payload
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn rejects_tes3_compression() {
let dir = unique_dir("create-tes3-compressed-invalid");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("hello.txt"), b"hello").unwrap();
let archive = dir.join("out.bsa");
let err = create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Tes3,
compress: true,
..Default::default()
},
)
.unwrap_err();
assert_eq!(
err.to_string(),
"archive error: compress is not valid with TES3 BSA archives"
);
assert!(!archive.exists());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn rejects_non_dds_dx10_inputs_without_clobbering_output() {
let dir = unique_dir("create-dx10-invalid");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("not-a-texture.txt"), b"payload").unwrap();
let archive = dir.join("out.ba2");
fs::write(&archive, b"existing").unwrap();
let err = create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Ba2,
ba2_kind: Ba2ArchiveKind::Dx10,
..Default::default()
},
)
.unwrap_err();
assert!(err.to_string().contains("DX10"));
assert_eq!(fs::read(&archive).unwrap(), b"existing");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn accepts_uppercase_dx10_extensions() {
let dir = unique_dir("create-dx10-uppercase");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("TEXTURE.DDS"), b"payload").unwrap();
let archive = dir.join("out.ba2");
let err = create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Ba2,
ba2_kind: Ba2ArchiveKind::Dx10,
..Default::default()
},
)
.unwrap_err();
assert!(!err.to_string().contains("can only contain .dds"));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn add_preserves_existing_dx10_entries() {
let dir = unique_dir("add-dx10-preserve");
let input = dir.join("input");
let textures = input.join("textures");
fs::create_dir_all(&textures).unwrap();
fs::write(textures.join("base.dds"), dx10_dds(&[0x11; 16])).unwrap();
fs::write(textures.join("kept.dds"), dx10_dds(&[0x22; 16])).unwrap();
let archive = dir.join("base.ba2");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Ba2,
ba2_kind: Ba2ArchiveKind::Dx10,
..Default::default()
},
)
.unwrap();
let added = dir.join("added.dds");
fs::write(&added, dx10_dds(&[0x33; 16])).unwrap();
let output = dir.join("updated.ba2");
let count = add_to_archive(
&archive,
&AddOptions {
inputs: vec![added],
output: Some(output.clone()),
fsync: false,
follow_symlinks: false,
},
)
.unwrap();
assert_eq!(count, 3);
let updated = dream_archive::ba2::Archive::open_path(&output).unwrap();
assert_eq!(updated.info().format, PayloadFormat::DX10);
assert!(
ArchiveTool::read_entry(&output, "textures/kept.dds")
.unwrap()
.ends_with(&[0x22; 16])
);
assert!(
ArchiveTool::read_entry(&output, "added.dds")
.unwrap()
.ends_with(&[0x33; 16])
);
fs::remove_dir_all(dir).unwrap();
}
fn compressed_entries(archive: &Path) -> BTreeMap<String, bool> {
ArchiveTool::list(archive)
.unwrap()
.into_iter()
.map(|entry| (entry.path, entry.compressed_size.is_some()))
.collect()
}
#[test]
fn add_keeps_each_ba2_entry_compressed_or_stored_and_compresses_new_ones() {
let dir = unique_dir("add-ba2-compression");
fs::create_dir_all(&dir).unwrap();
let archive = dir.join("base.ba2");
let mut builder = dream_archive::Ba2Builder::new();
builder.set_compression(Some(Ba2CompressionFormat::Zip));
builder
.add_bytes_with_compression(
b"packed.txt",
[b'a'; 1024],
dream_archive::CompressionOverride::Compress,
)
.unwrap();
builder
.add_bytes_with_compression(
b"stored.wav",
[b'w'; 1024],
dream_archive::CompressionOverride::Store,
)
.unwrap();
with_temp_output(&archive, false, |file| {
builder.write_seek(file).map_err(archive_error)
})
.unwrap();
let added = dir.join("added.txt");
fs::write(&added, [b'b'; 1024]).unwrap();
let output = dir.join("updated.ba2");
add_to_archive(
&archive,
&AddOptions {
inputs: vec![added],
output: Some(output.clone()),
..AddOptions::default()
},
)
.unwrap();
assert_eq!(
compressed_entries(&output),
BTreeMap::from([
("added.txt".to_string(), true),
("packed.txt".to_string(), true),
("stored.wav".to_string(), false),
])
);
assert_eq!(
ArchiveTool::read_entry(&output, "packed.txt").unwrap(),
[b'a'; 1024]
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn add_to_a_zlib_dx10_ba2_compresses_new_textures() {
let dir = unique_dir("add-dx10-compression");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("base.dds"), dx10_dds(&[0x11; 16])).unwrap();
let archive = dir.join("base.ba2");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Ba2,
ba2_kind: Ba2ArchiveKind::Dx10,
compress: true,
..Default::default()
},
)
.unwrap();
let added = dir.join("added.dds");
fs::write(&added, dx10_dds(&[0x33; 16])).unwrap();
let output = dir.join("updated.ba2");
add_to_archive(
&archive,
&AddOptions {
inputs: vec![added],
output: Some(output.clone()),
..AddOptions::default()
},
)
.unwrap();
assert_eq!(
compressed_entries(&output),
BTreeMap::from([
("added.dds".to_string(), true),
("base.dds".to_string(), true)
])
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn rejects_gnmf_creation_without_clobbering_output() {
let dir = unique_dir("create-gnmf-invalid");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("not-a-model.txt"), b"payload").unwrap();
let archive = dir.join("out.ba2");
fs::write(&archive, b"existing").unwrap();
let err = create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Ba2,
ba2_kind: Ba2ArchiveKind::Gnmf,
..Default::default()
},
)
.unwrap_err();
assert!(err.to_string().contains("GNMF"));
assert_eq!(fs::read(&archive).unwrap(), b"existing");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn rejects_gnmf_creation_before_extension_policy_matters() {
let dir = unique_dir("create-gnmf-uppercase");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("MODEL.GNF"), b"payload").unwrap();
let archive = dir.join("out.ba2");
let err = create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Ba2,
ba2_kind: Ba2ArchiveKind::Gnmf,
..Default::default()
},
)
.unwrap_err();
assert!(err.to_string().contains("GNMF"));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn create_ba2_can_write_starfield_version() {
let dir = unique_dir("create-ba2-starfield");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("base.txt"), b"base").unwrap();
let archive = dir.join("out.ba2");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Ba2,
ba2_version: Ba2Version::Starfield,
..Default::default()
},
)
.unwrap();
let archive = dream_archive::ba2::Archive::open_path(&archive).unwrap();
assert_eq!(archive.info().version, Ba2ArchiveVersion::v2);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn create_ba2_can_write_next_gen_version() {
let dir = unique_dir("create-ba2-next-gen");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("base.txt"), b"base").unwrap();
let archive = dir.join("out.ba2");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Ba2,
ba2_version: Ba2Version::Fallout4NextGen,
..Default::default()
},
)
.unwrap();
let archive = dream_archive::ba2::Archive::open_path(&archive).unwrap();
assert_eq!(archive.info().version, Ba2ArchiveVersion::v8);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn add_preserves_starfield_v3_ba2_version() {
let dir = unique_dir("preserve-v3");
let archive = dir.join("base.ba2");
fs::create_dir_all(&dir).unwrap();
let mut builder = dream_archive::Ba2Builder::new();
builder.set_version(Ba2ArchiveVersion::v3);
builder.add_bytes(b"base.txt", b"base").unwrap();
with_temp_output(&archive, false, |file| {
builder.write_seek(file).map_err(archive_error)
})
.unwrap();
let added = dir.join("added.txt");
fs::write(&added, b"added").unwrap();
let output = dir.join("updated.ba2");
add_to_archive(
&archive,
&AddOptions {
inputs: vec![added],
output: Some(output.clone()),
fsync: false,
follow_symlinks: false,
},
)
.unwrap();
let updated = dream_archive::ba2::Archive::open_path(&output).unwrap();
assert_eq!(updated.info().version, Ba2ArchiveVersion::v3);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn add_preserves_next_gen_v8_ba2_version() {
let dir = unique_dir("preserve-v8");
let archive = dir.join("base.ba2");
fs::create_dir_all(&dir).unwrap();
let mut builder = dream_archive::Ba2Builder::new();
builder.set_version(Ba2ArchiveVersion::v8);
builder.add_bytes(b"base.txt", b"base").unwrap();
with_temp_output(&archive, false, |file| {
builder.write_seek(file).map_err(archive_error)
})
.unwrap();
let added = dir.join("added.txt");
fs::write(&added, b"added").unwrap();
let output = dir.join("updated.ba2");
add_to_archive(
&archive,
&AddOptions {
inputs: vec![added],
output: Some(output.clone()),
fsync: false,
follow_symlinks: false,
},
)
.unwrap();
let updated = dream_archive::ba2::Archive::open_path(&output).unwrap();
assert_eq!(updated.info().version, Ba2ArchiveVersion::v8);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn add_without_output_replaces_source_archive() {
let dir = unique_dir("add");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("base.txt"), b"base").unwrap();
let archive = dir.join("base.bsa");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Tes3,
..Default::default()
},
)
.unwrap();
let added = dir.join("added.txt");
fs::write(&added, b"added").unwrap();
let count = add_to_archive(
&archive,
&AddOptions {
inputs: vec![added],
output: None,
fsync: false,
follow_symlinks: false,
},
)
.unwrap();
assert_eq!(count, 2);
assert_eq!(
ArchiveTool::read_entry(&archive, "base.txt").unwrap(),
b"base"
);
assert_eq!(
ArchiveTool::read_entry(&archive, "added.txt").unwrap(),
b"added"
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn add_plan_without_output_reports_source_archive() {
let dir = unique_dir("add-plan-default-output");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("base.txt"), b"base").unwrap();
let archive = dir.join("base.bsa");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Tes3,
..Default::default()
},
)
.unwrap();
let added = dir.join("added.txt");
fs::write(&added, b"added").unwrap();
let plan = plan_add_to_archive(
&archive,
&AddOptions {
inputs: vec![added],
output: None,
fsync: false,
follow_symlinks: false,
},
)
.unwrap();
assert_eq!(plan.output, archive.display().to_string());
assert_eq!(plan.added, 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn add_replaces_existing_archive_entries() {
let dir = unique_dir("add-replace");
let input = dir.join("input");
fs::create_dir_all(input.join("textures")).unwrap();
fs::write(input.join("textures/example.dds"), b"old").unwrap();
fs::write(input.join("keep.txt"), b"keep").unwrap();
let archive = dir.join("base.bsa");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Tes3,
..Default::default()
},
)
.unwrap();
let replacement = dir.join("replacement");
fs::create_dir_all(replacement.join("textures")).unwrap();
fs::write(replacement.join("textures/example.dds"), b"new").unwrap();
let output = dir.join("updated.bsa");
let count = add_to_archive(
&archive,
&AddOptions {
inputs: vec![replacement],
output: Some(output.clone()),
fsync: false,
follow_symlinks: false,
},
)
.unwrap();
assert_eq!(count, 2);
assert_eq!(
ArchiveTool::read_entry(&output, "textures/example.dds").unwrap(),
b"new"
);
assert_eq!(
ArchiveTool::read_entry(&output, "keep.txt").unwrap(),
b"keep"
);
assert_eq!(
ArchiveTool::read_entry(&archive, "textures/example.dds").unwrap(),
b"old"
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn rejects_duplicate_paths_after_normalization() {
let mut entries = BTreeMap::new();
insert_input_path(
&mut entries,
b"textures/example.dds",
PathBuf::from("textures/example.dds"),
)
.unwrap();
let err = insert_input_path(
&mut entries,
b"textures/example.dds",
PathBuf::from("textures/EXAMPLE.DDS"),
)
.unwrap_err();
assert!(err.to_string().contains("duplicate archive path"));
}
#[test]
fn add_rejects_duplicate_paths_across_inputs() {
let dir = unique_dir("add-duplicate-across-inputs");
fs::create_dir_all(&dir).unwrap();
let base_input = dir.join("base-input");
fs::create_dir_all(&base_input).unwrap();
fs::write(base_input.join("base.txt"), b"base").unwrap();
let archive = dir.join("base.bsa");
create_archive(
&archive,
&base_input,
&CreateOptions {
format: ArchiveFormat::Tes3,
..Default::default()
},
)
.unwrap();
let first = dir.join("first");
let second = dir.join("second");
fs::create_dir_all(first.join("textures")).unwrap();
fs::create_dir_all(second.join("textures")).unwrap();
fs::write(first.join("textures/example.dds"), b"first").unwrap();
fs::write(second.join("textures/EXAMPLE.DDS"), b"second").unwrap();
let err = add_to_archive(
&archive,
&AddOptions {
inputs: vec![first, second],
output: Some(dir.join("updated.bsa")),
fsync: false,
follow_symlinks: false,
},
)
.unwrap_err();
assert!(err.to_string().contains("duplicate archive path"));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn add_rejects_empty_tes4_hash_only_archive() {
let dir = unique_dir("add-hash-only");
fs::create_dir_all(&dir).unwrap();
let archive = dir.join("hash-only.bsa");
let mut builder = dream_archive::Tes4BsaBuilder::new();
builder.set_name_mode(NameMode::HashOnly);
builder.write_path(&archive).unwrap();
let added = dir.join("added.txt");
fs::write(&added, b"added").unwrap();
let err = add_to_archive(
&archive,
&AddOptions {
inputs: vec![added],
output: Some(dir.join("updated.bsa")),
fsync: false,
follow_symlinks: false,
},
)
.unwrap_err();
assert!(err.to_string().contains("hash-only"));
fs::remove_dir_all(dir).unwrap();
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn input_collection_preserves_non_utf8_archive_path_bytes() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let dir = unique_dir("non-utf8-path");
fs::create_dir_all(&dir).unwrap();
let file_name = OsString::from_vec(vec![b'F', b'O', b'O', 0xff, b'.', b'T', b'X', b'T']);
let file_path = dir.join(file_name);
fs::write(&file_path, b"payload").unwrap();
let entries = collect_input_entry_paths(&dir, false).unwrap();
assert!(entries.contains_key(b"foo\xff.txt".as_slice()));
fs::remove_dir_all(dir).unwrap();
}
#[cfg(unix)]
#[test]
fn input_collection_rejects_symlinks_by_default() {
use std::os::unix::fs::symlink;
let dir = unique_dir("symlink-reject");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(dir.join("outside.txt"), b"outside").unwrap();
symlink(dir.join("outside.txt"), input.join("linked.txt")).unwrap();
let err = collect_input_entry_paths(&input, false).unwrap_err();
assert!(matches!(err, ArchiveError::SymlinkInput(_)), "{err}");
assert!(err.to_string().contains("refusing to follow symlink"));
assert!(err.to_string().contains("set follow_symlinks"));
fs::remove_dir_all(dir).unwrap();
}
#[cfg(unix)]
#[test]
fn input_collection_can_follow_symlinks_explicitly() {
use std::os::unix::fs::symlink;
let dir = unique_dir("symlink-follow");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(dir.join("outside.txt"), b"outside").unwrap();
symlink(dir.join("outside.txt"), input.join("linked.txt")).unwrap();
let entries = collect_input_entry_paths(&input, true).unwrap();
assert!(entries.contains_key(b"linked.txt".as_slice()));
fs::remove_dir_all(dir).unwrap();
}
#[cfg(unix)]
fn mode(path: &Path) -> u32 {
use std::os::unix::fs::PermissionsExt;
fs::metadata(path).unwrap().permissions().mode() & 0o777
}
#[cfg(unix)]
#[test]
fn written_archives_get_the_default_mode_and_add_in_place_keeps_the_old_one() {
use std::os::unix::fs::PermissionsExt;
let dir = unique_dir("archive-modes");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("base.txt"), b"base").unwrap();
let reference = dir.join("reference");
fs::write(&reference, b"").unwrap();
let archive = dir.join("base.bsa");
create_archive(&archive, &input, &CreateOptions::default()).unwrap();
assert_eq!(mode(&archive), mode(&reference));
let added = dir.join("added.txt");
fs::write(&added, b"added").unwrap();
let output = dir.join("updated.bsa");
let options = AddOptions {
inputs: vec![added],
output: Some(output.clone()),
..AddOptions::default()
};
add_to_archive(&archive, &options).unwrap();
assert_eq!(mode(&output), mode(&reference));
fs::set_permissions(&archive, fs::Permissions::from_mode(0o640)).unwrap();
add_to_archive(
&archive,
&AddOptions {
output: None,
..options
},
)
.unwrap();
assert_eq!(mode(&archive), 0o640);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn add_rejects_output_matching_input_archive() {
let dir = unique_dir("add-same-output");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
fs::write(input.join("base.txt"), b"base").unwrap();
let archive = dir.join("base.bsa");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Tes3,
..Default::default()
},
)
.unwrap();
let added = dir.join("added.txt");
fs::write(&added, b"added").unwrap();
let err = add_to_archive(
&archive,
&AddOptions {
inputs: vec![added],
output: Some(archive.clone()),
fsync: false,
follow_symlinks: false,
},
)
.unwrap_err();
assert!(err.to_string().contains("must differ"));
fs::remove_dir_all(dir).unwrap();
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn created_non_utf8_archive_can_be_listed_extracted_and_rewritten() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let dir = unique_dir("non-utf8-roundtrip");
let input = dir.join("input");
fs::create_dir_all(&input).unwrap();
let file_name = OsString::from_vec(vec![b'F', b'O', b'O', 0xff, b'.', b'T', b'X', b'T']);
fs::write(input.join(&file_name), b"payload").unwrap();
let archive = dir.join("out.bsa");
create_archive(
&archive,
&input,
&CreateOptions {
format: ArchiveFormat::Tes3,
..Default::default()
},
)
.unwrap();
let entries = ArchiveTool::list(&archive).unwrap();
assert_eq!(entries.len(), 1);
let extract_dir = dir.join("extract");
crate::extract::extract_all(
&archive,
&crate::ExtractAllOptions {
output: Some(extract_dir.clone()),
..Default::default()
},
)
.unwrap();
let normalized_name =
OsString::from_vec(vec![b'f', b'o', b'o', 0xff, b'.', b't', b'x', b't']);
assert_eq!(
fs::read(extract_dir.join(normalized_name)).unwrap(),
b"payload"
);
let added = dir.join("added.txt");
fs::write(&added, b"added").unwrap();
let updated = dir.join("updated.bsa");
add_to_archive(
&archive,
&AddOptions {
inputs: vec![added],
output: Some(updated.clone()),
fsync: false,
follow_symlinks: false,
},
)
.unwrap();
assert_eq!(ArchiveTool::list(&updated).unwrap().len(), 2);
fs::remove_dir_all(dir).unwrap();
}
}