use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
use std::path::Path;
use std::process::Command;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use tokio::sync::{Mutex, MutexGuard};
pub const RECV_TIMEOUT: Duration = Duration::from_secs(5);
pub fn http_json(status: &str, body: &str) -> String {
format!(
"HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
status,
body.len(),
body
)
}
pub fn spawn_seq(responses: Vec<String>) -> (String, mpsc::Receiver<String>) {
spawn_seq_with(move |_| responses)
}
pub fn spawn_seq_with<F>(build: F) -> (String, mpsc::Receiver<String>)
where
F: FnOnce(&str) -> Vec<String>,
{
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let base = format!("http://{addr}");
let responses = build(&base);
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
for response in responses {
let Ok((mut stream, _)) = listener.accept() else {
break;
};
let captured = read_request(&stream);
let _ = tx.send(captured);
let _ = stream.write_all(response.as_bytes());
let _ = stream.flush();
}
});
(base, rx)
}
fn read_request(stream: &std::net::TcpStream) -> String {
let mut reader = BufReader::new(stream.try_clone().expect("clone test socket"));
let mut request_line = String::new();
let _ = reader.read_line(&mut request_line);
let mut content_length = 0usize;
let mut headers: Vec<String> = Vec::new();
loop {
let mut header = String::new();
if reader.read_line(&mut header).unwrap_or(0) == 0 {
break;
}
let header = header.trim_end();
if header.is_empty() {
break;
}
if let Some(v) = header
.strip_prefix("Content-Length:")
.or_else(|| header.strip_prefix("content-length:"))
{
content_length = v.trim().parse().unwrap_or(0);
}
headers.push(header.to_string());
}
let mut body = vec![0u8; content_length];
if content_length > 0 {
let _ = reader.read_exact(&mut body);
}
format!(
"{} | {} | {}",
request_line.trim_end(),
headers.join("\n"),
String::from_utf8_lossy(&body)
)
}
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");
}