use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use clap::{Args, Parser, Subcommand};
use one_saves::extension::{Civil, SHOWN_BYTES, SHOWN_CHARS};
use one_saves::{Bundle, Game, Name, Origin, Part, PartKind, Recorded, Source, TakenWith};
use one_saves_convert::{Format, Profile, card, detect, n64dd, raw};
mod n64;
mod state;
#[derive(Parser)]
#[command(name = "1saves", version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Convert(Box<Convert>),
Extract(Extract),
New(New),
Inspect(FileArg),
Verify(FileArg),
Hash(FileArg),
Profiles,
}
#[derive(Args)]
struct FileArg {
file: PathBuf,
}
#[derive(Args)]
struct Convert {
input: PathBuf,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(long, value_name = "NAME")]
from: Option<String>,
#[arg(long, value_name = "SLUG")]
system: Option<String>,
#[arg(long, value_name = "SLUG")]
role: Option<String>,
#[arg(long, value_name = "VERSION")]
app_version: Option<String>,
#[arg(long, value_name = "NAME")]
core: Option<String>,
#[arg(long, value_name = "VERSION")]
core_version: Option<String>,
#[arg(long, value_name = "NAME")]
platform: Option<String>,
#[arg(long, value_name = "VERSION")]
platform_version: Option<String>,
#[arg(long)]
description: Option<String>,
#[cfg(feature = "rom")]
#[arg(long, value_name = "FILE")]
rom: Option<PathBuf>,
#[cfg(feature = "dat")]
#[arg(long, value_name = "FILE")]
dat: Option<PathBuf>,
#[arg(long, value_name = "FILE")]
rtc_file: Option<PathBuf>,
#[arg(long, value_name = "EPOCH")]
rtc_captured_at: Option<i64>,
#[arg(long, value_name = "CHIP")]
n64_save: Option<String>,
#[arg(long, value_name = "ORDER")]
n64_order: Option<String>,
#[arg(long, value_name = "CODE")]
n64_game: Option<String>,
#[arg(long, value_name = "OFFSET", allow_hyphen_values = true, value_parser = utc_offset)]
utc_offset: Option<i32>,
#[arg(long)]
keep_rtc_inline: bool,
#[arg(long)]
force: bool,
}
#[derive(Args)]
struct Extract {
input: PathBuf,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(long, value_name = "NAME")]
to: Option<String>,
#[arg(long, value_name = "NAME")]
core: Option<String>,
#[arg(long, value_name = "ID")]
part: Option<u64>,
#[arg(long, value_name = "TARGET")]
n64: Option<n64::Target>,
#[arg(long, value_name = "FILE")]
onto: Option<PathBuf>,
#[arg(long, value_name = "FILE")]
rtc_file: Option<PathBuf>,
#[arg(long, value_name = "OFFSET", allow_hyphen_values = true, value_parser = utc_offset)]
utc_offset: Option<i32>,
#[cfg(feature = "rom")]
#[arg(long, value_name = "FILE")]
rom: Option<PathBuf>,
#[arg(long)]
force: bool,
}
fn utc_offset(text: &str) -> Result<i32, String> {
let seconds = if let Ok(seconds) = text.parse::<i64>() {
seconds
} else {
let (sign, rest) = match text.split_at_checked(1) {
Some(("+", rest)) => (1, rest),
Some(("-", rest)) => (-1, rest),
_ => return Err(format!("{text:?} is not an offset such as -08:00, +09:00 or -28800")),
};
let digits: String = rest.chars().filter(|c| *c != ':').collect();
let (hours, minutes) = match digits.len() {
2 => (digits.as_str(), "0"),
4 => digits.split_at(2),
_ => return Err(format!("{text:?} is not an offset such as -08:00, +09:00 or -28800")),
};
let parse = |part: &str| part.parse::<i64>().map_err(|_| format!("{text:?} is not an offset"));
let (hours, minutes) = (parse(hours)?, parse(minutes)?);
if minutes >= 60 {
return Err(format!("{text:?} has {minutes} minutes"));
}
sign * (hours * 3600 + minutes * 60)
};
if !one_saves::Source::UTC_OFFSETS.contains(&seconds) {
return Err(format!("{text:?} is outside -12:00 to +14:00, where every zone is"));
}
i32::try_from(seconds).map_err(|e| e.to_string())
}
#[derive(Args)]
struct New {
kind: String,
output: PathBuf,
#[arg(long)]
size: Option<String>,
#[arg(long)]
shift_jis: bool,
#[arg(long)]
layout: Option<String>,
#[arg(long)]
force: bool,
}
fn main() -> ExitCode {
let cli = Cli::parse();
match run(cli) {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprint!("{}", report(&*error));
ExitCode::FAILURE
}
}
}
fn report(error: &dyn std::error::Error) -> String {
let mut out = format!("1saves: {}\n", printable(&error.to_string()));
let mut source = error.source();
while let Some(inner) = source {
let _ = writeln!(out, " caused by: {}", printable(&inner.to_string()));
source = inner.source();
}
out
}
type Fallible = Result<(), Box<dyn std::error::Error>>;
fn run(cli: Cli) -> Fallible {
match cli.command {
Command::Convert(args) => convert(*args),
Command::Extract(args) => extract(args),
Command::New(args) => new_card(&args),
Command::Inspect(args) => inspect(&args.file),
Command::Verify(args) => verify(&args.file),
Command::Hash(args) => hash(&args.file),
Command::Profiles => {
profiles();
Ok(())
}
}
}
fn extension_of(path: &Path) -> String {
path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase()
}
fn write_out(path: &Path, bytes: &[u8], force: bool) -> Fallible {
if !force {
return create_new(path, bytes).map_err(|e| match e.kind() {
std::io::ErrorKind::AlreadyExists => format!(
"{} already exists; pass --force to overwrite",
printable(&path.display().to_string())
)
.into(),
_ => e.into(),
});
}
let name = path.file_name().ok_or_else(|| format!("{} names no file", path.display()))?;
let mut temporary = std::ffi::OsString::from(".");
temporary.push(name);
temporary.push(format!(".{}.1saves-partial", std::process::id()));
let temporary = path.with_file_name(temporary);
create_new(&temporary, bytes)?;
std::fs::rename(&temporary, path).map_err(|e| {
let _ = std::fs::remove_file(&temporary);
e.into()
})
}
fn create_new(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(path)?;
file.write_all(bytes).and_then(|()| file.sync_all()).inspect_err(|_| {
let _ = std::fs::remove_file(path);
})
}
fn read_beside(path: &Path, limit: u64) -> Result<Option<Vec<u8>>, String> {
use std::io::Read as _;
let shown = || printable(&path.display().to_string());
let file = match open_beside(path) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) if is_a_link_refused(&e) => return Err(format!("{} is not a regular file", shown())),
Err(e) => return Err(format!("{} cannot be read: {e}", shown())),
};
let metadata = file.metadata().map_err(|e| format!("{} cannot be read: {e}", shown()))?;
if !metadata.file_type().is_file() {
return Err(format!("{} is not a regular file", shown()));
}
if metadata.len() > limit {
return Err(format!("{} is {} bytes, more than the {limit} it could be", shown(), metadata.len()));
}
let mut bytes = Vec::new();
file.take(limit + 1).read_to_end(&mut bytes).map_err(|e| format!("{} cannot be read: {e}", shown()))?;
if bytes.len() as u64 > limit {
return Err(format!("{} grew past the {limit} bytes it could be while it was read", shown()));
}
Ok(Some(bytes))
}
#[cfg(unix)]
fn open_beside(path: &Path) -> std::io::Result<std::fs::File> {
use std::os::unix::fs::OpenOptionsExt as _;
std::fs::OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(path)
}
#[cfg(windows)]
fn open_beside(path: &Path) -> std::io::Result<std::fs::File> {
use std::os::windows::fs::OpenOptionsExt as _;
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
std::fs::OpenOptions::new()
.read(true)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)
}
#[cfg(not(any(unix, windows)))]
fn open_beside(path: &Path) -> std::io::Result<std::fs::File> {
std::fs::File::open(path)
}
#[cfg(unix)]
fn is_a_link_refused(error: &std::io::Error) -> bool {
error.raw_os_error() == Some(libc::ELOOP)
}
#[cfg(not(unix))]
fn is_a_link_refused(_: &std::io::Error) -> bool {
false
}
#[cfg(feature = "archive")]
fn unwrap_archive(
input: &std::path::Path,
bytes: Vec<u8>,
) -> Result<(Vec<u8>, String), Box<dyn std::error::Error>> {
if !one_saves_convert::archive::is_archive(&bytes) {
return Ok((bytes, extension_of(input)));
}
let unpacked = one_saves_convert::archive::unpack(&bytes)?;
if unpacked.assembled {
eprintln!("{}: built a card from {}", input.display(), printable(&unpacked.source));
}
Ok((unpacked.bytes, unpacked.extension))
}
type Sidecar = (std::path::PathBuf, Vec<u8>, Option<i64>);
const MAX_SIDECAR_CLOCK: u64 = 64 << 10;
fn sidecar_clock(
args: &Convert,
source: Option<&Source>,
) -> Result<Option<Sidecar>, Box<dyn std::error::Error>> {
let found = if let Some(path) = &args.rtc_file {
Some((path.clone(), std::fs::read(path)?))
} else {
let beside = args.input.with_extension("rtc");
read_beside(&beside, MAX_SIDECAR_CLOCK)
.map_err(|why| format!("{why}, so it is not read as the save's clock; name it with --rtc-file"))?
.map(|bytes| (beside, bytes))
};
let Some((path, bytes)) = found else {
let footer_origin =
one_saves_convert::rtc::huc3_layout_of(source) == Some(one_saves_convert::rtc::Huc3Layout::Vbam);
if args.rtc_captured_at.is_some() && !footer_origin {
return Err("--rtc-captured-at was given, but there is no sidecar clock to apply it to".into());
}
return Ok(None);
};
let record = one_saves_convert::rtc::sidecar_record_of(source);
if !one_saves_convert::rtc::sidecar_takes_instant(record, bytes.len()) {
if args.rtc_captured_at.is_some() {
return Err(format!(
"--rtc-captured-at was given, but {} records its own instant",
path.display()
)
.into());
}
return Ok(Some((path, bytes, None)));
}
let captured_at = if let Some(stated) = args.rtc_captured_at {
stated
} else {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| format!("the system clock is before 1970: {e}"))?
.as_secs();
i64::try_from(now)?
};
Ok(Some((path, bytes, Some(captured_at))))
}
fn convert(args: Convert) -> Fallible {
#[cfg(feature = "archive")]
let (bytes, extension) = unwrap_archive(&args.input, std::fs::read(&args.input)?)?;
#[cfg(not(feature = "archive"))]
let (bytes, extension) = (std::fs::read(&args.input)?, extension_of(&args.input));
if let Some(kind) = state::kind_of(&args.input, &bytes) {
return state::convert(&args, kind, &bytes);
}
let profile = args.from.as_deref().and_then(one_saves_convert::profile);
let format = match args.from.as_deref().and_then(Format::from_name) {
Some(format) => format,
None => detect::detect(&bytes, &extension)?,
};
if format == Format::Bundle {
return Err("this file is already a bundle".into());
}
#[cfg(feature = "rom")]
let Identified { mut game, system: rom_system, clock: rom_clock, n64_save: rom_n64_save, memory } =
identify(&args)?;
#[cfg(not(feature = "rom"))]
let Identified { mut game, system: rom_system, clock: rom_clock, n64_save: rom_n64_save, memory } =
Identified::default();
let source = source_of(&args, profile.as_ref())?;
let sidecar = sidecar_clock(&args, source.as_ref())?;
let sidecar_path = sidecar.as_ref().map(|(path, _, at)| (path.clone(), at.is_some()));
let sidecar = sidecar.map(|(_, bytes, at)| (bytes, at.unwrap_or_default()));
let system = system_of(&args, rom_system, profile.as_ref(), source.as_ref(), &extension, bytes.len());
let mut label = format.label().to_owned();
let mut bundle = if n64::is_n64(system.as_deref(), &extension, &bytes) {
let (bundle, read_as) = n64::convert(&args, &bytes, &extension, source, game.clone(), rom_n64_save)?;
label = read_as;
bundle
} else if format == Format::Raw {
let options = raw::RawOptions {
layout: profile.as_ref().and_then(|profile| profile.layout_in(system.as_deref()?)),
system,
role: args.role.clone(),
source,
game: game.clone(),
description: args.description.clone(),
split_rtc: !args.keep_rtc_inline,
rtc_sidecar: sidecar,
clock_chip: rom_clock.map(ToOwned::to_owned),
captured_at: args.rtc_captured_at,
memory,
..raw::RawOptions::default()
};
read_flat(&args.input, &bytes, options)?
} else {
read_card(&args, format, &bytes, &extension, system.as_deref(), source)?
};
if bundle.header.card.is_some()
&& let Some(game) = game.take()
{
bundle.header.game = Some(game);
}
if let Some(code) = args.n64_game.as_deref() {
(bundle, label) = n64::cut(&bundle, &label, code)?;
}
if let Some(description) = args.description {
bundle.header.description = Some(description);
}
let output = args.output.unwrap_or_else(|| args.input.with_extension(one_saves::EXTENSION));
let encoded = bundle.to_vec()?;
write_out(&output, &encoded, args.force)?;
report_clock(sidecar_path.as_ref(), args.rtc_captured_at.is_some(), &bundle);
if has_clock(&bundle) && one_saves_convert::rtc::scale_of(&bundle).is_none() {
println!(
"note: this clock was stamped in the MiSTer's local time, and nothing said how far that is from"
);
println!(
" UTC; pass --utc-offset (-08:00 for Pacific) so it reaches other emulators at the right hour"
);
}
let backup_ram = raw::is_segacd_bram(&bytes)
&& bundle.header.system.as_ref().is_some_and(|system| system.as_str() == "sega-cd");
if args.role.is_none() && backup_ram {
eprintln!("note: a Sega CD carries internal backup RAM and a Backup RAM Cart at once; pass");
eprintln!(" --role internal or --role ram-cart to say which socket this came out of");
}
let saves = bundle.parts.iter().filter(|p| p.kind == PartKind::Bundle).count();
let what = if *bundle.shape() == one_saves::Shape::Device {
format!("{} component(s)", bundle.parts.len())
} else if saves > 0 {
format!("{saves} save(s)")
} else {
format!("{} part(s)", bundle.parts.len())
};
println!(
"{} -> {} ({}, {what}, {} bytes)",
args.input.display(),
output.display(),
match () {
() if backup_ram => "Sega CD backup RAM",
() if n64dd::is_disk_save(&bundle) => "64DD disk save",
() if n64dd::is_drive(&bundle) => "64DD disk save and the drive's clock",
() => label.as_str(),
},
encoded.len()
);
Ok(())
}
fn read_flat(
input: &Path,
bytes: &[u8],
mut options: raw::RawOptions,
) -> Result<Bundle, Box<dyn std::error::Error>> {
if !n64dd::is_image(bytes) && options.system.as_deref() != Some(n64dd::SYSTEM) {
return Ok(raw::wrap(bytes, &options)?);
}
if options.rtc_sidecar.is_none() {
let beside = input.with_file_name(one_saves_convert::console_clock::ARES_N64DD_RTC);
if let Some(clock) = read_beside(&beside, MAX_SIDECAR_CLOCK)? {
println!("read {} beside it", beside.display());
options.rtc_sidecar = Some((clock, 0));
}
}
Ok(n64dd::read(bytes, &options)?)
}
fn read_card(
args: &Convert,
format: Format,
bytes: &[u8],
extension: &str,
system: Option<&str>,
source: Option<Source>,
) -> Result<Bundle, Box<dyn std::error::Error>> {
let options = card::CardOptions {
role: args.role.as_deref().map(|role| slug_flag("--role", role)).transpose()?,
system: system.map(|system| slug_flag("--system", system)).transpose()?,
source,
};
match saturn_device(args, format, bytes, extension, &options)? {
Some(device) => Ok(device),
None => Ok(card::read(format, bytes, &options)?),
}
}
#[cfg(feature = "saturn")]
const MAX_SATURN_CART: u64 = 8 << 20;
#[cfg(feature = "saturn")]
const MAX_SMPC: u64 = 64 << 10;
#[cfg(feature = "saturn")]
fn saturn_device(
args: &Convert,
format: Format,
bytes: &[u8],
extension: &str,
options: &card::CardOptions,
) -> Result<Option<Bundle>, Box<dyn std::error::Error>> {
use one_saves_convert::card::saturn;
if format != Format::SaturnBup || extension != extension_of(&args.input) || !saturn::is_internal(bytes) {
return Ok(None);
}
let beside = |extension: &str, limit: u64| -> Result<Option<(PathBuf, Vec<u8>)>, String> {
let path = args.input.with_extension(extension);
Ok(read_beside(&path, limit)?.map(|bytes| (path, bytes)))
};
let cart = beside(saturn::CART_EXTENSION, MAX_SATURN_CART)?;
let smpc = beside(saturn::SMPC_EXTENSION, MAX_SMPC)?;
if cart.is_none() && smpc.is_none() {
return Ok(None);
}
for (path, _) in cart.iter().chain(&smpc) {
println!("read {} beside it", path.display());
}
let files = saturn::DeviceFiles {
internal: bytes.to_vec(),
cart: cart.map(|(_, bytes)| bytes),
smpc: smpc.map(|(_, bytes)| bytes),
};
Ok(Some(saturn::read_device(&files, options)?))
}
#[cfg(not(feature = "saturn"))]
#[allow(clippy::unnecessary_wraps)]
fn saturn_device(
_: &Convert,
_: Format,
_: &[u8],
_: &str,
_: &card::CardOptions,
) -> Result<Option<Bundle>, Box<dyn std::error::Error>> {
Ok(None)
}
fn extract_apart(args: &Extract, bundle: &Bundle) -> Option<Fallible> {
#[cfg(feature = "saturn")]
if one_saves_convert::card::saturn::is_device(bundle)
&& args.to.as_deref().is_none_or(|to| Format::from_name(to) == Some(Format::SaturnBup))
{
return Some(extract_saturn(args, bundle));
}
if n64dd::is_drive(bundle) {
return Some(extract_drive(args, bundle));
}
let onto = args.onto.as_deref().filter(|_| n64dd::is_disk_save(bundle))?;
Some(extract_disk_copy(args, bundle, onto))
}
fn extract_drive(args: &Extract, bundle: &Bundle) -> Fallible {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| i64::try_from(since.as_secs()).unwrap_or(i64::MAX));
let (save, clock) = n64dd::split_drive(bundle, now)?;
let (output, bytes, what) = match args.onto.as_deref() {
Some(onto) => {
let output = args.output.clone().unwrap_or_else(|| args.input.with_extension("ndr"));
let copy = disk_copy(&save, onto, &output)?;
(output, copy, "64DD disk holding the save")
}
None => (
args.output.clone().unwrap_or_else(|| args.input.with_extension(n64dd::EXTENSION)),
save.parts.first().map(|part| part.payload.clone()).unwrap_or_default(),
"64DD disk save",
),
};
write_out(&output, &bytes, args.force)?;
println!("{} -> {} ({what}, {} bytes)", args.input.display(), output.display(), bytes.len());
if let Some(clock) = clock {
let path = output.with_file_name(one_saves_convert::console_clock::ARES_N64DD_RTC);
write_out(&path, &clock, args.force)?;
println!("clock -> {} ({} bytes)", path.display(), clock.len());
}
Ok(())
}
fn extract_disk_copy(args: &Extract, bundle: &Bundle, onto: &Path) -> Fallible {
let output = args.output.clone().unwrap_or_else(|| args.input.with_extension("ndr"));
let copy = disk_copy(bundle, onto, &output)?;
write_out(&output, ©, args.force)?;
println!(
"{} -> {} (64DD disk holding the save, {} bytes)",
args.input.display(),
output.display(),
copy.len()
);
Ok(())
}
fn disk_copy(save: &Bundle, onto: &Path, output: &Path) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let image = std::fs::read(onto)?;
Ok(if extension_of(output) == n64dd::ARES_DISK_EXTENSION {
n64dd::write_ares_disk(save, &image)?
} else {
n64dd::write_image(save, &image)?
})
}
#[cfg(feature = "saturn")]
fn extract_saturn(args: &Extract, bundle: &Bundle) -> Fallible {
use one_saves_convert::card::saturn;
if args.onto.is_some() {
return Err("--onto is for an N64 save, with --n64, or a Controller Pak".into());
}
let files = saturn::write_device(bundle)?;
let output =
args.output.clone().unwrap_or_else(|| args.input.with_extension(Format::SaturnBup.extension()));
let cart = files.cart.map(|cart| (output.with_extension(saturn::CART_EXTENSION), cart));
let smpc = files.smpc.map(|smpc| (output.with_extension(saturn::SMPC_EXTENSION), smpc));
write_out(&output, &files.internal, args.force)?;
println!(
"{} -> {} (Saturn internal memory, {} bytes)",
args.input.display(),
output.display(),
files.internal.len()
);
for (what, (path, bytes)) in
[("cart", cart), ("clock", smpc)].into_iter().filter_map(|(what, file)| Some((what, file?)))
{
write_out(&path, &bytes, args.force)?;
println!("{what} -> {} ({} bytes)", path.display(), bytes.len());
}
Ok(())
}
fn report_clock(sidecar: Option<&(PathBuf, bool)>, instant_given: bool, bundle: &Bundle) {
if let Some((path, _)) = sidecar
&& !has_clock(bundle)
{
println!(
"note: {} holds no clock for this cartridge, since what wrote it keeps none of its chip there",
path.display()
);
} else if let Some((path, needed_instant)) = sidecar {
let how = if !needed_instant {
"the instant it records"
} else if instant_given {
"the instant given"
} else {
"the time it was read"
};
println!("read the clock from {}, using {how}", path.display());
} else if one_saves_convert::rtc::footer_of(bundle).is_some() {
println!("split a real-time-clock footer off the save, so its bytes hash the same over time");
}
}
fn system_of(
args: &Convert,
rom_system: Option<&str>,
profile: Option<&Profile>,
source: Option<&Source>,
extension: &str,
len: usize,
) -> Option<String> {
let core_system = source
.and_then(|source| source.core.as_ref())
.and_then(|core| one_saves_registry::core(core.as_str()))
.and_then(|core| match core.systems {
[only] => Some(*only),
_ => None,
});
args.system
.clone()
.or_else(|| rom_system.map(ToOwned::to_owned))
.or_else(|| profile.and_then(Profile::only_system).map(ToOwned::to_owned))
.or_else(|| core_system.map(ToOwned::to_owned))
.or_else(|| n64::system_of_extension(extension).map(ToOwned::to_owned))
.or_else(|| {
(extension == n64dd::EXTENSION && n64dd::disk_type(len).is_some())
.then(|| n64dd::SYSTEM.to_owned())
})
}
fn slug_flag(flag: &str, text: &str) -> Result<one_saves::Slug, String> {
one_saves::Slug::parse(text).map_err(|e| format!("{flag} {text:?} is not a slug: {e}"))
}
fn source_of(
args: &Convert,
profile: Option<&Profile>,
) -> Result<Option<Source>, Box<dyn std::error::Error>> {
let mut source = profile.map(Profile::source).unwrap_or_default();
if let Some(text) = &args.core {
let core =
listed_name(text, "--core", |name| one_saves_registry::core_by_any_name(name).map(|c| c.slug))?;
if let Some(named) = &source.core
&& named != &core
{
return Err(format!("--from names the core {named}, and --core says {core}").into());
}
let app = source.app.as_ref().and_then(|app| one_saves_registry::app(app.as_str()));
if let Some(app) = app
&& let Some(listed) = one_saves_registry::core(core.as_str())
&& !app.runs(listed)
{
return Err(format!(
"{} does not run {}, so --core {text} cannot be right",
app.name, listed.name
)
.into());
}
source.core = Some(core);
}
if let Some(text) = &args.platform {
let platform = listed_name(text, "--platform", |name| {
one_saves_registry::platform_by_any_name(name).map(|p| p.slug)
})?;
source.platform = Some(platform);
}
for (flag, version, named, what) in [
("--app-version", &args.app_version, source.app.is_some(), "an app"),
("--core-version", &args.core_version, source.core.is_some(), "a core"),
("--platform-version", &args.platform_version, source.platform.is_some(), "a platform"),
] {
if version.is_some() && !named {
let hint = if flag == "--app-version" && source.core.is_some() {
"; --from names a core here, so its version is --core-version"
} else {
""
};
return Err(format!(
"{flag} was given, but nothing names {what} for it to be the version of{hint}"
)
.into());
}
}
source.app_version.clone_from(&args.app_version);
source.core_version.clone_from(&args.core_version);
source.platform_version.clone_from(&args.platform_version);
if let Some(offset) = args.utc_offset {
let core = source.core.as_ref().and_then(|core| one_saves_registry::core(core.as_str()));
match core {
Some(core) if one_saves_convert::rtc::stamps_local_time(core) => source.utc_offset = Some(offset),
Some(core) => {
return Err(format!(
"{} stamps its clock in UTC, so --utc-offset has nothing to say about it",
core.name
)
.into());
}
None => {
return Err(
"--utc-offset needs --from or --core to name the core that stamped the clock".into()
);
}
}
}
Ok((!source.is_empty()).then_some(source))
}
fn listed_name(
text: &str,
flag: &str,
lookup: impl Fn(&str) -> Option<&'static str>,
) -> Result<Name, String> {
if let Some(slug) = lookup(text) {
return Name::parse(slug).map_err(|e| format!("the registry slug {slug:?} is malformed: {e}"));
}
match Name::parse(text) {
Ok(name @ Name::ReverseDns(_)) => Ok(name),
Ok(Name::Slug(_)) => Err(format!(
"{flag} {text:?} is not one the registry lists; an unlisted one is written as its owner's \
reverse-DNS name"
)),
Err(e) => Err(format!("{flag} {text:?} is neither listed nor a well-formed name: {e}")),
}
}
#[derive(Default)]
struct Identified {
game: Option<one_saves::Game>,
system: Option<&'static str>,
clock: Option<&'static str>,
n64_save: Option<one_saves::extension::N64Save>,
memory: Option<one_saves_convert::layout::SaveMemory>,
}
#[cfg(feature = "rom")]
fn identify(args: &Convert) -> Result<Identified, Box<dyn std::error::Error>> {
let Some(rom_path) = args.rom.as_deref() else {
return Ok(Identified::default());
};
let bytes = std::fs::read(rom_path)?;
let filename = rom_path.file_name().and_then(|n| n.to_str());
#[cfg_attr(not(feature = "dat"), allow(unused_mut))]
let mut game = one_saves_convert::rom::game_from_rom(&bytes, filename);
let info = one_saves_convert::rom::identify(&bytes).unwrap_or_default();
#[cfg(feature = "dat")]
if let Some(dat) = args.dat.as_deref() {
let catalog = one_saves_convert::dat::Catalog::open(dat)?;
if catalog.enrich(&mut game) {
println!("identified as {:?}", game.title.as_deref().unwrap_or_default());
} else {
eprintln!("note: this ROM is not in {}", dat.display());
}
}
Ok(Identified {
game: Some(game),
system: info.system,
clock: info.clock,
n64_save: info.n64_save,
memory: info.memory,
})
}
fn extract(args: Extract) -> Fallible {
let bytes = std::fs::read(&args.input)?;
let bundle = Bundle::from_slice(&bytes)?;
if let Some(id) = args.part {
let payload = raw::unwrap_part(&bundle, id)?;
let output = args.output.unwrap_or_else(|| args.input.with_extension(format!("part{id}.bin")));
write_out(&output, &payload, args.force)?;
println!("part {id} -> {} ({} bytes)", output.display(), payload.len());
return Ok(());
}
if matches!(bundle.shape(), one_saves::Shape::State | one_saves::Shape::Screenshot) {
return state::extract(&args, &bundle);
}
if args.n64.is_none()
&& let Some(done) = extract_apart(&args, &bundle)
{
return done;
}
if let Some(target) = args.n64 {
if !n64::is_n64_bundle(&bundle) {
return Err("--n64 writes an N64 save, and this bundle is not one".into());
}
let base = args.output.unwrap_or_else(|| args.input.with_extension(""));
return n64::extract(&bundle, target, &base, args.onto.as_deref(), args.force);
}
if n64::is_n64_bundle(&bundle) && args.to.is_none() {
return Err("an N64 save is written differently for each emulator; pass --n64 retroarch, \
mupen64plus, project64 or everdrive"
.into());
}
let card_format = card::card_format_of(&bundle)?.map(|format| format.as_str().to_owned());
let device = *bundle.shape() == one_saves::Shape::Device;
if let Some(name) = args.to.clone()
&& Format::from_name(&name).is_none()
{
if card_format.is_some() || device || n64::is_n64_bundle(&bundle) {
return Err(format!(
"--to {name} lays a cartridge save out for the app or core that reads it; a card is written \
as its own format, and an N64 save with --n64"
)
.into());
}
return extract_for(&args, &bundle, &name);
}
if args.core.is_some() {
return Err("--core names the core an app given with --to runs".into());
}
let target = match args.to.as_deref() {
Some(name) => Format::from_name(name).ok_or_else(|| format!("unknown format {name:?}"))?,
None => match card_format.as_deref() {
Some(slug) => Format::from_card_format(slug)
.ok_or_else(|| format!("this bundle is a {slug}, which this build cannot write"))?,
None => Format::Raw,
},
};
if args.onto.is_some() && target != Format::N64Pak {
return Err("--onto is for an N64 save, with --n64, a Controller Pak, or a 64DD disk's save".into());
}
let reader = reader_of(&args, None)?;
let unwrapped = (target == Format::Raw).then(|| raw::unwrap_as(&bundle, &reader)).transpose()?;
let payload = match target {
Format::Raw => unwrapped.as_ref().map(|laid| laid.save.clone()).unwrap_or_default(),
Format::Bundle => return Err("extracting a bundle as a bundle is a copy".into()),
card => match args.onto.as_deref() {
Some(onto) => card::write_onto(card, &bundle, &std::fs::read(onto)?)?,
None => card::write(card, &bundle)?,
},
};
let (suffix, what) = written_as(target, &bundle, args.to.is_none());
let output = args.output.unwrap_or_else(|| args.input.with_extension(suffix));
let (payload, beside) = clock_beside(&bundle, unwrapped.as_ref(), payload, args.rtc_file, &output)?;
write_out(&output, &payload, args.force)?;
println!("{} -> {} ({}, {} bytes)", args.input.display(), output.display(), what, payload.len());
if let Some((path, sidecar)) = beside {
write_out(&path, &sidecar, args.force)?;
println!("clock -> {} ({} bytes)", path.display(), sidecar.len());
}
if let Some(unwrapped) = &unwrapped {
report_unwrapped(unwrapped, "its producer");
}
Ok(())
}
fn written_as(target: Format, bundle: &Bundle, as_produced: bool) -> (&'static str, &'static str) {
let device = *bundle.shape() == one_saves::Shape::Device;
match (target, producer_of(bundle)) {
(Format::Raw, _) if bundle.header.system.as_ref().is_some_and(|s| s.as_str() == "sega-cd") => {
("brm", "Sega CD backup RAM")
}
(Format::Raw, _) if n64dd::is_disk_save(bundle) => (n64dd::EXTENSION, "64DD disk save"),
(Format::Raw, Some((core, app))) if as_produced => {
(save_suffix(core, app, system_of_bundle(bundle)), target.label())
}
(Format::NeoGeoCard, _) if device => ("sav", "MiSTer NeoGeo save"),
_ => (target.extension(), target.label()),
}
}
#[cfg_attr(not(feature = "rom"), allow(clippy::unnecessary_wraps))]
fn reader_of(
args: &Extract,
core: Option<(&'static one_saves_registry::Core, Option<&'static one_saves_registry::App>)>,
) -> Result<raw::Reader, Box<dyn std::error::Error>> {
#[cfg(feature = "rom")]
let memory = match args.rom.as_deref() {
Some(rom) => one_saves_convert::rom::identify(&std::fs::read(rom)?).and_then(|info| info.memory),
None => None,
};
#[cfg(not(feature = "rom"))]
let memory = None;
Ok(raw::Reader { core, utc_offset: args.utc_offset, memory, layout: None, clock: None })
}
fn report_unwrapped(unwrapped: &raw::Unwrapped, reader: &str) {
if unwrapped.rescaled_by != 0 {
let hours = f64::from(i32::try_from(unwrapped.rescaled_by).unwrap_or(i32::MAX)) / 3600.0;
println!("moved the clock's anchor {hours:+} h, from the scale it was stamped on to {reader}'s");
}
if unwrapped.scale_unknown {
println!(
"note: the clock was stamped in a MiSTer's local time, or is going to one, and nothing said how"
);
println!(" far that is from UTC, so it may be off by the zone's offset; --utc-offset says");
}
if unwrapped.memory_assumed {
println!(
"note: laid out as SRAM, since nothing said what the cartridge keeps; pass --rom if it has an"
);
println!(" EEPROM larger than 256 bytes");
}
}
type ClockFile = (PathBuf, Vec<u8>);
fn clock_beside(
bundle: &Bundle,
unwrapped: Option<&raw::Unwrapped>,
payload: Vec<u8>,
rtc_file: Option<PathBuf>,
output: &Path,
) -> Result<(Vec<u8>, Option<ClockFile>), Box<dyn std::error::Error>> {
Ok(match (rtc_file, unwrapped) {
(Some(path), unwrapped) => {
let sidecar = one_saves_convert::rtc::sidecar_of(bundle)
.ok_or("this bundle carries no clock to write to a sidecar")?;
let save = match unwrapped {
Some(unwrapped) => unwrapped.save[..unwrapped.memory_len].to_vec(),
None => raw::unwrap_save_only(bundle)?,
};
(save, Some((path, sidecar)))
}
(None, Some(unwrapped)) => {
(payload, unwrapped.sidecar.clone().map(|sidecar| (output.with_extension("rtc"), sidecar)))
}
(None, None) => (payload, None),
})
}
fn extract_for(args: &Extract, bundle: &Bundle, name: &str) -> Fallible {
use one_saves_registry::{App, Core};
type Written = (&'static str, raw::Unwrapped);
let system = system_of_bundle(bundle);
if let Some(reader) =
one_saves_convert::profile(name).filter(|profile| profile.device_kind == "cartridge-reader")
{
return extract_for_cartridge_reader(args, bundle, &reader);
}
let (app, cores) = readers_of(name, args.core.as_deref(), system)?;
if let (Some(system), [core]) = (system, cores.as_slice())
&& !core.systems.contains(&system)
{
return Err(
format!("{} runs {}, and this save is for {system}", core.name, core.systems.join(", ")).into()
);
}
let written =
|core: &'static Core, app: Option<&'static App>| -> Result<Written, Box<dyn std::error::Error>> {
let unwrapped = raw::unwrap_as(bundle, &reader_of(args, Some((core, app)))?)?;
Ok((save_suffix(core, app, system), unwrapped))
};
let first = cores.first().ok_or("no core to write the save for")?;
let (suffix, unwrapped) = written(first, app)?;
for other in &cores[1..] {
let (other_suffix, other) = written(other, app)?;
if (other_suffix, &other.save, &other.sidecar) != (suffix, &unwrapped.save, &unwrapped.sidecar) {
let names: Vec<&str> = cores.iter().map(|core| core.slug).collect();
let app = app.map_or("", |app| app.name);
return Err(format!(
"{app} runs {} for this save, and they do not write it alike; name the one that will read it \
with --core",
names.join(", ")
)
.into());
}
}
let reader = match (app, cores.as_slice()) {
(Some(app), [_, _, ..]) => app.name.to_owned(),
(Some(app), _) if app.name != first.name => format!("{} in {}", first.name, app.name),
_ => first.name.to_owned(),
};
if unwrapped.sidecar.is_none() && args.rtc_file.is_some() {
return Err(format!(
"{reader} keeps no clock beside the save, so there is nothing to write to --rtc-file"
)
.into());
}
let output = args.output.clone().unwrap_or_else(|| args.input.with_extension(suffix));
let payload = &unwrapped.save;
write_out(&output, payload, args.force)?;
println!("{} -> {} (save for {reader}, {} bytes)", args.input.display(), output.display(), payload.len());
if let Some(beside) = &unwrapped.sidecar {
let path = args.rtc_file.clone().unwrap_or_else(|| output.with_extension("rtc"));
write_out(&path, beside, args.force)?;
println!("clock -> {} ({} bytes)", path.display(), beside.len());
} else if has_clock(bundle) && unwrapped.save.len() == unwrapped.memory_len {
println!("note: {reader} keeps no clock for this cartridge, so the save's clock was left out");
}
report_unwrapped(&unwrapped, &reader);
Ok(())
}
fn extract_for_cartridge_reader(
args: &Extract,
bundle: &Bundle,
reader: &one_saves_convert::Profile,
) -> Fallible {
if args.core.is_some() {
return Err(format!("{} runs no core, so --core has nothing to name", reader.label).into());
}
if args.rtc_file.is_some() {
return Err(format!(
"{} keeps no clock file, so there is nothing to write to --rtc-file",
reader.label
)
.into());
}
let system = system_of_bundle(bundle);
if let Some(system) = system
&& !reader.systems.contains(&system)
{
return Err(format!(
"{} reads {}, and this save is for {system}",
reader.label,
reader.systems.join(", ")
)
.into());
}
let unwrapped = raw::unwrap_as(
bundle,
&raw::Reader { layout: system.and_then(|system| reader.layout_in(system)), ..reader_of(args, None)? },
)?;
let save = &unwrapped.save[..unwrapped.memory_len];
let output = args.output.clone().unwrap_or_else(|| args.input.with_extension("sav"));
write_out(&output, save, args.force)?;
println!(
"{} -> {} (save for {}, {} bytes)",
args.input.display(),
output.display(),
reader.label,
save.len()
);
if has_clock(bundle) {
println!(
"note: nothing says how {} keeps a cartridge's clock, so the save's clock was left out",
reader.label
);
}
report_unwrapped(&unwrapped, reader.label);
Ok(())
}
fn save_suffix(
core: &one_saves_registry::Core,
app: Option<&one_saves_registry::App>,
system: Option<&str>,
) -> &'static str {
let libretro = core.kind == one_saves_registry::CoreKind::Libretro
&& app.is_none_or(|app| !app.cores.builds.contains(&core.slug));
match system {
Some("sega-cd") => "brm",
_ if libretro => "srm",
_ => "sav",
}
}
fn producer_of(
bundle: &Bundle,
) -> Option<(&'static one_saves_registry::Core, Option<&'static one_saves_registry::App>)> {
let source = bundle.header.source.as_ref()?;
let core = one_saves_registry::core(source.core.as_ref()?.as_str())?;
Some((core, source.app.as_ref().and_then(|app| one_saves_registry::app(app.as_str()))))
}
fn system_of_bundle(bundle: &Bundle) -> Option<&str> {
bundle.header.system.as_ref().map(one_saves::Slug::as_str)
}
fn has_clock(bundle: &Bundle) -> bool {
use one_saves::extension::{RtcHuc3, RtcMbc3, RtcN64dd, RtcS3511a};
let extensions = &bundle.header.extensions;
extensions.get::<RtcMbc3>().is_some()
|| extensions.get::<RtcS3511a>().is_some()
|| extensions.get::<RtcHuc3>().is_some()
|| extensions.get::<RtcN64dd>().is_some()
}
fn readers_of(
name: &str,
core: Option<&str>,
system: Option<&str>,
) -> Result<(Option<&'static one_saves_registry::App>, Vec<&'static one_saves_registry::Core>), String> {
let listed_core = |name: &str| {
one_saves_registry::core_by_any_name(name).ok_or_else(|| format!("{name:?} is not a listed core"))
};
let Some(app) = one_saves_registry::app_by_any_name(name) else {
let reader = one_saves_registry::core_by_any_name(name)
.ok_or_else(|| format!("{name:?} is neither a format nor a listed app or core"))?;
if core.is_some() {
return Err(format!("--core names the core an app runs, and {} is a core", reader.name));
}
return Ok((None, vec![reader]));
};
let readers = match (core, app.cores.builds, system) {
(Some(core), _, _) => vec![listed_core(core)?],
(None, [only], _) if app.cores.kind.is_none() => vec![listed_core(only)?],
(None, _, Some(system)) => {
let readers: Vec<_> =
one_saves_registry::cores_for_system(system).filter(|core| app.runs(core)).collect();
if readers.is_empty() {
return Err(format!("{} runs no listed core for {system}", app.name));
}
readers
}
(None, _, None) => {
return Err(format!(
"{} runs many cores and this save names no system; name the one that will read it with --core",
app.name
));
}
};
if let Some(reader) = readers.iter().find(|reader| !app.runs(reader)) {
return Err(format!("{} does not run {}", app.name, reader.name));
}
Ok((Some(app), readers))
}
fn new_card(args: &New) -> Fallible {
let format =
Format::from_name(&args.kind).filter(|format| !card::sizes(*format).is_empty()).ok_or_else(|| {
format!("{:?} is not a kind of memory card: ps1, ps2, gc, n64, vmu, saturn or neogeo", args.kind)
})?;
let size = match &args.size {
Some(name) => card::size(format, name).ok_or_else(|| {
let sizes: Vec<String> =
card::sizes(format).iter().map(|size| format!("{} ({})", size.name, size.label)).collect();
let (last, rest) = sizes.split_last().expect("every card has a size");
let listed =
if rest.is_empty() { last.clone() } else { format!("{} or {last}", rest.join(", ")) };
format!("a {} comes in {listed}", format.label())
})?,
None => {
card::sizes(format).iter().find(|size| size.standard).expect("every card has a standard size")
}
};
let layout = match args.layout.as_deref() {
Some(name) => card::Layout::from_name(name)
.ok_or_else(|| format!("{name:?} is not a layout: bare, wide or mister"))?,
None => card::Layout::Bare,
};
let as_bundle = extension_of(&args.output) == one_saves::EXTENSION;
if as_bundle && layout != card::Layout::Bare {
return Err(
"--layout is how an emulator's file wraps a card, and a bundle holds the card itself".into()
);
}
let options = card::BlankOptions { capacity: Some(size.capacity), shift_jis: args.shift_jis, layout };
let bytes = card::blank(format, &options)?;
let bytes =
if as_bundle { card::read(format, &bytes, &card::CardOptions::default())?.to_vec()? } else { bytes };
write_out(&args.output, &bytes, args.force)?;
println!("empty {} -> {} ({}, {} bytes)", format.label(), args.output.display(), size.label, bytes.len());
Ok(())
}
fn inspect(path: &Path) -> Fallible {
let bytes = std::fs::read(path)?;
let bundle = Bundle::from_slice(&bytes)?;
println!("{}", path.display());
println!(" {} bytes, spec version {}", bytes.len(), one_saves::SPEC_VERSION);
describe(&bundle, 2, 0);
Ok(())
}
const LABEL_WIDTH: usize = 13;
const MAX_DEPTH: usize = 4;
fn field(indent: usize, label: &str, value: &str) {
println!("{}", format!("{:indent$}{label:LABEL_WIDTH$}{value}", "").trim_end());
}
fn describe(bundle: &Bundle, indent: usize, depth: usize) {
let header = &bundle.header;
let shape = bundle.shape();
if shape.is_known() {
field(indent, "shape", shape.as_str());
} else {
field(indent, "shape", &format!("{shape} (not a shape spec {} defines)", one_saves::SPEC_VERSION));
}
if let Some(system) = &header.system {
field(indent, "system", &system_name(system));
}
if let Some(card) = &header.card {
field(indent, "card", &format!("{}, capacity {} bytes", card.format, card.capacity));
if let Some(area) = &card.system_area {
field(indent, "", &format!("system area {}", shown_bytes(area)));
}
for line in unknown_keys(&card.unknown) {
field(indent, "", &format!("unknown {line}"));
}
}
if let Some(source) = &header.source {
describe_source(indent, source);
}
if let Some(seconds) = header.bundled_at {
field(indent, "bundled", &format!("{} UTC", Civil(seconds)));
}
if let Some(seconds) = header.taken_at {
field(indent, "taken", &format!("{} UTC", Civil(seconds)));
}
if let Some(origin) = &header.origin {
let what = match origin {
Origin::Auto => "the emulator took it to resume from".to_owned(),
Origin::Undo => "the emulator kept it to undo a save or a load".to_owned(),
Origin::Unknown(_) => format!("not an origin spec {} defines", one_saves::SPEC_VERSION),
};
field(indent, "origin", &format!("{origin} ({what})"));
}
if let Some(taken_with) = &header.taken_with {
describe_taken_with(indent, taken_with);
}
match &header.game {
Some(game) => describe_game(indent, game),
None if matches!(shape, one_saves::Shape::Device | one_saves::Shape::Collection) => {}
None => field(indent, "game", "unidentified"),
}
if let Some(description) = &header.description {
field(indent, "description", &printable(description));
}
for key in header.extensions.keys() {
field(indent, "extension", &describe_extension(&header.extensions, key));
}
for line in unknown_keys(&header.unknown) {
field(indent, "unknown", &line);
}
field(indent, "parts", &bundle.parts.len().to_string());
for part in &bundle.parts {
describe_part(part, indent + 2, depth);
}
}
fn describe_part(part: &Part, indent: usize, depth: usize) {
let kind = part.kind.as_str().unwrap_or("save");
let role = match (&part.role, &part.kind) {
(Some(role), _) => role.as_str(),
(None, PartKind::State | PartKind::Screenshot) => "",
(None, _) => "primary",
};
let serial = printable(part.game.as_ref().and_then(|game| game.serial.as_deref()).unwrap_or(""));
let path = printable(part.path.as_deref().unwrap_or(""));
let slot = part.slot.map_or_else(String::new, |s| format!("slot {s}"));
let id = format!("[{}]", part.id);
let digest = part.sha256.to_string();
let short = digest.strip_prefix("sha256:").unwrap_or(&digest);
let line = format!(
"{:indent$}{id:<5} {kind:10} {role:16} {:>9} bytes {} {serial:12} {slot:8} {path}",
"",
part.payload.len(),
&short[..16]
);
println!("{}", line.trim_end());
let indent = indent + 6;
let inner = if part.kind != PartKind::Bundle {
None
} else if depth >= MAX_DEPTH {
Some(Err(format!("not listed, being more than {MAX_DEPTH} deep")))
} else {
Some(
Bundle::from_slice(&part.payload)
.map_err(|e| format!("cannot be opened: {}", printable(&e.to_string()))),
)
};
let held = inner.as_ref().and_then(|inner| inner.as_ref().ok()).map(|inner| &inner.header);
if let Some(source) = &part.source {
describe_source(indent, source);
}
if let Some(game) = &part.game
&& held.is_none_or(|held| held.game.as_ref() != Some(game))
{
describe_game(indent, game);
}
if let Some(system) = &part.system
&& held.is_none_or(|held| held.system.as_ref() != Some(system))
{
field(indent, "system", &system_name(system));
}
if let Some(binding) = &part.binding {
let listed = if one_saves_registry::is_binding(binding.as_str()) { "" } else { " (unlisted)" };
field(indent, "binding", &format!("{binding}{listed}"));
}
if let Some(bound_to) = &part.bound_to {
for (label, id) in
[("console", &bound_to.device), ("account", &bound_to.account), ("medium", &bound_to.medium)]
{
if let Some(id) = id {
field(indent, "bound to", &format!("{label} {}", shown_bytes(id)));
}
}
for line in unknown_keys(&bound_to.unknown) {
field(indent, "bound to", &line);
}
}
if let Some(content_type) = &part.content_type {
field(indent, "content type", &printable(content_type));
}
if let Some(dirent) = &part.dirent {
field(indent, "dirent", &shown_bytes(dirent));
}
for key in part.extensions.keys() {
field(indent, "extension", &describe_extension(&part.extensions, key));
}
for line in unknown_keys(&part.unknown) {
field(indent, "unknown", &line);
}
match inner {
Some(Ok(inner)) => describe(&inner, indent + 2, depth + 1),
Some(Err(why)) => field(indent, "bundle", &why),
None => {}
}
}
fn describe_taken_with(indent: usize, taken_with: &TakenWith) {
fn entry<T>(
lines: &mut Vec<String>,
name: &str,
value: Option<&Recorded<T>>,
show: impl Fn(&T) -> Vec<String>,
) {
match value {
None => {}
Some(Recorded::Unknown) => lines.push(format!("{name} unknown")),
Some(Recorded::Known(value)) => {
lines.extend(show(value).into_iter().map(|line| format!("{name} {line}")));
}
}
}
let mut lines = Vec::new();
entry(&mut lines, "byte order", taken_with.byte_order.as_ref(), |order| vec![order.as_str().to_owned()]);
entry(&mut lines, "word size", taken_with.word_size.as_ref(), |size| {
vec![format!("{} bits", size.bits())]
});
entry(&mut lines, "firmware", taken_with.firmware.as_ref(), |files| {
files
.iter()
.map(|(file, hashes)| {
let hashes: Vec<String> = hashes.iter().map(ToString::to_string).collect();
format!("{} {}", printable(file), hashes.join(" "))
})
.collect()
});
entry(&mut lines, "language", taken_with.language.as_ref(), |language| vec![printable(language)]);
entry(&mut lines, "option", taken_with.options.as_ref(), |options| {
options.iter().map(|(name, value)| format!("{} = {}", printable(name), printable(value))).collect()
});
entry(&mut lines, "format version", taken_with.format_version.as_ref(), |version| {
vec![version.to_string()]
});
lines.extend(
taken_with
.extensions
.keys()
.map(|key| format!("extension {}", describe_extension(&taken_with.extensions, key))),
);
lines.extend(unknown_keys(&taken_with.unknown).map(|line| format!("unknown {line}")));
for (index, line) in lines.iter().enumerate() {
field(indent, if index == 0 { "taken with" } else { "" }, line);
}
}
fn describe_source(indent: usize, source: &Source) {
let app = layer("app", "", source.app.as_ref(), source.app_version.as_deref(), |slug| {
one_saves_registry::app(slug).map(|app| app.name)
});
let core = layer("core", "core ", source.core.as_ref(), source.core_version.as_deref(), |slug| {
one_saves_registry::core(slug).map(|core| core.name)
});
let platform = layer(
"platform",
"platform ",
source.platform.as_ref(),
source.platform_version.as_deref(),
|slug| one_saves_registry::platform(slug).map(|platform| platform.name),
);
let kind = source.device_kind.as_ref().map(|kind| {
let listed = if one_saves_registry::is_device_kind(kind.as_str()) { "" } else { " (unlisted)" };
format!("{kind}{listed}")
});
let bits: Vec<String> = [app, core, platform, kind].into_iter().flatten().collect();
field(indent, "source", &bits.join(", "));
if let Some(fingerprint) = &source.fingerprint {
field(indent, "", &format!("fingerprint {}", printable(fingerprint)));
}
for line in unknown_keys(&source.unknown) {
field(indent, "", &format!("unknown {line}"));
}
}
fn layer(
what: &str,
label: &str,
name: Option<&Name>,
version: Option<&str>,
lookup: impl Fn(&str) -> Option<&'static str>,
) -> Option<String> {
let name = name.map(|name| match name.as_slug() {
Some(slug) => format!("{name} ({})", lookup(slug.as_str()).unwrap_or("unlisted")),
None => name.to_string(),
});
match (name, version.map(printable)) {
(Some(name), Some(version)) => Some(format!("{label}{name} {version}")),
(Some(name), None) => Some(format!("{label}{name}")),
(None, Some(version)) => Some(format!("{what} version {version}")),
(None, None) => None,
}
}
fn describe_game(indent: usize, game: &Game) {
let bits: Vec<String> = [&game.title, &game.serial, &game.rom_filename]
.into_iter()
.flatten()
.map(|text| printable(text))
.collect();
field(indent, "game", &bits.join(", "));
if let Some(system) = &game.system {
field(indent, "", &format!("system {}", system_name(system)));
}
for hash in &game.rom_hashes {
field(indent, "", &hash.to_string());
}
for (resolver, id) in &game.game_id {
let id = match id {
one_saves::GameId::Uint(n) => n.to_string(),
one_saves::GameId::Text(t) => printable(t),
};
field(indent, "", &format!("{resolver} = {id}"));
}
for key in game.extensions.keys() {
field(indent, "", &format!("extension {}", describe_extension(&game.extensions, key)));
}
for line in unknown_keys(&game.unknown) {
field(indent, "", &format!("unknown {line}"));
}
}
fn system_name(system: &one_saves::Slug) -> String {
format!("{system} ({})", one_saves_registry::system(system.as_str()).map_or("unlisted", |s| s.name))
}
fn unknown_keys(keys: &one_saves::UnknownKeys) -> impl Iterator<Item = String> + '_ {
keys.iter().map(|(key, value)| {
let text = value.diagnostic_flat();
let text = match text.char_indices().nth(SHOWN_CHARS - 1) {
Some((cut, _)) if text.chars().nth(SHOWN_CHARS).is_some() => format!("{}…", &text[..cut]),
_ => text,
};
format!("key {key} = {}", printable(&text))
})
}
fn shown_bytes(bytes: &[u8]) -> String {
let mut head = String::new();
for byte in bytes.iter().take(SHOWN_BYTES) {
write!(head, "{byte:02x}").expect("a String takes any write");
}
let more = if bytes.len() > SHOWN_BYTES { "…" } else { "" };
format!("h'{head}{more}' ({} bytes)", bytes.len())
}
fn describe_extension(extensions: &one_saves::Extensions, key: &one_saves::ReverseDnsName) -> String {
match extensions.display(key) {
Some(value) => format!("{key} = {}", printable(&value.to_string())),
None => key.to_string(),
}
}
fn printable(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for character in text.chars() {
if character.is_control() || is_bidi_control(character) {
out.extend(character.escape_default());
} else {
out.push(character);
}
}
out
}
fn is_bidi_control(character: char) -> bool {
matches!(character, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
}
fn verify(path: &Path) -> Fallible {
let bytes = std::fs::read(path)?;
let bundle = Bundle::from_slice(&bytes)?;
if bundle.to_vec()? != bytes {
eprintln!(" this file is not the deterministic encoding of what it says");
return Err(format!("1 problem in {}", path.display()).into());
}
println!("{}: ok ({} part(s))", path.display(), bundle.parts.len());
Ok(())
}
fn hash(path: &Path) -> Fallible {
let bytes = std::fs::read(path)?;
Bundle::from_slice(&bytes)?;
println!("content {}", one_saves::HashValue::sha256_of(&bytes));
Ok(())
}
fn profiles() {
println!("{:<14} {:<18} {:<12} {:<18} SYSTEMS", "NAME", "DEVICE KIND", "APP", "CORE");
for profile in one_saves_convert::profile::profiles() {
let systems =
if profile.systems.is_empty() { "(any)".to_owned() } else { profile.systems.join(", ") };
println!(
"{:<14} {:<18} {:<12} {:<18} {systems}",
profile.key,
profile.device_kind,
profile.app.unwrap_or("-"),
profile.core.unwrap_or("-")
);
}
println!(
"\nA dash is a name neither registry lists, which a bundle leaves out rather than invent one for.\n\
Any of the {} apps and {} cores in the registry also works by slug or name, and --core and\n\
--platform name the core an app ran and the firmware it ran on.",
one_saves_registry::apps().len(),
one_saves_registry::cores().len()
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_reader_is_an_app_first_and_a_core_otherwise() {
let slugs = |name, core, system| {
readers_of(name, core, system).map(|(app, cores)| {
(app.map(|app| app.slug), cores.iter().map(|core| core.slug).collect::<Vec<_>>())
})
};
assert_eq!(slugs("mgba", None, None), Ok((Some("mgba"), vec!["mgba"])));
assert_eq!(slugs("retroarch", Some("mGBA"), None), Ok((Some("retroarch"), vec!["mgba"])));
assert_eq!(slugs("gambatte", None, None), Ok((None, vec!["gambatte"])));
assert_eq!(slugs("Gameboy_MiSTer", None, None), Ok((None, vec!["gameboy-mister"])));
assert_eq!(slugs("openemu", Some("gambatte"), None), Ok((Some("openemu"), vec!["gambatte"])));
assert_eq!(slugs("mister", None, Some("gbc")), Ok((Some("mister"), vec!["gameboy-mister"])));
assert_eq!(
slugs("mister", None, Some("gb")),
Ok((Some("mister"), vec!["gameboy-mister", "sgb-mister"]))
);
assert!(slugs("retroarch", None, None).unwrap_err().contains("--core"));
assert!(slugs("retroarch", Some("gameboy-mister"), None).unwrap_err().contains("does not run"));
assert!(slugs("gambatte", Some("mgba"), None).is_err(), "--core is for an app");
assert!(slugs("nonesuch", None, None).is_err());
}
#[test]
fn text_from_a_bundle_cannot_drive_the_terminal() {
assert_eq!(printable("FINAL FANTASY VII"), "FINAL FANTASY VII");
assert_eq!(printable("TEKKEN 4"), "TEKKEN 4");
assert_eq!(printable("\u{1b}]0;owned\u{7}\u{1b}[2J"), r"\u{1b}]0;owned\u{7}\u{1b}[2J");
assert_eq!(printable("two\nlines\u{9b}"), r"two\nlines\u{9b}");
}
#[test]
fn text_from_a_bundle_cannot_reorder_itself_either() {
assert_eq!(printable("save\u{202e}vas.exe"), r"save\u{202e}vas.exe");
assert_eq!(printable("\u{2066}a\u{2069}\u{200f}\u{61c}"), r"\u{2066}a\u{2069}\u{200f}\u{61c}");
assert_eq!(printable("ポケモン"), "ポケモン");
}
#[test]
fn an_error_quoting_the_file_cannot_drive_the_terminal() {
#[derive(Debug)]
struct Quoting(&'static str, Option<Box<Quoting>>);
impl std::fmt::Display for Quoting {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for Quoting {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.1.as_deref().map(|inner| inner as &(dyn std::error::Error + 'static))
}
}
let error =
Quoting("`\u{1b}]0;owned\u{7}` is not an encoding", Some(Box::new(Quoting("\u{1b}[2J", None))));
let report = report(&error);
assert!(!report.contains('\u{1b}') && !report.contains('\u{7}'), "{report:?}");
assert_eq!(report, "1saves: `\\u{1b}]0;owned\\u{7}` is not an encoding\n caused by: \\u{1b}[2J\n");
}
fn scratch(name: &str) -> PathBuf {
let directory = std::env::temp_dir().join(format!("1saves-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&directory);
std::fs::create_dir_all(&directory).unwrap();
directory
}
#[test]
fn writing_refuses_whatever_is_already_there() {
let directory = scratch("write-refuses");
let path = directory.join("out.mcd");
write_out(&path, b"first", false).unwrap();
let error = write_out(&path, b"second", false).unwrap_err();
assert!(error.to_string().contains("already exists; pass --force"), "{error}");
assert_eq!(std::fs::read(&path).unwrap(), b"first");
write_out(&path, b"second", true).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"second");
assert_eq!(std::fs::read_dir(&directory).unwrap().count(), 1, "no temporary is left behind");
}
#[cfg(unix)]
#[test]
fn writing_never_follows_a_link_planted_at_the_output() {
let directory = scratch("write-links");
let victim = directory.join("victim");
let output = directory.join("save.srm");
std::os::unix::fs::symlink(&victim, &output).unwrap();
assert!(write_out(&output, b"payload", false).is_err());
assert!(!victim.exists(), "the link's target was created");
std::fs::write(&victim, b"precious").unwrap();
write_out(&output, b"payload", true).unwrap();
assert_eq!(std::fs::read(&victim).unwrap(), b"precious");
assert!(std::fs::symlink_metadata(&output).unwrap().file_type().is_file());
assert_eq!(std::fs::read(&output).unwrap(), b"payload");
}
#[test]
fn a_file_beside_the_input_is_read_when_it_is_a_small_regular_file() {
let directory = scratch("beside-regular");
assert_eq!(read_beside(&directory.join("absent.rtc"), 64), Ok(None));
let clock = directory.join("save.rtc");
std::fs::write(&clock, [1, 2, 3, 4]).unwrap();
assert_eq!(read_beside(&clock, 64), Ok(Some(vec![1, 2, 3, 4])));
std::fs::write(&clock, [0; 65]).unwrap();
let why = read_beside(&clock, 64).unwrap_err();
assert!(why.contains("more than the 64"), "{why}");
assert!(read_beside(&directory, 64).is_err(), "a directory is not a file to read");
}
#[cfg(unix)]
#[test]
fn a_file_beside_the_input_is_not_a_link_or_a_fifo() {
let directory = scratch("beside-special");
let private = directory.join("private.png");
std::fs::write(&private, b"\x89PNG private").unwrap();
let thumbnail = directory.join("game.state.png");
std::os::unix::fs::symlink(&private, &thumbnail).unwrap();
assert!(read_beside(&thumbnail, 1 << 20).unwrap_err().contains("not a regular file"));
let fifo = directory.join("game.rtc");
let made = std::process::Command::new("mkfifo").arg(&fifo).status().unwrap();
assert!(made.success());
assert!(read_beside(&fifo, 64).unwrap_err().contains("not a regular file"));
let linked = directory.join("other.rtc");
std::os::unix::fs::symlink(&fifo, &linked).unwrap();
assert!(read_beside(&linked, 64).unwrap_err().contains("not a regular file"));
}
#[test]
fn a_digest_inside_a_nested_bundle_is_checked_on_the_way_in() {
let mut save = Bundle::new(one_saves::Header::default(), vec![Part::new(0, *b"SAVE")]);
save.parts[0].sha256 = one_saves::HashValue::sha256_of(b"EVAS");
let nested = Part::new(0, save.to_cbor().to_cbor_data()).kind(PartKind::Bundle);
let bundle = Bundle::new(one_saves::Header::new(one_saves::Shape::Collection), vec![nested]);
let error = Bundle::from_slice(&bundle.to_cbor().to_cbor_data()).unwrap_err();
assert_eq!(error.kind(), &one_saves::ErrorKind::PayloadHashMismatch, "{error}");
}
fn convert_args(line: &[&str]) -> Convert {
let Command::Convert(args) = Cli::try_parse_from(line).expect("parses").command else {
panic!("not a convert");
};
*args
}
#[test]
fn a_chip_s_file_names_its_system_only_when_nothing_else_does() {
let args = convert_args(&["1saves", "convert", "--from", "mister", "Paper Mario (USA).fla"]);
assert_eq!(system_of(&args, None, None, None, "fla", 0).as_deref(), Some("n64"));
assert_eq!(system_of(&args, None, None, None, "sav", 0), None);
assert_eq!(system_of(&args, None, None, None, "ram", 1_942_080).as_deref(), Some("n64dd"));
assert_eq!(system_of(&args, None, None, None, "ram", 32_768), None);
let args = convert_args(&["1saves", "convert", "--system", "gba", "save.fla"]);
assert_eq!(system_of(&args, None, None, None, "fla", 0).as_deref(), Some("gba"));
let args = convert_args(&["1saves", "convert", "save.fla"]);
let duckstation = one_saves_convert::profile("duckstation");
assert_eq!(system_of(&args, None, duckstation.as_ref(), None, "fla", 0).as_deref(), Some("psx"));
}
}