gritpack-searchlib 0.1.1

Compiler-facing resolver and grammar integration surface for Gritpack
Documentation
use std::path::{Path, PathBuf};

use crate::models::CliError;

const GRITPACK_HOME_ENV: &str = "GRITPACK_HOME";
pub(crate) const PROJECT_GRITPACK_DIR: &str = ".gritpack";

pub(crate) fn gritpack_root() -> Result<PathBuf, CliError> {
    if let Some(explicit_root) = std::env::var_os(GRITPACK_HOME_ENV) {
        return Ok(PathBuf::from(explicit_root));
    }

    let home = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .or_else(|| {
            let drive = std::env::var_os("HOMEDRIVE")?;
            let path = std::env::var_os("HOMEPATH")?;
            let mut combined = PathBuf::from(drive);
            combined.push(path);
            Some(combined.into_os_string())
        })
        .ok_or_else(|| {
            CliError::Message(format!(
                "could not determine a home directory; set {}",
                GRITPACK_HOME_ENV
            ))
        })?;

    Ok(PathBuf::from(home).join(".frogfish").join("gritpack"))
}

pub(crate) fn gritpack_cache_root() -> Result<PathBuf, CliError> {
    Ok(gritpack_root()?.join("cache"))
}

pub(crate) fn gritpack_store_root() -> Result<PathBuf, CliError> {
    Ok(gritpack_root()?.join("store"))
}

pub(crate) fn gritpack_bin_root() -> Result<PathBuf, CliError> {
    Ok(gritpack_root()?.join("bin"))
}

pub(crate) fn gritpack_state_root() -> Result<PathBuf, CliError> {
    Ok(gritpack_root()?.join("state"))
}

pub(crate) fn gritpack_certs_root() -> Result<PathBuf, CliError> {
    Ok(gritpack_root()?.join("certs"))
}

pub(crate) fn gritpack_tool_store_root() -> Result<PathBuf, CliError> {
    Ok(gritpack_store_root()?.join("tools"))
}

pub(crate) fn gritpack_env_store_root() -> Result<PathBuf, CliError> {
    Ok(gritpack_store_root()?.join("envs"))
}

pub(crate) fn project_gritpack_root(project_root: &Path) -> PathBuf {
    project_root.join(PROJECT_GRITPACK_DIR)
}

pub(crate) fn project_packages_root(project_root: &Path) -> PathBuf {
    project_gritpack_root(project_root).join("packages")
}

#[cfg(test)]
pub(crate) fn path_contains(candidate: &Path) -> bool {
    std::env::var_os("PATH")
        .map(|paths| std::env::split_paths(&paths).any(|path| path == candidate))
        .unwrap_or(false)
}