cargo-makegen 0.1.2

Generate Makefile from Cargo metadata and/or Makefile.toml
Documentation
use crate::cargo_rules;
use crate::cli::{Args, OnlySection};
use crate::makefile_toml;
use crate::model::{MakefileToml, Metadata};
use crate::variables::build_env;
use anyhow::{Context, Result};
use std::{fs, process::Command};

pub fn run(args: Args) -> Result<()> {
    let meta = load_metadata()?;
    let env = build_env(&meta);

    let makefile_path = args
        .output
        .clone()
        .unwrap_or(meta.workspace_root.join("Makefile"));

    let mut out = String::new();
    out.push_str("# Auto-generated by cargo-makegen\n\n");

    // === CARGO ===
    if !args.skip_cargo && args.only != Some(OnlySection::Toml) {
        out.push_str(&cargo_rules::generate(&meta)?);
    }

    // === MAKEFILE.TOML ===
    let makefile_toml_path = meta.workspace_root.join("Makefile.toml");
    if makefile_toml_path.exists()
        && !args.skip_makefile_toml
        && args.only != Some(OnlySection::Cargo)
    {
        let text = fs::read_to_string(&makefile_toml_path)?;
        let parsed: MakefileToml = toml::from_str(&text)?;
        out.push_str(&makefile_toml::generate(&parsed, &env)?);
    }

    fs::write(&makefile_path, out)?;
    println!("Generated {}", makefile_path.display());

    Ok(())
}

fn load_metadata() -> Result<Metadata> {
    let output = Command::new("cargo")
        .args(["metadata", "--format-version=1", "--no-deps"])
        .output()
        .context("failed to run cargo metadata")?;

    if !output.status.success() {
        anyhow::bail!("cargo metadata failed");
    }

    Ok(serde_json::from_slice(&output.stdout)?)
}