s2s2lua 0.1.0

Transpile Stranded II .s2s scripts to Lua for OpenStranded
Documentation
// s2s2lua – transpile Stranded II .s2s scripts to Lua for OpenStranded
// Copyright (C) 2025  s2s2lua contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

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 {
    /// Namespace prefix for emitted commands (default: core_api)
    #[arg(short = 'n', long = "namespace", default_value = "core_api")]
    pub namespace: String,

    /// Input .s2s files or directories containing .s2s files
    #[arg(required = true)]
    pub inputs: Vec<PathBuf>,

    /// Output directory for generated .lua files
    #[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);
        }
    }
}