inf2ron 0.1.0

Parse Stranded II .inf definition files (items, objects, units, buildings, combinations) and output RON format
Documentation
// inf2ron – parse Stranded II .inf definition files to RON
// Copyright (C) 2025  inf2ron 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::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();

    // If the last argument is NOT an existing .inf file, treat it as output directory
    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,
    })
}

/// Convert a single .inf file to .ron and write to 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(())
}

/// Run the CLI.
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(())
}