hyuskui 0.0.5

Add hyuskui components to a GPUI project: cargo hyuskui add button
use std::{
    fs,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result, bail};
use similar::TextDiff;

use crate::registry::{self, Item};

/// The GPUI version the registry is checked against. Bump together.
const TESTED_ZED_REV: &str = "a36d4850f3c087bfef8a3552e2e15d72d97efdf4";
const TESTED_RUST: &str = "1.100.0";

const UI_MOD_HEADER: &str = "//! Components added with `cargo hyuskui add`. They are yours: edit freely.\n\n// Components expose more options than any one app uses.\n#![allow(dead_code)]\n\n";

pub struct Project {
    root: PathBuf,
}

impl Project {
    /// Finds the nearest directory with a Cargo.toml, starting at `path` or the current directory.
    pub fn locate(path: Option<PathBuf>) -> Result<Self> {
        let start = match path {
            Some(path) => path,
            None => std::env::current_dir()?,
        };
        let start = start
            .canonicalize()
            .with_context(|| format!("{} does not exist", start.display()))?;
        let mut dir: &Path = &start;
        loop {
            if dir.join("Cargo.toml").is_file() {
                return Ok(Self {
                    root: dir.to_path_buf(),
                });
            }
            match dir.parent() {
                Some(parent) => dir = parent,
                None => bail!("no Cargo.toml found in {} or any parent directory", start.display()),
            }
        }
    }

    /// Writes src/theme.rs and src/ui/mod.rs and declares both modules in the crate root.
    pub fn init(&self) -> Result<()> {
        let theme = registry::find("theme").expect("registry has a theme");
        for file in theme.files {
            self.write_new(file.target, file.content, false)?;
        }

        let ui_mod = self.root.join("src/ui/mod.rs");
        if !ui_mod.exists() {
            fs::create_dir_all(ui_mod.parent().unwrap())?;
            fs::write(&ui_mod, UI_MOD_HEADER)?;
            println!("created src/ui/mod.rs");
        }

        self.declare_root_modules(&["theme", "ui"])
    }

    /// Declares `mod name;` in the crate root for each module it doesn't declare yet.
    fn declare_root_modules(&self, modules: &[&str]) -> Result<()> {
        let crate_root = self.crate_root()?;
        let relative = crate_root
            .strip_prefix(&self.root)
            .unwrap_or(&crate_root)
            .display()
            .to_string();
        let mut source = fs::read_to_string(&crate_root)?;
        let mut changed = false;
        for module in modules {
            if !declares_module(&source, module) {
                source = insert_module(&source, module);
                changed = true;
                println!("declared `mod {module};` in {relative}");
            }
        }
        if changed {
            fs::write(&crate_root, source)?;
        }
        Ok(())
    }

    /// Adds a component, or shared code like `icons`, along with what it depends on.
    pub fn add(&self, item: &Item, overwrite: bool) -> Result<()> {
        for dependency in item.dependencies {
            // `init` already wrote the theme.
            if let Some(dep) = registry::find(dependency).filter(|dep| dep.name != "theme") {
                self.add(dep, overwrite)?;
            }
        }
        for file in item.files {
            self.write_new(file.target, file.content, overwrite)?;
        }
        if item.kind == "registry:ui" {
            return self.register_ui_module(item.name);
        }
        // Shared code lives at the crate root, as src/<name>.rs.
        let modules: Vec<&str> = item
            .files
            .iter()
            .filter_map(|file| file.target.strip_prefix("src/")?.strip_suffix(".rs"))
            .filter(|module| !module.contains('/'))
            .collect();
        self.declare_root_modules(&modules)
    }

    pub fn diff(&self, item: &Item) -> Result<()> {
        let mut identical = true;
        for file in item.files {
            let path = self.root.join(file.target);
            let Ok(local) = fs::read_to_string(&path) else {
                println!(
                    "{} is not in this project. Add it with `cargo hyuskui add {}`.",
                    file.target, item.name
                );
                continue;
            };
            if local == file.content {
                continue;
            }
            identical = false;
            let diff = TextDiff::from_lines(file.content, local.as_str());
            print!(
                "{}",
                diff.unified_diff()
                    .context_radius(3)
                    .header(&format!("registry/{}", file.target), &format!("local/{}", file.target))
            );
        }
        if identical {
            println!("{} matches the registry.", item.name);
        }
        Ok(())
    }

    /// Runs `cargo add` for the crates.io dependencies of `items` and everything they depend on,
    /// skipping crates the manifest already lists so a pinned version is never changed.
    pub fn add_crates(&self, items: &[&Item]) -> Result<()> {
        let manifest_path = self.root.join("Cargo.toml");
        let manifest = fs::read_to_string(&manifest_path).unwrap_or_default();
        let mut specs = Vec::new();
        for item in items {
            collect_crates(item, &mut specs);
        }
        specs.retain(|spec| !declares_dependency(&manifest, crate_name(spec)));
        if specs.is_empty() {
            return Ok(());
        }

        // Cargo sets $CARGO for subcommands, so this is the same toolchain that ran us.
        let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
        let status = std::process::Command::new(cargo)
            .arg("add")
            .arg("--manifest-path")
            .arg(&manifest_path)
            .args(&specs)
            .status()
            .context("running `cargo add`")?;
        if !status.success() {
            bail!("`cargo add {}` failed; run it yourself to finish the install", specs.join(" "));
        }
        Ok(())
    }

    pub fn check_gpui(&self) {
        let manifest = fs::read_to_string(self.root.join("Cargo.toml")).unwrap_or_default();
        if !declares_dependency(&manifest, "gpui") {
            println!(
                "\nnote: this crate does not depend on gpui yet. The components are tested against this \
                 Zed commit (build it with Rust {TESTED_RUST}):\n\n  \
                 gpui = {{ git = \"https://github.com/zed-industries/zed\", rev = \"{TESTED_ZED_REV}\" }}\n  \
                 gpui_platform = {{ git = \"https://github.com/zed-industries/zed\", rev = \"{TESTED_ZED_REV}\" }}"
            );
        }
    }

    fn crate_root(&self) -> Result<PathBuf> {
        for candidate in ["src/lib.rs", "src/main.rs"] {
            let path = self.root.join(candidate);
            if path.is_file() {
                return Ok(path);
            }
        }
        bail!("found neither src/lib.rs nor src/main.rs in {}", self.root.display())
    }

    fn write_new(&self, target: &str, content: &str, overwrite: bool) -> Result<()> {
        let path = self.root.join(target);
        if path.exists() && !overwrite {
            if fs::read_to_string(&path).is_ok_and(|existing| existing == content) {
                return Ok(());
            }
            println!("skipped {target}: it exists and differs from the registry (use --overwrite to replace it)");
            return Ok(());
        }
        let existed = path.exists();
        fs::create_dir_all(path.parent().unwrap())?;
        fs::write(&path, content).with_context(|| format!("writing {}", path.display()))?;
        println!("{} {target}", if existed { "replaced" } else { "added" });
        Ok(())
    }

    fn register_ui_module(&self, name: &str) -> Result<()> {
        let path = self.root.join("src/ui/mod.rs");
        let source = fs::read_to_string(&path).unwrap_or_else(|_| UI_MOD_HEADER.to_string());
        if declares_module(&source, name) {
            return Ok(());
        }
        let line = format!("pub mod {name};");

        // Keep a file of only comments and `pub mod` lines sorted; otherwise just append.
        let only_mods = source.lines().all(|l| {
            let l = l.trim();
            l.is_empty()
                || l.starts_with("//")
                || l.starts_with("#![")
                || (l.starts_with("pub mod ") && l.ends_with(';'))
        });
        let updated = if only_mods {
            let header: String = source
                .lines()
                .take_while(|l| !l.trim_start().starts_with("pub mod "))
                .map(|l| format!("{l}\n"))
                .collect();
            let mut mods: Vec<String> = source
                .lines()
                .filter(|l| l.trim_start().starts_with("pub mod "))
                .map(|l| l.trim().to_string())
                .chain([line])
                .collect();
            mods.sort();
            format!("{header}{}\n", mods.join("\n"))
        } else {
            format!("{}{}{line}\n", source, if source.ends_with('\n') { "" } else { "\n" })
        };
        fs::write(&path, updated)?;
        Ok(())
    }
}

fn collect_crates(item: &Item, out: &mut Vec<&'static str>) {
    for dependency in item.dependencies {
        if let Some(dep) = registry::find(dependency) {
            collect_crates(dep, out);
        }
    }
    for spec in item.crates {
        if !out.iter().any(|seen| crate_name(seen) == crate_name(spec)) {
            out.push(spec);
        }
    }
}

/// `sha3@0.10` -> `sha3`.
fn crate_name(spec: &str) -> &str {
    spec.split('@').next().unwrap_or(spec)
}

/// Whether a manifest line declares `name`, as `name = ...`, `name.workspace = true` or a
/// `[dependencies.name]` table. A line-level check, so it also counts dev and target deps.
fn declares_dependency(manifest: &str, name: &str) -> bool {
    manifest.lines().any(|line| {
        let line = line.trim();
        let key = line
            .strip_prefix('[')
            .and_then(|table| table.strip_suffix(']'))
            .and_then(|table| table.rsplit_once('.'))
            .map(|(section, key)| (section.ends_with("dependencies"), key));
        match key {
            Some((true, key)) => key.trim() == name,
            Some((false, _)) => false,
            None => line
                .strip_prefix(name)
                .is_some_and(|rest| rest.starts_with([' ', '=', '.', '\t'])),
        }
    })
}

fn declares_module(source: &str, name: &str) -> bool {
    source.lines().any(|line| {
        let line = line.trim();
        let line = line.strip_prefix("pub ").unwrap_or(line);
        let line = line.strip_prefix("pub(crate) ").unwrap_or(line);
        line == format!("mod {name};") || line.starts_with(&format!("mod {name} "))
    })
}

/// Inserts `mod name;` after any leading inner attributes and `//!` doc comments.
fn insert_module(source: &str, name: &str) -> String {
    let lines: Vec<&str> = source.lines().collect();
    let mut at = 0;
    while at < lines.len() {
        let line = lines[at].trim_start();
        if line.starts_with("#![") || line.starts_with("//!") {
            at += 1;
        } else {
            break;
        }
    }
    // Put it after other `mod` lines that directly follow the header, to keep them together.
    while at < lines.len() && lines[at].trim_start().starts_with("mod ") {
        at += 1;
    }
    let mut out: Vec<String> = lines[..at].iter().map(|l| l.to_string()).collect();
    if at > 0 && !lines[at - 1].trim_start().starts_with("mod ") && !lines[at - 1].trim().is_empty() {
        out.push(String::new());
    }
    out.push(format!("mod {name};"));
    if at < lines.len() && !lines[at].trim().is_empty() && !lines[at].trim_start().starts_with("mod ") {
        out.push(String::new());
    }
    out.extend(lines[at..].iter().map(|l| l.to_string()));
    let mut result = out.join("\n");
    if source.ends_with('\n') {
        result.push('\n');
    }
    result
}

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

    #[test]
    fn inserts_after_inner_attributes() {
        let source = "#![cfg_attr(target_family = \"wasm\", no_main)]\n\nuse gpui::App;\n";
        let out = insert_module(source, "theme");
        assert_eq!(
            out,
            "#![cfg_attr(target_family = \"wasm\", no_main)]\n\nmod theme;\n\nuse gpui::App;\n"
        );
    }

    #[test]
    fn groups_with_existing_mods() {
        let out = insert_module("mod app;\n\nfn main() {}\n", "theme");
        assert_eq!(out, "mod app;\nmod theme;\n\nfn main() {}\n");
    }

    #[test]
    fn detects_declared_dependencies() {
        let manifest = "[package]\nname = \"app\"\n\n[dependencies]\nsha3 = \"0.10\"\ngpui.workspace = true\n\n[dependencies.serde]\nversion = \"1\"\n";
        assert!(declares_dependency(manifest, "sha3"));
        assert!(declares_dependency(manifest, "gpui"));
        assert!(declares_dependency(manifest, "serde"));
        assert!(!declares_dependency(manifest, "sha"));
        assert!(!declares_dependency(manifest, "app"));
        assert!(!declares_dependency(manifest, "package"));
    }

    #[test]
    fn collects_crates_from_dependencies() {
        let onchain = registry::find("onchain").expect("registry has onchain");
        let mut specs = Vec::new();
        collect_crates(onchain, &mut specs);
        collect_crates(onchain, &mut specs);
        assert_eq!(specs, ["sha3@0.10"]);
        assert_eq!(crate_name("sha3@0.10"), "sha3");
    }

    #[test]
    fn detects_declared_modules() {
        assert!(declares_module("pub mod ui;\n", "ui"));
        assert!(declares_module("mod theme;\n", "theme"));
        assert!(!declares_module("mod theme_extra;\n", "theme"));
    }
}