hyuskui 0.0.5

Add hyuskui components to a GPUI project: cargo hyuskui add button
//! The root README is this crate's page on crates.io, and crates.io only shows a new README with a
//! new version. These tests fail CI when the README falls behind the registry, so a release can't
//! ship a stale page.

use std::path::Path;

use crate::registry;

fn repo_root() -> &'static Path {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("crates/hyuskui sits two levels below the repo root")
}

fn readme() -> String {
    std::fs::read_to_string(repo_root().join("README.md")).expect("README.md at the repo root")
}

#[test]
fn readme_counts_every_component() {
    let count = registry::components().count();
    let claim = format!("**{count} components**");
    assert!(
        readme().contains(&claim),
        "README.md should say {claim}: registry/ui has {count} components"
    );
}

#[test]
fn readme_links_every_component() {
    let readme = readme();
    let missing: Vec<_> = registry::components()
        .map(|item| item.name.replace('_', "-"))
        .filter(|slug| !readme.contains(&format!("https://ui.hyuskui.com/docs/components/{slug})")))
        .collect();
    assert!(
        missing.is_empty(),
        "README.md's Components list is missing: {missing:?}"
    );
}

/// The number of example files in `registry/examples/<dir>`, one per pattern.
fn patterns(dir: &str) -> usize {
    std::fs::read_dir(repo_root().join("registry/examples").join(dir))
        .unwrap_or_else(|_| panic!("registry/examples/{dir}"))
        .filter(|entry| {
            entry
                .as_ref()
                .is_ok_and(|e| e.path().extension().is_some_and(|x| x == "rs"))
        })
        .count()
}

#[test]
fn readme_counts_every_pattern() {
    let readme = readme();
    for (dir, section) in [("ai", "AI Elements"), ("crypto", "Crypto Elements")] {
        let count = patterns(dir);
        let line = readme
            .lines()
            .find(|line| line.contains(&format!("[{section}]")))
            .unwrap_or_else(|| panic!("README.md should link {section}"));
        assert!(
            line.contains(&format!("{count} patterns")),
            "README.md should say \"{count} patterns\" for {section}: registry/examples/{dir} has {count}"
        );
    }
}

/// crates.io can't resolve paths inside the repo, so a relative image or link shows up broken there.
#[test]
fn readme_links_are_absolute() {
    let readme = readme();
    let relative: Vec<_> = readme
        .match_indices("](")
        .map(|(ix, _)| &readme[ix + 2..])
        .map(|rest| &rest[..rest.find(')').unwrap_or(rest.len())])
        .filter(|target| !target.starts_with("https://") && !target.starts_with('#'))
        .collect();
    assert!(
        relative.is_empty(),
        "README.md has links crates.io can't follow: {relative:?}"
    );
}