pub mod macros;
pub mod path;
use anyhow::anyhow;
use colored::*;
use std::collections::HashMap;
use std::process::Command;
use std::{env, path::PathBuf};
fn append_pwd_to_pythonpath(runtime_path: &PathBuf) -> HashMap<String, String> {
let mut path = env::var("PYTHONPATH").unwrap_or_default();
if !path.contains(&runtime_path.to_string_lossy().to_string()) {
if !path.is_empty() {
path.push(':');
}
path.push_str(runtime_path.to_string_lossy().to_string().as_str());
}
HashMap::from([("PYTHONPATH".to_string(), path)])
}
pub fn set_additional_env_var(
additional_env_from_args: Vec<String>,
runtime_path: &PathBuf,
quiet: bool,
) -> HashMap<String, String> {
let mut additional_env = HashMap::new();
additional_env.extend(append_pwd_to_pythonpath(runtime_path));
for env_var in additional_env_from_args {
if let Some(pos) = env_var.find('=') {
let key = env_var[..pos].to_string();
let value = env_var[pos + 1..].to_string();
additional_env.insert(key.clone(), value.clone());
if !quiet {
println!("Setting env: {} = {}", key.bold(), value);
}
} else {
if !quiet {
warning_println!(
"Warning: Ignoring malformed environment variable: {}",
env_var.bold()
);
}
}
}
additional_env
}
pub fn validate_to_absolute_path(script_path: &PathBuf) -> anyhow::Result<PathBuf> {
match script_path.canonicalize() {
Ok(path) => {
if !path.exists() {
return Err(anyhow!("{} not exists", path.display().to_string().bold()));
}
Ok(path)
}
Err(err) => Err(anyhow!("Failed to get absolute path of script: {}", err)),
}
}
pub fn get_uv_path() -> anyhow::Result<String> {
#[cfg(not(target_os = "windows"))]
let find_executable = "which";
#[cfg(target_os = "windows")]
let find_executable = "where";
let output = Command::new(find_executable).arg("uv").output()?;
if output.status.success() {
let path = String::from_utf8(output.stdout)?.trim().to_string();
Ok(path)
} else {
eprintln!("Please run the following command to install uv:");
#[cfg(not(target_os = "windows"))]
eprintln!("wget -qO- https://astral.sh/uv/install.sh | sh");
#[cfg(target_os = "windows")]
eprintln!(
"powershell -ExecutionPolicy ByPass -c \"irm https://astral.sh/uv/install.ps1 | iex\""
);
Err(anyhow!("uv not installed"))
}
}
pub fn get_python_exec_path(venv_path: &PathBuf) -> PathBuf {
PathBuf::from(if cfg!(target_os = "windows") {
venv_path
.join("Scripts")
.join("python.exe")
.to_string_lossy()
.to_string()
} else {
venv_path
.join("bin")
.join("python")
.to_string_lossy()
.to_string()
})
}