use std::path::Path;
use std::process::Command;
use tokio::sync::{Mutex, MutexGuard};
static ENV_MUTATION_LOCK: Mutex<()> = Mutex::const_new(());
pub async fn lock_env_mutation() -> MutexGuard<'static, ()> {
ENV_MUTATION_LOCK.lock().await
}
pub fn lock_env_mutation_sync() -> MutexGuard<'static, ()> {
ENV_MUTATION_LOCK.blocking_lock()
}
pub struct EnvVarGuard {
prev: Vec<(String, Option<String>)>,
}
impl Default for EnvVarGuard {
fn default() -> Self {
Self::new()
}
}
impl EnvVarGuard {
pub fn new() -> Self {
Self { prev: Vec::new() }
}
pub fn set(&mut self, key: &str, val: impl AsRef<std::ffi::OsStr>) {
self.prev.push((key.to_string(), std::env::var(key).ok()));
unsafe {
std::env::set_var(key, val);
}
}
pub fn remove(&mut self, key: &str) {
self.prev.push((key.to_string(), std::env::var(key).ok()));
unsafe {
std::env::remove_var(key);
}
}
}
impl Drop for EnvVarGuard {
fn drop(&mut self) {
for (k, v) in self.prev.drain(..).rev() {
unsafe {
match v {
Some(val) => std::env::set_var(&k, val),
None => std::env::remove_var(&k),
}
}
}
}
}
pub fn init_git_repo(dir: &Path) {
let ok = Command::new("git")
.args(["-C", &dir.to_string_lossy(), "init"])
.status()
.expect("git init failed")
.success();
assert!(ok, "git init must succeed");
for (key, val) in [("user.email", "test@example.com"), ("user.name", "Test")] {
Command::new("git")
.args(["-C", &dir.to_string_lossy(), "config", key, val])
.status()
.expect("git config failed");
}
let ok = Command::new("git")
.args([
"-C",
&dir.to_string_lossy(),
"commit",
"--allow-empty",
"-m",
"init",
])
.status()
.expect("git commit failed")
.success();
assert!(ok, "init commit must succeed");
}
pub fn add_worktree(repo_dir: &Path, wt_dir: &Path) {
let ok = Command::new("git")
.args([
"-C",
&repo_dir.to_string_lossy(),
"worktree",
"add",
"--detach",
&wt_dir.to_string_lossy(),
])
.status()
.expect("git worktree add failed")
.success();
assert!(ok, "git worktree add must succeed");
}