inf2ron 0.2.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 [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>,
    /// Explicit output path (or directory), or None for stdout-per-file
    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}"));
    }

    // The last positional may be an output file/directory
    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")
        {
            // Treat as input (ends with .inf, is a directory, or has no clear extension)
            let inputs: Vec<PathBuf> = positional.iter().map(PathBuf::from).collect();
            (inputs, None)
        } else {
            // Last positional is an output path
            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,
    })
}

/// Determine output format for a given input stem.
fn output_format(_stem: &str, args: &Args) -> (&'static str, &'static str) {
    // Explicit flags win
    if args.force_json {
        return ("json", "JSON");
    }
    if args.force_ron {
        return ("ron", "RON");
    }

    // If an explicit output path was given, detect from its extension
    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")
}

/// Convert a single .inf file.
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);

    // Serialize
    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(),
    };

    // Determine output path
    let out_path = if let Some(ref explicit) = args.output {
        if explicit.is_dir() || !explicit.to_string_lossy().contains('.') {
            // Treat as directory
            let mut p = explicit.clone();
            p.push(format!("{stem}.{ext}"));
            p
        } else {
            // Treat as exact file path (overrides stem/extension)
            explicit.clone()
        }
    } else {
        let mut p = PathBuf::from(".");
        p.push(format!("{stem}.{ext}"));
        p
    };

    // Ensure parent directory exists
    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(())
}

/// 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(());
    }

    // Validate conflicting flags
    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(())
}