cat-fetch 0.1.1

MusKitty multi-repo source management CLI — one command to clone, build, test, push, and publish 8 independent crate repositories
//! repos.toml parsing and data structures.

use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

/// Top-level configuration deserialized from repos.toml.
#[derive(Debug, Deserialize)]
pub struct ConfigFile {
    pub project: ProjectMeta,
    pub main_repo: MainRepo,
    #[serde(default)]
    pub repos: Vec<Repo>,
}

#[derive(Debug, Deserialize)]
pub struct ProjectMeta {
    pub name: String,
    pub root: PathBuf,
    #[serde(default)]
    pub crates_dir: Option<PathBuf>,
}

#[derive(Debug, Deserialize)]
pub struct MainRepo {
    pub name: String,
    pub dir: PathBuf,
    pub url: String,
    #[serde(default)]
    pub upstream: Option<String>,
    pub token_key: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Repo {
    pub name: String,
    pub dir: String,
    pub url: String,
    #[serde(default)]
    pub deps: Vec<String>,
    #[serde(default)]
    pub dev_deps: Vec<String>,
    #[serde(default = "default_msrv")]
    pub msrv: String,
    #[serde(default = "default_token_key")]
    pub token_key: String,
}

fn default_msrv() -> String {
    "1.82".into()
}

fn default_token_key() -> String {
    "crates".into()
}

/// Fully resolved, validated configuration.
#[derive(Debug)]
pub struct Config {
    pub project_name: String,
    #[allow(dead_code)]
    pub root: PathBuf,
    pub crates_dir: PathBuf,
    pub main_repo: ResolvedMainRepo,
    /// All crate repos (does not include main).
    pub repos: Vec<ResolvedRepo>,
    /// Lookup: crate name → index in `repos`.
    #[allow(dead_code)]
    pub index: HashMap<String, usize>,
}

#[derive(Debug)]
pub struct ResolvedMainRepo {
    pub name: String,
    pub dir: PathBuf,
    pub url: String,
    pub upstream: Option<String>,
    #[allow(dead_code)]
    pub token_key: String,
}

#[derive(Debug, Clone)]
pub struct ResolvedRepo {
    pub name: String,
    pub abs_dir: PathBuf,
    pub url: String,
    pub deps: Vec<String>,
    pub dev_deps: Vec<String>,
    #[allow(dead_code)]
    pub msrv: String,
    #[allow(dead_code)]
    pub token_key: String,
}

impl Config {
    /// Load and validate repos.toml from `path`.
    pub fn load(path: &Path) -> Result<Self, String> {
        let content = std::fs::read_to_string(path)
            .map_err(|e| format!("cannot read {}: {}", path.display(), e))?;
        let cf: ConfigFile = toml::from_str(&content)
            .map_err(|e| format!("parse error in {}: {}", path.display(), e))?;

        // Validate project name
        if cf.project.name.is_empty() {
            return Err("[project].name must not be empty".into());
        }

        let crates_dir = cf
            .project
            .crates_dir
            .unwrap_or_else(|| cf.project.root.join("crates"));

        // Create name→index mapping and validate
        let mut index = HashMap::new();
        for (i, repo) in cf.repos.iter().enumerate() {
            if index.contains_key(&repo.name) {
                return Err(format!("duplicate repo name: {}", repo.name));
            }
            index.insert(repo.name.clone(), i);
        }

        // Validate deps reference existing repos
        let names: HashSet<&str> = cf.repos.iter().map(|r| r.name.as_str()).collect();
        for repo in &cf.repos {
            for dep in &repo.deps {
                if !names.contains(dep.as_str()) {
                    return Err(format!(
                        "repo '{}' depends on '{}', which is not in repos.toml",
                        repo.name, dep
                    ));
                }
            }
            for dep in &repo.dev_deps {
                if !names.contains(dep.as_str()) {
                    return Err(format!(
                        "repo '{}' has dev-dep '{}', which is not in repos.toml",
                        repo.name, dep
                    ));
                }
            }
        }

        let project_root = cf.project.root.clone();

        Ok(Self {
            project_name: cf.project.name.clone(),
            root: cf.project.root,
            crates_dir,
            main_repo: ResolvedMainRepo {
                name: cf.main_repo.name,
                dir: cf.main_repo.dir,
                url: cf.main_repo.url,
                upstream: cf.main_repo.upstream,
                token_key: cf.main_repo.token_key,
            },
            repos: cf
                .repos
                .into_iter()
                .map(|r| ResolvedRepo {
                    abs_dir: project_root.join(&r.dir),
                    name: r.name,
                    url: r.url,
                    deps: r.deps,
                    dev_deps: r.dev_deps,
                    msrv: r.msrv,
                    token_key: r.token_key,
                })
                .collect(),
            index,
        })
    }

    /// Look up a resolved repo by name.
    #[allow(dead_code)]
    pub fn repo_by_name(&self, name: &str) -> Option<&ResolvedRepo> {
        self.index.get(name).map(|&i| &self.repos[i])
    }

    /// All repo dirs (main + crates) that exist for scanning.
    #[allow(dead_code)]
    pub fn all_dirs(&self) -> impl Iterator<Item = (&str, &Path)> {
        let main = ("main", self.main_repo.dir.as_path());
        let crates = self
            .repos
            .iter()
            .map(|r| (r.name.as_str(), r.abs_dir.as_path()));
        std::iter::once(main).chain(crates)
    }
}