pets_tools 0.2.0

MusKitty multi-repo source management CLI — one command to clone, build, test, push, and publish 9 independent crate repositories
//! `pets new <project> <name>` — scaffold a new muskitty crate.

use crate::config::Config;
use crate::ui;
use crate::NewArgs;
use std::path::Path;

pub fn run(config: Config, args: &NewArgs) {
    let crate_name = format!("muskitty-{}", args.name);
    let crate_dir = config.crates_dir.join(&crate_name);

    ui::heading(&format!("Scaffolding new crate: {}", crate_name));

    if args.dry_run {
        ui::info("--dry-run: showing what would be created:");
        list_files(&crate_dir, &args.deps, &args.dev_deps);
        return;
    }

    if crate_dir.exists() {
        ui::error(&format!(
            "{} already exists — aborting.",
            crate_dir.display()
        ));
        std::process::exit(1);
    }

    // Create directory structure
    let dirs = [
        crate_dir.clone(),
        crate_dir.join("src"),
        crate_dir.join(".github").join("workflows"),
        crate_dir.join("scripts"),
    ];
    for d in &dirs {
        std::fs::create_dir_all(d).unwrap_or_else(|e| {
            ui::error(&format!("Cannot create {}: {}", d.display(), e));
            std::process::exit(1);
        });
    }

    // Resolve full dep names (add muskitty- prefix if needed)
    let deps: Vec<String> = args.deps.iter().map(|d| full_name(d)).collect();
    let dev_deps: Vec<String> = args.dev_deps.iter().map(|d| full_name(d)).collect();

    let deps_toml = format_deps(&deps);
    let dev_deps_toml = format_dev_deps(&dev_deps);

    write_file(
        &crate_dir.join("Cargo.toml"),
        &cargo_toml(&crate_name, &deps_toml, &dev_deps_toml, &args.msrv),
    );
    write_file(&crate_dir.join("src").join("lib.rs"), &lib_rs(&crate_name));
    write_file(&crate_dir.join("LICENSE"), LICENSE_TEXT);
    write_file(&crate_dir.join("README.md"), &readme(&crate_name));
    write_file(
        &crate_dir.join(".github").join("workflows").join("ci.yml"),
        &ci_yml(&crate_name, &deps),
    );
    write_file(
        &crate_dir
            .join(".github")
            .join("workflows")
            .join("publish.yml"),
        &publish_yml(&crate_name, &deps),
    );
    if !deps.is_empty() {
        write_file(
            &crate_dir.join("scripts").join("setup-deps.sh"),
            &setup_deps_sh(&crate_name, &deps),
        );
    }

    ui::success(&format!(
        "Created {} in {}",
        crate_name,
        crate_dir.display()
    ));
    println!();
    ui::info("Next steps:");
    ui::info(&format!("  1. cd {}", crate_dir.display()));
    ui::info("  2. git init && git remote add origin https://github.com/muskitty-dev/<repo>.git");
    ui::info(&format!(
        "  3. Add [[repos]] entry to repos.toml for '{}'",
        crate_name
    ));
    ui::info("  4. cargo check");
}

// ── helpers ──

fn full_name(s: &str) -> String {
    if s.starts_with("muskitty-") {
        s.to_string()
    } else {
        format!("muskitty-{}", s)
    }
}

fn list_files(dir: &Path, deps: &[String], dev_deps: &[String]) {
    let files = [
        "Cargo.toml",
        "src/lib.rs",
        "LICENSE",
        "README.md",
        ".github/workflows/ci.yml",
        ".github/workflows/publish.yml",
    ];
    for f in &files {
        ui::info(&format!("  {}", dir.join(f).display()));
    }
    if !deps.is_empty() || !dev_deps.is_empty() {
        ui::info(&format!(
            "  {}",
            dir.join("scripts/setup-deps.sh").display()
        ));
    }
}

fn format_deps(deps: &[String]) -> String {
    deps.iter()
        .map(|d| format!("{} = {{ path = \"../{}\", version = \"0.1.0\" }}", d, d))
        .collect::<Vec<_>>()
        .join("\n")
}

fn format_dev_deps(deps: &[String]) -> String {
    deps.iter()
        .map(|d| format!("{} = {{ path = \"../{}\", version = \"0.1.0\" }}", d, d))
        .collect::<Vec<_>>()
        .join("\n")
}

fn write_file(path: &Path, content: &str) {
    std::fs::write(path, content).unwrap_or_else(|e| {
        ui::error(&format!("Cannot write {}: {}", path.display(), e));
        std::process::exit(1);
    });
    ui::info(&format!(
        "  ✓ {}",
        path.file_name().unwrap_or_default().to_string_lossy()
    ));
}

// ── templates ──

fn cargo_toml(name: &str, deps: &str, dev_deps: &str, msrv: &str) -> String {
    let mut out = format!(
        "[package]\n\
         name = \"{}\"\n\
         version = \"0.1.0\"\n\
         edition = \"2021\"\n\
         rust-version = \"{}\"\n\
         license = \"Apache-2.0\"\n\
         description = \"TODO: describe {}\"\n\
         repository = \"https://github.com/muskitty-dev/{}\"\n\
         homepage = \"https://github.com/muskitty-dev\"\n\
         documentation = \"https://docs.rs/{}\"\n\
         keywords = [\"web\", \"browser\"]\n\
         categories = [\"web-programming\"]\n\
         authors = [\"MusCat / MusKitty Bit-Torch Community\"]\n",
        name, msrv, name, name, name,
    );

    if !deps.is_empty() {
        out.push_str("\n[dependencies]\n");
        out.push_str(deps);
        out.push('\n');
    }

    if !dev_deps.is_empty() {
        out.push_str("\n[dev-dependencies]\n");
        out.push_str(dev_deps);
        out.push('\n');
    }

    out.push_str(
        "\n# Prevent parent workspace from absorbing this crate.\n\
         # This crate is an independent git repo with its own workspace root.\n\
         [workspace]\n",
    );
    out
}

fn lib_rs(name: &str) -> String {
    format!(
        "//! {} — TODO: describe this crate.\n\
         //!\n\
         //! Part of the MusKitty browser engine project.\n\n\
         // TODO: add public API\n",
        name,
    )
}

const LICENSE_TEXT: &str = "\
                                 Apache License\n\
                                 Version 2.0, January 2004\n\
                                 http://www.apache.org/licenses/\n\
\n\
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\
\n\
1. Definitions.\n\
\n\
\"License\" shall mean the terms and conditions for use, reproduction,\n\
and distribution as defined by Sections 1 through 9 of this document.\n\
\n\
\"Licensor\" shall mean the copyright owner or entity authorized by\n\
the copyright owner that is granting the License.\n\
\n\
[... full Apache-2.0 text would go here ...]\n\
\n\
END OF TERMS AND CONDITIONS\n\
\n\
Licensed under the Apache License, Version 2.0.\n";

fn readme(name: &str) -> String {
    format!(
        "# {}\n\n\
         TODO: describe {}. Part of the MusKitty browser engine project.\n\n\
         ## License\n\n\
         Apache-2.0\n",
        name, name,
    )
}

fn setup_step(deps: &[String]) -> String {
    if deps.is_empty() {
        return String::new();
    }
    "      - name: Clone path dependencies\n\
             \x20       run: bash scripts/setup-deps.sh\n\
             \x20       env:\n\
             \x20         GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
        .to_string()
}

fn ci_job_template(name: &str, deps: &[String], extra: &str) -> String {
    let toolchain_with = if name == "fmt:" {
        "        with:\n          components: rustfmt\n"
    } else if name == "clippy:" {
        "        with:\n          components: clippy\n"
    } else {
        ""
    };
    let command = match name {
        "check:" => "cargo check",
        "test-unit:" => "cargo test --lib",
        "test-integration:" => "cargo test --tests",
        "fmt:" => "cargo fmt --all -- --check",
        "clippy:" => "cargo clippy --all-targets -- -D warnings",
        "msrv:" => "cargo check",
        _ => "cargo check",
    };
    format!(
        "    {}\n\
         {}    steps:\n      - uses: actions/checkout@v4\n\
         {}\
         {}      - uses: dtolnay/rust-toolchain@stable\n      - uses: Swatinem/rust-cache@v2\n\
              - run: {}\n",
        name,
        extra,
        setup_step(deps),
        toolchain_with,
        command,
    )
}

fn ci_yml(_name: &str, deps: &[String]) -> String {
    let jobs = [
        ("check:", ""),
        ("test-unit:", ""),
        ("test-integration:", ""),
        ("fmt:", ""),
        ("clippy:", ""),
    ];
    let msrv_extra = "      - uses: dtolnay/rust-toolchain@master\n        with:\n          toolchain: \"1.85\"\n";

    let mut out = "name: CI\n\n\
         on:\n  push:\n    branches: [main, master]\n  pull_request:\n    branches: [main, master]\n\n\
         env:\n  CARGO_TERM_COLOR: always\n  RUSTFLAGS: -D warnings\n\n\
         jobs:\n"
        .to_string();

    for (job_name, extra) in &jobs {
        let body = ci_job_template(job_name, deps, extra);
        out.push_str(&body);
        out.push('\n');
    }

    // msrv job is special (different toolchain setup)
    out.push_str(&format!(
        "  msrv:\n    name: MSRV (1.85)\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n\
         {}\
         {}      - uses: Swatinem/rust-cache@v2\n      - run: cargo check\n",
        setup_step(deps),
        msrv_extra,
    ));
    out
}

fn publish_yml(_name: &str, deps: &[String]) -> String {
    format!(
        "name: Publish\n\n\
         on:\n  push:\n    tags: ['v*']\n\n\
         jobs:\n\
           check-version:\n    runs-on: ubuntu-latest\n    outputs:\n      published: ${{{{ steps.check.outputs.published }}}}\n    steps:\n      - uses: actions/checkout@v4\n      - id: check\n        run: |\n          VERSION=$(grep '^version' Cargo.toml | head -1 | sed 's/.*= \"//;s/\"//')\n          STATUS=$(curl -s -o /dev/null -w '%{{http_code}}' https://crates.io/api/v1/crates/{}/$VERSION)\n          if [ \"$STATUS\" = \"200\" ]; then echo \"published=true\" >> $GITHUB_OUTPUT; else echo \"published=false\" >> $GITHUB_OUTPUT; fi\n\n\
           publish:\n    needs: check-version\n    if: needs.check-version.outputs.published != 'true'\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n\
         {}\
              - uses: dtolnay/rust-toolchain@stable\n      - run: cargo publish --token ${{{{ secrets.CARGO_REGISTRY_TOKEN }}}}\n\n\
           create-release:\n    needs: publish\n    if: always() && needs.publish.result == 'success'\n    runs-on: ubuntu-latest\n    steps:\n      - uses: softprops/action-gh-release@v2\n        with:\n          generate_release_notes: true\n",
        _name,
        setup_step(deps),
    )
}

fn setup_deps_sh(_name: &str, deps: &[String]) -> String {
    let mut clones = String::new();
    for dep in deps {
        clones.push_str(&format!(
            "clone_if_absent https://github.com/muskitty-dev/{}.git ../{}\n",
            dep, dep,
        ));
    }

    format!(
        "#!/bin/bash\n\
         # Clone path dependencies for independent CI.\n\
         # Auto-generated by pets_tools for {}.\n\
         set -euo pipefail\n\n\
         if [ -n \"${{GH_TOKEN:-}}\" ]; then\n\
         \x20   git config --global \"url.https://x-access-token:${{GH_TOKEN}}@github.com/\".insteadOf \"https://github.com/\"\n\
         fi\n\n\
         clone_if_absent() {{\n\
         \x20   local url=\"$1\"\n\
         \x20   local dest=\"$2\"\n\
         \x20   if [ -d \"$dest\" ]; then\n\
         \x20       echo \"skip $dest (exists)\"\n\
         \x20   else\n\
         \x20       git clone --depth 1 \"$url\" \"$dest\"\n\
         \x20   fi\n\
         }}\n\n\
         {}\n",
        _name, clones,
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn full_name_adds_and_keeps_prefix() {
        assert_eq!(full_name("dom"), "muskitty-dom");
        assert_eq!(full_name("muskitty-css"), "muskitty-css");
    }

    #[test]
    fn cargo_toml_has_workspace_guard_and_msrv() {
        let deps = "muskitty-dom = { path = \"../muskitty-dom\", version = \"0.1.0\" }";
        let s = cargo_toml("muskitty-dom", deps, "", "1.85");
        assert!(s.contains("name = \"muskitty-dom\""));
        assert!(s.contains("rust-version = \"1.85\""));
        assert!(s.contains("[workspace]"));
        assert!(s.contains("[dependencies]"));
        assert!(!s.contains("[dev-dependencies]"));
    }

    #[test]
    fn ci_yml_has_msrv_job_and_dep_clone_step() {
        let deps = vec!["muskitty-css".to_string()];
        let s = ci_yml("muskitty-x", &deps);
        assert!(s.contains("name: CI"));
        assert!(s.contains("MSRV (1.85)"));
        assert!(s.contains("Clone path dependencies"));
    }

    #[test]
    fn setup_deps_sh_mentions_pets_tools_and_repo_urls() {
        let deps = vec!["muskitty-dom".to_string()];
        let s = setup_deps_sh("muskitty-x", &deps);
        assert!(s.contains("Auto-generated by pets_tools"));
        assert!(s.contains("https://github.com/muskitty-dev/muskitty-dom.git"));
    }

    #[test]
    fn format_deps_renders_path_entries() {
        let deps = vec!["muskitty-dom".to_string()];
        let s = format_deps(&deps);
        assert!(s.contains("muskitty-dom = { path = \"../muskitty-dom\", version = \"0.1.0\" }"));
    }
}