pray-core 1.27.0

Prayfile core library — package manager for the language placed before inference
Documentation
mod cargo;

use crate::resolve_context::ResolveOptions;
use crate::{PrayError, PrayResult};
pub(crate) use cargo::CargoPackages;
use std::path::{Path, PathBuf};
use std::process::Command;

pub const DEFAULT_HOST_PRAYERS_SUBDIR: &str = "prayers";

pub const HOST_SOURCE_KINDS: &[&str] = &["gem", "npm", "crate", "hex", "pypi"];

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostPackageLocation {
    pub install_root: PathBuf,
    pub version: Option<String>,
}

pub fn is_host_source_kind(kind: &str) -> bool {
    HOST_SOURCE_KINDS.contains(&kind)
}

pub fn host_manager_keywords() -> &'static [&'static str] {
    HOST_SOURCE_KINDS
}

pub fn validate_host_package_name(kind: &str, name: &str) -> PrayResult<()> {
    fn valid_segment(segment: &str) -> bool {
        segment
            .bytes()
            .next()
            .is_some_and(|first| first.is_ascii_alphanumeric() || first == b'_')
            && !segment.ends_with('.')
            && segment
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
    }
    let valid = if let Some(scoped) = name.strip_prefix('@').filter(|_| kind == "npm") {
        scoped
            .split_once('/')
            .is_some_and(|(scope, package)| valid_segment(scope) && valid_segment(package))
    } else {
        valid_segment(name)
    };
    if valid {
        return Ok(());
    }
    Err(PrayError::Parse {
        kind: "manifest",
        message: format!("{kind}: invalid package name"),
    })
}

pub fn validate_host_subdir(subdir: &str) -> PrayResult<()> {
    if subdir.trim().is_empty()
        || subdir.starts_with('/')
        || subdir.contains(['\\', ':', '"', '<', '>', '|', '?', '*'])
        || subdir.bytes().any(|byte| byte < b' ')
        || subdir
            .split('/')
            .any(|part| part != "." && part.ends_with(['.', ' ']))
    {
        return Err(PrayError::Parse {
            kind: "manifest",
            message: "subdir must be a portable relative path".to_string(),
        });
    }
    Ok(())
}

pub(crate) fn locate_host_package(
    project_root: &Path,
    kind: &str,
    package_name: &str,
    options: &ResolveOptions,
    cargo_packages: &mut Option<CargoPackages>,
) -> PrayResult<HostPackageLocation> {
    validate_host_package_name(kind, package_name)?;
    let key = (kind.to_string(), package_name.to_string());
    if let Some(override_location) = options.host_packages.get(&key) {
        return Ok(override_location.clone());
    }
    match kind {
        "gem" => probe_gem(project_root, package_name),
        "npm" => probe_npm(project_root, package_name),
        "crate" => cargo::locate(project_root, package_name, cargo_packages),
        "hex" => probe_hex(project_root, package_name),
        "pypi" => probe_pypi(project_root, package_name),
        _ => Err(PrayError::Unsupported(format!(
            "source kind {kind} is not a host package locator"
        ))),
    }
}

pub fn host_prayers_directory(
    location: &HostPackageLocation,
    kind: &str,
    package_name: &str,
    subdir: Option<&str>,
) -> PrayResult<PathBuf> {
    let relative = subdir.unwrap_or(DEFAULT_HOST_PRAYERS_SUBDIR);
    validate_host_subdir(relative)?;
    let label = format!("{kind} package {package_name} prayers directory");
    let directory =
        crate::source_path::declared_directory(&location.install_root, relative, &label)?;
    if !directory.is_dir() {
        return Err(PrayError::Resolution(format!(
            "{label} was not found: {relative}"
        )));
    }
    Ok(directory)
}

fn probe_gem(project_root: &Path, package_name: &str) -> PrayResult<HostPackageLocation> {
    let gemfile = project_root
        .ancestors()
        .find_map(|directory| {
            ["Gemfile", "gems.rb"]
                .map(|name| directory.join(name))
                .into_iter()
                .find(|path| path.is_file())
        })
        .ok_or_else(|| missing_host_package("gem", package_name))?;
    let output = Command::new("bundle")
        .args(["info", package_name])
        .env("BUNDLE_GEMFILE", gemfile)
        .env("BUNDLE_FROZEN", "true")
        .current_dir(project_root)
        .output()
        .map_err(|_| missing_host_package("gem", package_name))?;
    if !output.status.success() {
        return Err(missing_host_package("gem", package_name));
    }
    let text = String::from_utf8_lossy(&output.stdout);
    let path = text
        .lines()
        .rev()
        .find_map(|line| line.strip_prefix("\tPath: "))
        .ok_or_else(|| missing_host_package("gem", package_name))?;
    let heading = format!("* {package_name} (");
    let version = text.lines().find_map(|line| {
        line.trim()
            .strip_prefix(&heading)?
            .strip_suffix(')')?
            .split_whitespace()
            .next()
            .map(str::to_string)
    });
    let install_root = PathBuf::from(path);
    if !install_root.is_absolute() || !install_root.is_dir() {
        return Err(missing_host_package("gem", package_name));
    }
    Ok(HostPackageLocation {
        install_root,
        version,
    })
}

fn metadata_field<'a>(text: &'a str, label: &str) -> Option<&'a str> {
    text.lines()
        .filter_map(|line| line.trim_start().strip_prefix(label))
        .map(str::trim)
        .find(|value| !value.is_empty())
}

fn probe_npm(project_root: &Path, package_name: &str) -> PrayResult<HostPackageLocation> {
    let candidate = project_root.join("node_modules").join(package_name);
    if candidate.is_dir() {
        let version = read_npm_version(&candidate);
        return Ok(HostPackageLocation {
            install_root: candidate,
            version,
        });
    }
    Err(missing_host_package("npm", package_name))
}

fn read_npm_version(package_root: &Path) -> Option<String> {
    let text = std::fs::read_to_string(package_root.join("package.json")).ok()?;
    let value: serde_json::Value = serde_json::from_str(&text).ok()?;
    value.get("version")?.as_str().map(str::to_string)
}

fn probe_hex(project_root: &Path, package_name: &str) -> PrayResult<HostPackageLocation> {
    let candidate = project_root.join("deps").join(package_name);
    if candidate.is_dir() {
        return Ok(HostPackageLocation {
            install_root: candidate,
            version: None,
        });
    }
    Err(missing_host_package("hex", package_name))
}

fn probe_pypi(project_root: &Path, package_name: &str) -> PrayResult<HostPackageLocation> {
    let output = Command::new("pip")
        .args(["show", package_name])
        .current_dir(project_root)
        .output()
        .map_err(|_| missing_host_package("pypi", package_name))?;
    if !output.status.success() {
        return Err(missing_host_package("pypi", package_name));
    }
    let text = String::from_utf8_lossy(&output.stdout);
    let location = metadata_field(&text, "Location:")
        .filter(|value| Path::new(value).is_absolute())
        .ok_or_else(|| missing_host_package("pypi", package_name))?;
    let version = metadata_field(&text, "Version:").map(str::to_string);
    let module = package_name
        .split(['-', '_', '.'])
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join("_")
        .to_ascii_lowercase();
    let install_root = Path::new(location).join(module);
    if !install_root.is_dir() {
        return Err(missing_host_package("pypi", package_name));
    }
    Ok(HostPackageLocation {
        install_root,
        version,
    })
}

fn missing_host_package(kind: &str, package_name: &str) -> PrayError {
    PrayError::Resolution(format!(
        "{kind} package {package_name} was not found in the project install tree"
    ))
}

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

    #[test]
    fn accepts_relative_subdir() {
        validate_host_subdir("prayers").expect("default");
        validate_host_subdir("guidance/extra").expect("nested");
    }

    #[test]
    fn rejects_unsafe_subdir() {
        assert!(validate_host_subdir("").is_err());
        assert!(validate_host_subdir("/abs").is_err());
        assert!(validate_host_subdir("../escape").is_err());
    }

    #[test]
    fn override_wins_over_probe() {
        let mut options = ResolveOptions::default();
        options.host_packages.insert(
            ("gem".to_string(), "demo".to_string()),
            HostPackageLocation {
                install_root: PathBuf::from("/tmp/demo-gem"),
                version: Some("1.2.3".to_string()),
            },
        );
        let located = locate_host_package(Path::new("."), "gem", "demo", &options, &mut None)
            .expect("override");
        assert_eq!(located.install_root, PathBuf::from("/tmp/demo-gem"));
        assert_eq!(located.version.as_deref(), Some("1.2.3"));
    }
}