yog-cli 0.47.0

Yog build tool — `yog build` compiles a mod and packages it as .yog.
Documentation
//! The generated `.yog-build/Cargo.toml`.

use crate::manifest::{
    DEFAULT_EDITION, DEPS_SECTION, YogToml, to_snake_name, workspace_rkyv_version,
};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};

/// Generate the hidden Cargo.toml from yog.toml metadata.
/// `benches`: the mod's `yog bench` files — they add `[dev-dependencies]`,
/// `[[bench]]` targets and an `rlib` for them to link.
pub fn generate_cargo_toml(meta: &YogToml, benches: &[crate::bench::BenchFile]) -> String {
    let authors_toml = if meta.authors.is_empty() {
        String::new()
    } else {
        let list = meta
            .authors
            .iter()
            .map(|a| format!("{a:?}"))
            .collect::<Vec<_>>()
            .join(", ");
        format!("authors      = [{list}]\n")
    };
    let edition = meta.edition.as_deref().unwrap_or(DEFAULT_EDITION);

    // With a local yog-api, its sibling yog-* crates (yog-ui, yog-gfx,
    // yog-interop, ...) come from the same checkout too — the local API may
    // need versions of them that aren't on crates.io yet.
    let patch = if meta.yog_api_path.is_some() || std::env::var("YOG_API_PATH").is_ok() {
        let env_path = std::env::var("YOG_API_PATH").ok();
        let api_path = meta
            .yog_api_path
            .as_deref()
            .or(env_path.as_deref())
            .unwrap_or("");
        // The mod's own yog-* dependencies (yog-kit, ...) too: they're
        // built against the local yog-api.
        // They depend on yog-api from crates.io, so it's patched as well.
        let mut extra: Vec<&str> = meta
            .dependencies
            .iter()
            .map(|(name, _)| name.as_str())
            .filter(|n| n.starts_with("yog-"))
            .collect();
        if !extra.is_empty() {
            extra.push("yog-api");
        }
        local_api_patch(Path::new(api_path), &extra)
    } else {
        String::new()
    };

    // Plain crates.io dependencies from [dependencies] — used exactly as
    // written, never guessed at.
    let mut deps_lines: Vec<String> = Vec::new();
    for (name, spec) in &meta.dependencies {
        deps_lines.push(format!("{} = {}", name, spec));
    }

    // Other Yog mods this mod depends on, from [dependencies.exports].
    // Each maps to that mod's generated exports crate — package name must
    // match `publish_exports`'s own `{sanitized_id}_exports` naming exactly
    // (underscores, not hyphens: that's the literal name published to
    // crates.io). Each dependency keeps its own name as the local alias
    // (`{name} = { package = ... }`), so mod code imports it the same way
    // as a direct dependency (`use {name}::...`) and two mod dependencies
    // never collide under one shared alias.
    for (name, spec) in &meta.mod_dependencies {
        let exports_name = format!("{}_exports", name.replace('-', "_"));
        let dep = if spec.starts_with('{') {
            let inner = spec.trim_start_matches('{').trim_end_matches('}').trim();
            if inner.is_empty() {
                format!("{name} = {{ package = \"{exports_name}\" }}")
            } else {
                format!("{name} = {{ package = \"{exports_name}\", {inner} }}")
            }
        } else {
            format!("{name} = {{ package = \"{exports_name}\", version = {spec} }}")
        };
        deps_lines.push(dep);
    }

    format!(
        r#"# Generated by yog from yog.toml — do not edit.
[package]
name         = "{id}"
version      = "{version}"
edition      = "{edition}"
description  = {description:?}
{authors_line}license      = {license:?}

[lib]
name       = "{lib_name}"
crate-type = {crate_types}
path       = "../src/lib.rs"

[dependencies]
{api_dep}
rkyv = "{rkyv_ver}"
{deps}
{bench}{patch}"#,
        id = meta.id,
        rkyv_ver = workspace_rkyv_version(),
        lib_name = to_snake_name(&meta.id),
        version = meta.version,
        edition = edition,
        description = meta.description,
        authors_line = authors_toml,
        license = meta.license,
        api_dep = meta.api_dep(),
        deps = deps_lines.join("\n"),
        patch = patch,
        crate_types = if benches.is_empty() {
            r#"["cdylib"]"#
        } else {
            r#"["cdylib", "rlib"]"#
        },
        bench = crate::bench::cargo_sections(meta, benches),
    )
}

/// The `yog-*` crates a yog-api `Cargo.toml` depends on, in order.
pub fn yog_dependencies(cargo_toml: &str) -> Vec<String> {
    let mut in_deps = false;
    let mut out = Vec::new();
    for line in cargo_toml.lines() {
        let line = line.trim();
        if line.starts_with('[') {
            in_deps = line == DEPS_SECTION;
            continue;
        }
        if !in_deps {
            continue;
        }
        let Some((name, _)) = line.split_once('=') else {
            continue;
        };
        // `yog-x = { workspace = true }` or the dotted `yog-x.workspace = true`.
        let name = name.split('.').next().unwrap_or(name).trim();
        if name.starts_with("yog-") && !out.iter().any(|n| n == name) {
            out.push(name.to_string());
        }
    }
    out
}

/// `[patch.crates-io]` pointing every yog-* dependency of the local yog-api
/// at `api_path`'s sibling crate directory (always including yog-interop,
/// whose proc-macros generated code must match).
/// `extra` adds the mod's own yog-* dependencies.
pub fn local_api_patch(api_path: &Path, extra: &[&str]) -> String {
    let crates_dir = api_path
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from("crates"));
    let mut names = std::fs::read_to_string(api_path.join("Cargo.toml"))
        .map(|t| yog_dependencies(&t))
        .unwrap_or_default();
    if !names.iter().any(|n| n == "yog-interop") {
        names.push("yog-interop".into());
    }
    for name in extra {
        if !names.iter().any(|n| n == name) {
            names.push((*name).to_string());
        }
    }
    // Transitively: a local yog-ui may need a yog-graphics that crates.io
    // hasn't got yet.
    let mut i = 0;
    while i < names.len() {
        let deps = std::fs::read_to_string(crates_dir.join(&names[i]).join("Cargo.toml"))
            .map(|t| yog_dependencies(&t))
            .unwrap_or_default();
        for dep in deps {
            if !names.contains(&dep) {
                names.push(dep);
            }
        }
        i += 1;
    }
    let mut out = String::from("\n[patch.crates-io]\n");
    for name in names {
        let dir = crates_dir.join(&name);
        if !dir.join("Cargo.toml").is_file() && name != "yog-interop" {
            continue;
        }
        let abs = dir.canonicalize().unwrap_or(dir);
        let _ = writeln!(out, "{name} = {{ path = {:?} }}", abs.to_string_lossy());
    }
    out
}

#[cfg(test)]
mod tests {
    #[test]
    fn yog_dependencies_reads_the_dependencies_table() {
        let toml = "[package]\nname = \"yog-api\"\n\n[dependencies]\nyog-abi  = \"0.25\"\nyog-ui = { version = \"0.35\" }\nserde = \"1\"\n\n[dev-dependencies]\nyog-test = \"1\"\n";
        assert_eq!(super::yog_dependencies(toml), ["yog-abi", "yog-ui"]);
    }

    #[test]
    fn yog_dependencies_reads_workspace_inherited_lines() {
        let toml = "[dependencies]\nyog-abi = { workspace = true }\nyog-ui = { workspace = true }\nlibc = { workspace = true }\n";
        assert_eq!(super::yog_dependencies(toml), ["yog-abi", "yog-ui"]);
    }
}