use std::path::{Path, PathBuf};
use crate::error::InfResult;
use crate::parser::InfParser;
const USAGE: &str = "\
Usage: inf2ron [options] <file.inf>... [output]
Parse Stranded II .inf definition files to RON or JSON.
Output format is auto-detected from extension:
file.ron → RON (default if no extension matches)
file.json → JSON
Arguments:
<file.inf>... One or more .inf files to parse
[output] Optional output file or directory
Options:
--json Force JSON output (overrides extension detection)
--ron Force RON output (overrides extension detection)
--help, -? Show this help message and exit
Examples:
inf2ron items_edible.inf
inf2ron items_edible.inf output/
inf2ron items_edible.inf output/items.ron
inf2ron --json items_edible.inf items.json
";
struct Args {
help: bool,
force_json: bool,
force_ron: bool,
inputs: Vec<PathBuf>,
output: Option<PathBuf>,
}
fn parse_args() -> Result<Args, String> {
let raw: Vec<String> = std::env::args().collect();
let mut help = false;
let mut force_json = false;
let mut force_ron = false;
let mut positional: Vec<String> = Vec::new();
let mut i = 1;
while i < raw.len() {
match raw[i].as_str() {
"--help" | "-?" => help = true,
"--json" => force_json = true,
"--ron" => force_ron = true,
s if s.starts_with('-') => {
return Err(format!("unknown option '{s}'\n\n{USAGE}"));
}
_ => positional.push(raw[i].clone()),
}
i += 1;
}
if help {
return Ok(Args {
help: true,
force_json,
force_ron,
inputs: vec![],
output: None,
});
}
if positional.is_empty() {
return Err(format!("no input files specified\n\n{USAGE}"));
}
let (inputs, output) = if positional.len() >= 2 {
let last = PathBuf::from(positional.last().unwrap());
if last.to_string_lossy().ends_with(".inf")
|| last.is_dir()
|| last.extension().is_none_or(|e| e == "inf")
{
let inputs: Vec<PathBuf> = positional.iter().map(PathBuf::from).collect();
(inputs, None)
} else {
let out = Some(last);
let inputs: Vec<PathBuf> = positional[..positional.len() - 1]
.iter()
.map(PathBuf::from)
.collect();
(inputs, out)
}
} else {
let inputs: Vec<PathBuf> = positional.iter().map(PathBuf::from).collect();
(inputs, None)
};
for p in &inputs {
if !p.is_file() {
return Err(format!("file not found: {}", p.display()));
}
}
Ok(Args {
help: false,
force_json,
force_ron,
inputs,
output,
})
}
fn output_format(_stem: &str, args: &Args) -> (&'static str, &'static str) {
if args.force_json {
return ("json", "JSON");
}
if args.force_ron {
return ("ron", "RON");
}
if let Some(ref out_path) = args.output
&& (out_path.is_file() || out_path.to_string_lossy().contains('.'))
{
match out_path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("ron")
{
"json" => return ("json", "JSON"),
_ => return ("ron", "RON"),
}
}
("ron", "RON")
}
fn convert_one(inf_path: &Path, args: &Args) -> InfResult<()> {
let entries = InfParser::parse_file(inf_path)?;
let stem = inf_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("output");
let (ext, fmt_name) = output_format(stem, args);
let serialized: String = match ext {
"json" => serde_json::to_string_pretty(&entries)
.map_err(|e| format!("JSON serialization failed: {e}"))
.unwrap(),
_ => ron::to_string(&entries)
.map_err(|e| format!("RON serialization failed: {e}"))
.unwrap(),
};
let out_path = if let Some(ref explicit) = args.output {
if explicit.is_dir() || !explicit.to_string_lossy().contains('.') {
let mut p = explicit.clone();
p.push(format!("{stem}.{ext}"));
p
} else {
explicit.clone()
}
} else {
let mut p = PathBuf::from(".");
p.push(format!("{stem}.{ext}"));
p
};
if let Some(parent) = out_path.parent() {
let _ = std::fs::create_dir_all(parent);
}
std::fs::write(&out_path, &serialized)
.map_err(crate::error::InfError::Io)?;
eprintln!("wrote {} ({fmt_name})", out_path.display());
Ok(())
}
pub fn run() -> InfResult<()> {
let args = match parse_args() {
Ok(a) => a,
Err(e) => {
eprintln!("error: {e}");
std::process::exit(1);
}
};
if args.help {
print!("{USAGE}");
return Ok(());
}
if args.force_json && args.force_ron {
eprintln!("error: cannot specify both --json and --ron");
std::process::exit(1);
}
for inf_path in &args.inputs {
if let Err(e) = convert_one(inf_path, &args) {
eprintln!("error: {}: {e}", inf_path.display());
}
}
Ok(())
}