use std::io;
use std::path::{Path, PathBuf};
pub struct Private(PathBuf);
pub const SHORT_PARENT: &str = "/tmp";
impl Private {
pub fn make() -> io::Result<Self> {
let name = uuid::Uuid::new_v4().simple().to_string();
Self::make_at(&std::env::temp_dir(), &name)
}
pub fn make_for(agent: super::super::adapter::Agent) -> io::Result<Self> {
if agent != super::super::adapter::Agent::Cursor {
return Self::make();
}
let name = uuid::Uuid::new_v4().simple().to_string();
Self::make_at(Path::new(SHORT_PARENT), &name[..12])
}
fn make_at(parent: &Path, name: &str) -> io::Result<Self> {
use std::os::unix::fs::{DirBuilderExt, MetadataExt};
let dir = parent.join(format!("neosian-harness-{}-{name}", std::process::id()));
std::fs::DirBuilder::new().mode(0o700).create(&dir)?;
let made = Self::marked(dir, |dir| {
std::fs::write(dir.join(super::super::MARKER), "")
})?;
let found = made.0.symlink_metadata()?;
let own = found.uid() == super::cursor_run::uid() && found.mode() & 0o077 == 0;
if !found.is_dir() || !own {
return Err(io::Error::other(
"the private directory is not this user's own",
));
}
Ok(made)
}
pub fn marked(dir: PathBuf, mark: impl FnOnce(&Path) -> io::Result<()>) -> io::Result<Self> {
let made = Self(dir);
mark(&made.0)?;
Ok(made)
}
pub fn path(&self) -> &Path {
&self.0
}
}
impl Drop for Private {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}