use std::path::{Path, PathBuf};
use crate::error::InfResult;
use crate::parser::InfParser;
const USAGE: &str = "\
Usage: inf2ron <file.inf>... [output]
Parse Stranded II .inf definition files and write RON output.
Arguments:
<file.inf>... One or more .inf files to parse
[output] Optional output directory (default: current directory)
Options:
--help, -? Show this help message and exit
";
struct Args {
help: bool,
inputs: Vec<PathBuf>,
output_dir: PathBuf,
}
fn parse_args() -> Result<Args, String> {
let raw: Vec<String> = std::env::args().collect();
if raw.len() >= 2 && (raw[1] == "--help" || raw[1] == "-?") {
return Ok(Args {
help: true,
inputs: vec![],
output_dir: PathBuf::new(),
});
}
if raw.len() < 2 {
return Err(format!("too few arguments\n\n{USAGE}"));
}
let mut paths: Vec<PathBuf> = raw[1..].iter().map(PathBuf::from).collect();
let output_dir = if paths.len() >= 2 {
let last = paths.last().unwrap();
if !last.to_string_lossy().ends_with(".inf") && !last.is_file() {
paths.pop().unwrap()
} else {
PathBuf::from(".")
}
} else {
PathBuf::from(".")
};
if paths.is_empty() {
return Err("no input files specified\n\n{USAGE}".into());
}
for p in &paths {
if !p.is_file() {
return Err(format!("file not found: {}", p.display()));
}
}
Ok(Args {
help: false,
inputs: paths,
output_dir,
})
}
fn convert_one(inf_path: &Path, out_dir: &Path) -> InfResult<()> {
let entries = InfParser::parse_file(inf_path)?;
let stem = inf_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("output");
let ron = ron::to_string(&entries)
.map_err(|e| crate::error::InfError::Parse {
line: 0,
message: format!("RON serialization failed: {e}"),
})?;
std::fs::create_dir_all(out_dir)
.map_err(crate::error::InfError::Io)?;
let mut out_path = out_dir.to_path_buf();
out_path.push(format!("{stem}.ron"));
std::fs::write(&out_path, &ron)
.map_err(crate::error::InfError::Io)?;
eprintln!("wrote {}", 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(());
}
for inf_path in &args.inputs {
if let Err(e) = convert_one(inf_path, &args.output_dir) {
eprintln!("error: {}: {e}", inf_path.display());
}
}
Ok(())
}