Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ forge9 --dict names.txt psin script.rpf 1 --structs
# the TOC's u32 name hash column, a column beside the records rather than a record field; some
# archives have no such column, or one shorter than their records.
forge9 --dict names.txt catalog common.rpf script.rpf
forge9 --dict names.txt catalog common.rpf --write-dict names.txt # accumulate confirmed candidates into a sorted, deduped dict
forge9 catalog common.rpf --json # array of {id, archive, path, hash, kind, stored, inflated, status, name, evidence, candidates}
```

Expand Down
94 changes: 92 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ enum Command {
archives: Vec<PathBuf>,
#[arg(long)]
json: bool,
/// Write confirmed candidates as `hexhash name` lines (deduped, sorted), merging into an existing file
#[arg(long, value_name = "PATH")]
write_dict: Option<PathBuf>,
},
/// Extract entries to a directory
Extract {
Expand Down Expand Up @@ -436,7 +439,7 @@ fn main() -> Result<()> {
Err(e) => { eprintln!("Error: {e:?}"); std::process::exit(2) }
},
Command::Harvest { archives } => cmd_harvest(&archives, &crypto, &dict),
Command::Catalog { archives, json } => cmd_catalog(&archives, &crypto, &dict, json),
Command::Catalog { archives, json, write_dict } => cmd_catalog(&archives, &crypto, &dict, json, write_dict.as_deref()),
Command::Extract { archive, output, select } => cmd_extract(&archive, &crypto, &output, select),
Command::Hexdump { archive, index, limit } => cmd_hexdump(&archive, &crypto, index, limit),
Command::Replace { archive, index, file, output } => cmd_replace(&archive, &crypto, index, &file, &output),
Expand Down Expand Up @@ -838,12 +841,49 @@ fn name_rows(rows: &mut [CatalogRow], archives: &[(String, rpf9::reader::Archive
Ok(())
}

fn cmd_catalog(paths: &[PathBuf], crypto: &rpf9::crypto::CryptoContext, dict: &rpf9::hashes::Dict, json: bool) -> Result<()> {
/// Confirmed `(hash, name)` pairs from `catalog` rows: unambiguous single-candidate joaat matches
/// and embedded resource labels whose name (or stem before `.#`) hashes to the row's hash.
/// Returns `(entries, skipped_ambiguous)`.
fn confirmed_catalog_names(rows: &[CatalogRow]) -> (Vec<(u32, String)>, usize) {
let mut out = std::collections::BTreeMap::new();
let mut ambiguous = std::collections::HashSet::new();
for r in rows {
let Some(h) = r.hash else { continue };
match (&r.name, r.evidence, r.candidates.as_slice()) {
(Some(labels), "embedded resource label", _) => {
for label in labels.split(", ") {
let stem = label.split_once(".#").map_or(label, |(s, _)| s);
if let Some(m) = [label, stem].into_iter().find(|s| rpf9::hashes::joaat(s) == h) {
out.entry(h).or_insert_with(|| m.to_string());
break;
}
}
}
(None, _, [(name, _)]) if rpf9::hashes::joaat(name) == h => {
out.entry(h).or_insert_with(|| name.clone());
}
(None, _, c) if c.len() > 1 => { ambiguous.insert(h); }
_ => {}
}
}
(out.into_iter().collect(), ambiguous.len())
}

fn cmd_catalog(paths: &[PathBuf], crypto: &rpf9::crypto::CryptoContext, dict: &rpf9::hashes::Dict, json: bool, write_dict: Option<&std::path::Path>) -> Result<()> {
let raws = paths.iter().map(|p| std::fs::read(p).with_context(|| format!("reading {}", p.display()))).collect::<Result<Vec<_>>>()?;
let archives = paths.iter().zip(&raws).map(|(p, r)| Ok((p.file_name().unwrap_or_default().to_string_lossy().into_owned(), rpf9::reader::Archive::open(r, crypto)?)))
.collect::<Result<Vec<_>>>()?;
let mut rows = catalog(&archives, crypto)?;
name_rows(&mut rows, &archives, crypto, dict)?;
if let Some(out_path) = write_dict {
let (entries, skipped) = confirmed_catalog_names(&rows);
let (added, total) = rpf9::hashes::write_dict(out_path, entries)?;
if skipped > 0 {
eprintln!("wrote {total} dict entries ({added} new, {skipped} ambiguous skipped) to {}", out_path.display());
} else {
eprintln!("wrote {total} dict entries ({added} new) to {}", out_path.display());
}
}
if json {
let records: Vec<_> = rows.iter().map(|r| serde_json::json!({
"id": r.id(), "archive": r.archive, "path": r.path, "hash": r.hash.map(|h| format!("{h:#010x}")),
Expand Down Expand Up @@ -2023,4 +2063,54 @@ mod tests {
assert!(rows[..5].iter().all(|r| r.hash.is_none() && r.status() == "unresolved"));
assert_eq!(rows[6].candidates, [("health_max".to_string(), "string in entry b.rpf:0".to_string())]);
}

#[test]
fn catalog_write_dict_accumulates_sorted_deduped_entries() {
let crypto = crypto();
let mut drawable = vec![0u8; 176];
for at in [8, 16, 80, 168] { drawable[at..at + 8].copy_from_slice(&(forge9::formats::resource::VIRTUAL_BASE + 176).to_le_bytes()); }
drawable.extend(b"prop_crate_01.#dr\0");

let dict_path = std::env::temp_dir().join(format!("forge9-catalog-dict-{}.txt", std::process::id()));
let _ = std::fs::remove_file(&dict_path);

// Run 1: archive a.rpf yields a single candidate ("health_max") and an embedded drawable label ("prop_crate_01").
let a = named_archive(&crypto, &[b"<x n=\"Health_Max\"/>".to_vec(), b"x".to_vec(), drawable, b"y".to_vec()],
&[0xde396fe2, joaat("health_max"), joaat("prop_crate_01"), joaat("no_such_name")]);
let archives_a = [("a.rpf".to_string(), Archive::open(&a, &crypto).unwrap())];
let mut rows_a = catalog(&archives_a, &crypto).unwrap();
name_rows(&mut rows_a, &archives_a, &crypto, &rpf9::hashes::Dict::load(None).unwrap()).unwrap();
// Also ensure an ambiguous row with 2 candidates is skipped rather than written.
rows_a.push(CatalogRow { archive: "a.rpf".into(), path: "99".into(), hash: Some(0x12345678), ext: "bin", stored: 1, inflated: 1,
name: None, evidence: "embedded resource label", candidates: vec![("first".into(), "ev".into()), ("second".into(), "ev".into())] });
let (entries_a, skipped) = confirmed_catalog_names(&rows_a);
assert_eq!(skipped, 1);
assert_eq!(rpf9::hashes::write_dict(&dict_path, entries_a).unwrap(), (2, 2));

// Run 2: reload the written dict and catalog b.rpf (contains an already-recovered hash + a new candidate).
let dict = rpf9::hashes::Dict::load(Some(&dict_path)).unwrap();
let b = named_archive(&crypto, &[b"<x n=\"spawn_point\"/>".to_vec(), b"x".to_vec(), b"y".to_vec()],
&[0, joaat("health_max"), joaat("spawn_point")]);
let archives_b = [("b.rpf".to_string(), Archive::open(&b, &crypto).unwrap())];
let mut rows_b = catalog(&archives_b, &crypto).unwrap();
name_rows(&mut rows_b, &archives_b, &crypto, &dict).unwrap();
assert_eq!((rows_b[1].status(), rows_b[1].name.as_deref(), rows_b[1].evidence), ("resolved", Some("health_max"), "dictionary"));
let (entries_b, skipped_b) = confirmed_catalog_names(&rows_b);
assert_eq!(skipped_b, 0);
assert_eq!(rpf9::hashes::write_dict(&dict_path, entries_b).unwrap(), (1, 3));

// Verify the accumulated file is deduplicated, sorted by hash, and reloads cleanly.
let text = std::fs::read_to_string(&dict_path).unwrap();
let mut expected = [
(joaat("health_max"), "health_max"),
(joaat("prop_crate_01"), "prop_crate_01"),
(joaat("spawn_point"), "spawn_point"),
];
expected.sort_by_key(|(h, _)| *h);
let want: String = expected.iter().map(|(h, n)| format!("{h:#010x} {n}\n")).collect();
assert_eq!(text, want);
let reloaded = rpf9::hashes::Dict::load(Some(&dict_path)).unwrap();
for (h, n) in expected { assert_eq!(reloaded.name(h), Some(n)); }
let _ = std::fs::remove_file(&dict_path);
}
}
46 changes: 45 additions & 1 deletion src/rpf9/hashes.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! joaat hash dictionary: embedded known names plus optional external file.

use anyhow::{Context, Result};
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use std::path::Path;

const KNOWN: &[(u32, &str)] = &[
Expand Down Expand Up @@ -81,6 +81,37 @@ fn parse_lines(text: &str) -> impl Iterator<Item = (u32, String)> + '_ {
})
}

/// Merges `entries` into `existing` (`hexhash name` lines), keeping existing names on conflict,
/// deduplicating by hash and sorting ascending by hash. Returns `(formatted, added, total)`.
pub fn merge_dict(existing: &str, entries: impl IntoIterator<Item = (u32, String)>) -> (String, usize, usize) {
let mut map: BTreeMap<u32, String> = parse_lines(existing).collect();
let mut added = 0;
for (hash, name) in entries {
let name = name.trim();
if name.is_empty() || name.contains(['\n', '\r']) { continue; }
map.entry(hash).or_insert_with(|| { added += 1; name.to_string() });
}
let mut out = String::new();
for (hash, name) in &map {
use std::fmt::Write;
let _ = writeln!(out, "{hash:#010x} {name}");
}
(out, added, map.len())
}

/// Merges `entries` into `path` (creating it if absent) as sorted, deduplicated `hexhash name`
/// lines. Returns `(added, total)`.
pub fn write_dict(path: &Path, entries: impl IntoIterator<Item = (u32, String)>) -> Result<(usize, usize)> {
let existing = match std::fs::read_to_string(path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(e).with_context(|| format!("reading dict {}", path.display())),
};
let (formatted, added, total) = merge_dict(&existing, entries);
std::fs::write(path, formatted).with_context(|| format!("writing dict {}", path.display()))?;
Ok((added, total))
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -97,4 +128,17 @@ mod tests {
assert_eq!(d.fmt(0xde396fe2), "0xde396fe2 (root_document)");
assert_eq!(d.fmt(0x12345678), "0x12345678");
}

#[test]
fn merge_dict_dedups_sorts_and_preserves_existing() {
let existing = "# saved\n0x00000020 kept_name\n";
let (text, added, total) = merge_dict(existing, [
(0x00000020, "override_attempt".to_string()),
(0x00000030, "later".to_string()),
(0x00000010, "earlier".to_string()),
(0x00000010, "duplicate".to_string()),
]);
assert_eq!((added, total), (2, 3));
assert_eq!(text, "0x00000010 earlier\n0x00000020 kept_name\n0x00000030 later\n");
}
}