use std::{io, process::Command};
use camino::{Utf8Path, Utf8PathBuf};
use cap_std::{ambient_authority, fs_utf8::Dir};
use tempfile::TempDir;
pub fn utf8(path: &std::path::Path) -> io::Result<&Utf8Path> {
Utf8Path::from_path(path).ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("non-UTF-8 temporary path: {}", path.display()),
)
})
}
pub fn open_dir(dir: &Utf8Path) -> io::Result<Dir> {
Dir::open_ambient_dir(dir, ambient_authority())
}
pub fn manifest_dir() -> Utf8PathBuf { Utf8PathBuf::from(env!("CARGO_MANIFEST_DIR")) }
pub fn script_path() -> Utf8PathBuf { manifest_dir().join("scripts/check-static-regexes.sh") }
pub fn fixture(label: &str) -> io::Result<String> {
let relative = format!("tests/data/static_regex/{label}.rs.txt");
open_dir(&manifest_dir())?.read_to_string(&relative)
}
pub fn scan_dir_with(label: &str) -> io::Result<TempDir> {
let dir = TempDir::new()?;
open_dir(utf8(dir.path())?)?.write(format!("{label}.rs"), fixture(label)?)?;
Ok(dir)
}
pub fn run_guard(scan_dir: &Utf8Path, rg: Option<&str>) -> io::Result<std::process::Output> {
let mut cmd = Command::new(script_path());
cmd.arg(scan_dir).current_dir(scan_dir);
match rg {
Some(rg) => cmd.env("RG", rg),
None => cmd.env_remove("RG"),
};
cmd.output()
}