sastri 0.1.0

Scaffold multi-ecosystem packaging and CI/CD for Rust CLIs (Homebrew, Scoop, PyPI, npm, Hex, mise, asdf, …)
Documentation
//! Non-sensitive project config (`Sastri.toml`). Secrets are never stored here.

use std::fs;
use std::path::Path;

use anyhow::{Context, Result};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SastriConfig {
    pub project: Project,
    #[serde(default)]
    pub org: Org,
    /// Mechanism id → enabled. Unknown ids are ignored at generate time so
    /// future ecosystems can appear in config before the binary knows them.
    #[serde(default)]
    pub mechanisms: IndexMap<String, bool>,
    #[serde(default)]
    pub release: Release,
    #[serde(default)]
    pub paths: Paths,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Project {
    /// Crate / product name (often matches the binary)
    pub name: String,
    pub description: String,
    pub github_owner: String,
    pub github_repo: String,
    pub binary_name: String,
    #[serde(default = "default_license")]
    pub license: String,
    #[serde(default = "default_version")]
    pub version: String,
    /// Path to the Cargo package that builds the CLI (relative to repo root)
    #[serde(default = "default_manifest")]
    pub cargo_manifest: String,
    pub homepage: Option<String>,
}

fn default_license() -> String {
    "MIT".into()
}
fn default_version() -> String {
    "0.1.0".into()
}
fn default_manifest() -> String {
    "Cargo.toml".into()
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Org {
    /// e.g. latentmeta/homebrew-tap
    pub homebrew_tap: Option<String>,
    /// e.g. latentmeta/scoop-bucket
    pub scoop_bucket: Option<String>,
    /// e.g. latentmeta (npm org without @)
    pub npm_org: Option<String>,
    /// e.g. @latentmeta/oratos — full package name
    pub npm_package: Option<String>,
    /// Hex package atom, e.g. oratos
    pub hex_package: Option<String>,
    /// PyPI project name
    pub pypi_package: Option<String>,
    /// asdf plugin repo, e.g. latentmeta/asdf-oratos
    pub asdf_plugin_repo: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Release {
    /// Platforms to emit in the release matrix
    #[serde(default = "default_platforms")]
    pub platforms: Vec<String>,
    #[serde(default = "default_true")]
    pub publish_crates_io: bool,
    #[serde(default = "default_true")]
    pub publish_sha256sums: bool,
}

impl Default for Release {
    fn default() -> Self {
        Self {
            platforms: default_platforms(),
            publish_crates_io: true,
            publish_sha256sums: true,
        }
    }
}

fn default_platforms() -> Vec<String> {
    vec![
        "linux-x86_64".into(),
        "linux-aarch64".into(),
        "macos-aarch64".into(),
        "macos-x86_64".into(),
        "windows-x86_64".into(),
    ]
}

fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Paths {
    #[serde(default = "default_packaging")]
    pub packaging_dir: String,
    #[serde(default = "default_scripts")]
    pub scripts_dir: String,
    #[serde(default = "default_workflows")]
    pub workflows_dir: String,
    #[serde(default = "default_actions")]
    pub actions_dir: String,
}

impl Default for Paths {
    fn default() -> Self {
        Self {
            packaging_dir: default_packaging(),
            scripts_dir: default_scripts(),
            workflows_dir: default_workflows(),
            actions_dir: default_actions(),
        }
    }
}

fn default_packaging() -> String {
    "packaging".into()
}
fn default_scripts() -> String {
    "scripts".into()
}
fn default_workflows() -> String {
    ".github/workflows".into()
}
fn default_actions() -> String {
    ".github/actions".into()
}

impl SastriConfig {
    pub fn load(path: &Path) -> Result<Self> {
        let text = fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
        toml::from_str(&text).with_context(|| format!("parse {}", path.display()))
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        let text = toml::to_string_pretty(self)?;
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() {
                fs::create_dir_all(parent)?;
            }
        }
        fs::write(path, text).with_context(|| format!("write {}", path.display()))?;
        Ok(())
    }

    pub fn github_slug(&self) -> String {
        format!("{}/{}", self.project.github_owner, self.project.github_repo)
    }

    pub fn homepage(&self) -> String {
        self.project.homepage.clone().unwrap_or_else(|| {
            format!(
                "https://github.com/{}/{}",
                self.project.github_owner, self.project.github_repo
            )
        })
    }

    pub fn mechanism_enabled(&self, id: &str) -> bool {
        self.mechanisms.get(id).copied().unwrap_or(false)
    }

    /// Default mechanism map for a new project (stable channels on).
    pub fn default_mechanisms() -> IndexMap<String, bool> {
        IndexMap::from([
            ("ci".into(), true),
            ("github_releases".into(), true),
            ("install_sh".into(), true),
            ("homebrew".into(), true),
            ("scoop".into(), true),
            ("asdf".into(), true),
            ("mise".into(), true),
            ("setup_action".into(), true),
            ("npm".into(), true),
            ("pypi".into(), true),
            ("hex".into(), true),
            // Future — registered as stubs; enable when implemented.
            ("ruby_gem".into(), false),
            ("haskell_cabal".into(), false),
        ])
    }
}

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

    fn minimal_toml() -> String {
        r#"
[project]
name = "greet"
description = "Tiny CLI"
github_owner = "latentmeta"
github_repo = "greet"
binary_name = "greet"
version = "1.2.3"
"#
        .into()
    }

    #[test]
    fn parse_applies_defaults() {
        let cfg: SastriConfig = toml::from_str(&minimal_toml()).unwrap();
        assert_eq!(cfg.project.license, "MIT");
        assert_eq!(cfg.project.cargo_manifest, "Cargo.toml");
        assert!(cfg.release.publish_crates_io);
        assert_eq!(cfg.paths.packaging_dir, "packaging");
        assert_eq!(cfg.release.platforms.len(), 5);
        assert_eq!(cfg.homepage(), "https://github.com/latentmeta/greet");
        assert_eq!(cfg.github_slug(), "latentmeta/greet");
    }

    #[test]
    fn round_trip_save_load() {
        let dir = std::env::temp_dir().join(format!("sastri-cfg-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("Sastri.toml");

        let mut cfg: SastriConfig = toml::from_str(&minimal_toml()).unwrap();
        cfg.mechanisms = SastriConfig::default_mechanisms();
        cfg.org.homebrew_tap = Some("latentmeta/homebrew-tap".into());
        cfg.save(&path).unwrap();

        let loaded = SastriConfig::load(&path).unwrap();
        assert_eq!(loaded.project.name, "greet");
        assert_eq!(loaded.project.version, "1.2.3");
        assert!(loaded.mechanism_enabled("ci"));
        assert!(!loaded.mechanism_enabled("ruby_gem"));
        assert!(!loaded.mechanism_enabled("unknown_future"));

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn default_mechanisms_enable_distribution_core() {
        let m = SastriConfig::default_mechanisms();
        for id in ["ci", "github_releases", "homebrew", "scoop", "asdf", "mise"] {
            assert_eq!(m.get(id), Some(&true), "{id}");
        }
    }

    #[test]
    fn load_missing_file_errors() {
        let path = PathBuf::from("/tmp/sastri-does-not-exist-hopefully.toml");
        assert!(SastriConfig::load(&path).is_err());
    }
}