use std::fs;
use std::path::{Path, PathBuf};
use clap::Parser;
use s2s2lua::{GenOptions, LuaGenerator, S2sParser};
#[derive(Parser)]
#[command(name = "s2s2lua", about = "Transpile Stranded II .s2s scripts to Lua")]
pub struct Cli {
#[arg(short = 'n', long = "namespace", default_value = "core_api")]
pub namespace: String,
#[arg(required = true)]
pub inputs: Vec<PathBuf>,
#[arg(required = true)]
pub output: PathBuf,
}
pub fn run(cli: Cli) {
let mut files: Vec<PathBuf> = Vec::new();
for input in &cli.inputs {
if input.is_dir() {
collect_s2s_files(input, &mut files);
} else if input.is_file() {
files.push(input.clone());
} else {
eprintln!("error: '{}' is neither a file nor a directory", input.display());
std::process::exit(1);
}
}
if files.is_empty() {
eprintln!("error: no .s2s files found");
std::process::exit(1);
}
fs::create_dir_all(&cli.output).unwrap_or_else(|e| {
eprintln!("error: failed to create output directory '{}': {e}", cli.output.display());
std::process::exit(1);
});
let options = GenOptions {
command_prefix: format!("{}.", cli.namespace),
};
let mut success = 0;
let mut failed = 0;
for path in &files {
let source = match fs::read_to_string(path) {
Ok(s) => s,
Err(e) => {
eprintln!("error: failed to read '{}': {e}", path.display());
failed += 1;
continue;
}
};
let script = match S2sParser::parse(&source) {
Ok(s) => s,
Err(e) => {
eprintln!("error: failed to parse '{}': {e}", path.display());
failed += 1;
continue;
}
};
let lua = match LuaGenerator::generate(&script, options.clone()) {
Ok(l) => l,
Err(e) => {
eprintln!("error: failed to generate Lua for '{}': {e}", path.display());
failed += 1;
continue;
}
};
let out_name = path.file_stem().unwrap_or_default().to_string_lossy().to_string();
let out_path = cli.output.join(format!("{}.lua", out_name));
if let Err(e) = fs::write(&out_path, &lua) {
eprintln!("error: failed to write '{}': {e}", out_path.display());
failed += 1;
continue;
}
println!(" {} -> {}", path.display(), out_path.display());
success += 1;
}
if failed > 0 {
eprintln!("completed: {success} succeeded, {failed} failed");
std::process::exit(1);
}
}
fn collect_s2s_files(dir: &Path, files: &mut Vec<PathBuf>) {
let entries = match fs::read_dir(dir) {
Ok(e) => e,
Err(_) => return,
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_s2s_files(&path, files);
} else if path.extension().is_some_and(|ext| ext == "s2s") {
files.push(path);
}
}
}