mod error;
use std::env;
use std::path::{Path, PathBuf};
use xshell::PushEnv;
pub use xshell::Shell;
pub use error::{Error, Result};
macro_rules! cmd {
($sh:expr, $cmd:literal) => {{
xshell::cmd!($sh, $cmd).env_remove("PYTHONHOME")
}};
}
pub struct VirtualEnv<'a> {
shell: &'a Shell,
_env: Vec<PushEnv<'a>>,
}
fn guess_python(sh: &Shell) -> Result<&'static str, Error> {
#[cfg(windows)]
{
if xshell::cmd!(sh, "python3.exe --version").run().is_ok() {
return Ok("python3.exe");
}
if let Ok(output) = xshell::cmd!(sh, "python.exe --version").read() {
if output.contains("Python 3.") {
return Ok("python.exe");
}
}
}
if xshell::cmd!(sh, "python3 --version").run().is_ok() {
return Ok("python3");
}
if let Ok(output) = xshell::cmd!(sh, "python --version").read() {
if output.contains("Python 3.") {
return Ok("python");
}
}
Err("couldn't find Python 3 in $PATH".into())
}
fn create_venv(sh: &Shell, path: &Path) -> Result<(), Error> {
let pybin = path.join("bin").join("python");
if !pybin.exists() {
let python = guess_python(sh)?;
xshell::cmd!(sh, "{python} -m venv {path}").run()?;
}
Ok(())
}
fn find_directory(name: &str) -> PathBuf {
#[allow(clippy::never_loop)]
let mut venv_dir = loop {
if let Ok(target_dir) = env::var("CARGO_TARGET_DIR") {
break PathBuf::from(target_dir);
}
if let Ok(out_dir) = env::var("OUT_DIR") {
let path = Path::new(&out_dir);
let path = path
.parent()
.and_then(|p| p.parent())
.and_then(|p| p.parent());
if let Some(out_dir) = path {
break PathBuf::from(out_dir);
}
}
if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
let mut p = PathBuf::from(manifest_dir);
p.push("target");
break p;
}
break env::temp_dir();
};
let name = format!("venv-{name}");
venv_dir.push(&name);
venv_dir
}
impl<'a> VirtualEnv<'a> {
pub fn new(shell: &'a Shell, name: &str) -> Result<VirtualEnv<'a>, Error> {
let venv_dir = find_directory(name);
Self::with_path(shell, &venv_dir)
}
pub fn with_path(shell: &'a Shell, venv_dir: &Path) -> Result<VirtualEnv<'a>, Error> {
create_venv(shell, venv_dir)?;
let path = env::var("PATH").unwrap_or_else(|_| "/bin:/usr/bin".to_string());
let path = format!("{}/bin:{}", venv_dir.display(), path);
let mut env = vec![];
env.push(shell.push_env("VIRTUAL_ENV", format!("{}", venv_dir.display())));
env.push(shell.push_env("PATH", path));
Ok(VirtualEnv { shell, _env: env })
}
pub fn pip_install(&self, package: &str) -> Result<()> {
cmd!(self.shell, "pip3 install {package}").run()?;
Ok(())
}
pub fn pip_upgrade(&self, package: &str) -> Result<()> {
cmd!(self.shell, "pip3 install --upgrade {package}").run()?;
Ok(())
}
pub fn run(&self, code: &str) -> Result<String> {
let py = cmd!(self.shell, "python");
Ok(py.stdin(code).read()?)
}
pub fn run_module(&self, module: &str, args: &[&str]) -> Result<String> {
let py = cmd!(self.shell, "python -m {module} {args...}");
Ok(py.read()?)
}
}
#[cfg(all(unix, test))]
mod test {
use super::*;
#[test]
fn multiple_venv() {
let sh = Shell::new().unwrap();
let script = "import sys; print(sys.prefix)";
let venv1 = VirtualEnv::new(&sh, "multiple_venv-1").unwrap();
let out1 = venv1.run(script).unwrap();
let venv2 = VirtualEnv::new(&sh, "multiple_venv-2").unwrap();
let out2 = venv2.run(script).unwrap();
assert_ne!(out1, out2);
}
#[test]
fn deactivate_on_drop() {
let sh = Shell::new().unwrap();
let script = "import sys; print(sys.prefix == sys.base_prefix)";
let out = cmd!(sh, "python3 -c {script}").read().unwrap();
assert_eq!("True", out);
{
let venv = VirtualEnv::new(&sh, "deactivate_on_drop").unwrap();
let out = venv.run(script).unwrap();
assert_eq!("False", out);
}
let out = cmd!(sh, "python3 -c {script}").read().unwrap();
assert_eq!("True", out);
}
}