hyuskui 0.0.1

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");
        }

        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 ["theme", "ui"] {
            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(())
    }

    pub fn add(&self, item: &Item, overwrite: bool) -> Result<()> {
        for dependency in item.dependencies {
            if let Some(dep) = registry::find(dependency).filter(|dep| dep.kind == "registry:ui") {
                self.add(dep, overwrite)?;
            }
        }
        for file in item.files {
            self.write_new(file.target, file.content, overwrite)?;
        }
        self.register_ui_module(item.name)
    }

    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(())
    }

    pub fn check_gpui(&self) {
        let manifest = fs::read_to_string(self.root.join("Cargo.toml")).unwrap_or_default();
        let has_gpui = manifest.lines().any(|line| {
            let line = line.trim_start();
            line.starts_with("gpui ") || line.starts_with("gpui=") || line.starts_with("gpui.")
        });
        if !has_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 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_modules() {
        assert!(declares_module("pub mod ui;\n", "ui"));
        assert!(declares_module("mod theme;\n", "theme"));
        assert!(!declares_module("mod theme_extra;\n", "theme"));
    }
}