conda-build/src/lib.rs

Tue, 12 May 2026 20:44:45 -0500

author
Tuomo Valkonen <tuomov@iki.fi>
date
Tue, 12 May 2026 20:44:45 -0500
changeset 7
733ae1911a97
parent 3
c3a4f4bb87f7
permissions
-rw-r--r--

README arXiv link

//use anyhow::bail;
//use regex::Regex;
pub use python_config::{Error as PyCError, PythonConfig};
use std::env;
use std::ffi::OsString;
use std::path::PathBuf;
//use std::process::Command;

/// Adds CONDA_PREFIX/lib/pkgconfig/ to PKG_CONFIG_PATH
pub fn pkgconfig_conda() -> Result<Option<PathBuf>, anyhow::Error> {
    if let Some(conda_root_) = option_env!("CONDA_PREFIX") {
        let conda_root = PathBuf::from(conda_root_);
        let conda_pkgconfig = conda_root.join("lib/pkgconfig/");

        // Prepend CONDA_PREFIX to any existing PKG_CONFIG_PATH
        let new_path = match option_env!("PKG_CONFIG_PATH") {
            Some(path) => {
                let mut paths = env::split_paths(&path).collect::<Vec<_>>();
                paths.insert(0, conda_pkgconfig);
                env::join_paths(paths)?
            }
            None => conda_pkgconfig.into(),
        };

        // Set the environment variable
        unsafe {
            env::set_var("PKG_CONFIG_PATH", &new_path);
        }

        Ok(Some(conda_root))
    } else {
        Ok(None)
    }
}

/// Looks up conda Python
pub fn python_conda() -> Option<OsString> {
    option_env!("CONDA_PREFIX").and_then(|conda_prefix| {
        let py = PathBuf::from(conda_prefix).join("bin/python");
        if py.exists() {
            Some(py.into())
        } else {
            None
        }
    })
}

/// Returns a the python configuration and indication whether it's from Conda
pub fn python_config() -> (
    Result<PythonConfig, PyCError>,
    Option<PathBuf>,
    Option<&'static str>,
) {
    if let Some(py) = option_env!("VIRTUAL_ENV") {
        let interp = PathBuf::from(py).join("bin/python");
        (
            PythonConfig::interpreter(interp),
            Some(py.into()),
            Some("venv"),
        )
    } else if let Some(py) = python_conda() {
        (PythonConfig::interpreter(py), None, Some("conda"))
    } else {
        (Ok(PythonConfig::new()), None, None)
    }
}

/*
/// Looks up python includes given executable
pub fn python_includes(mut py: OsString) -> Result<Vec<String>, anyhow::Error> {
    py.push("3-config");
    let output = Command::new(&py).args(["--includes"]).output()?;
    if !output.status.success() {
        bail!("Failed to run {}.", py.display())
    }
    let re = Regex::new(r"\w+-I\w*").unwrap();
    let includes = re
        .split(format!(" {}", String::from_utf8(output.stdout)?).as_str())
        .map(String::from)
        .collect();
    Ok(includes)
}
*/

mercurial