use std::{env::temp_dir, fs, ops::Drop, os::unix::fs::PermissionsExt, path::PathBuf}; use uuid::Uuid; pub struct TempFile { path: PathBuf, } impl TempFile { pub fn get_path(&self) -> String { self.path.to_string_lossy().to_string() } pub fn new() -> Self { let name = Uuid::simple(&Uuid::new_v4()).to_string(); let mut path = temp_dir(); path.push(name); Self { path } } pub fn write_all(&self, data: &[u8]) -> Result<(), String> { fs::write(&self.path, data).map_err(|e| e.to_string()) } pub fn write_exec(data: &[u8]) -> Result { let this = Self::new(); let path = this.get_path(); this.write_all(data).map_err(|e| (path.clone(), e))?; let perms = fs::Permissions::from_mode(0o555); fs::set_permissions(&path, perms).map_err(|e| (path, e.to_string()))?; Ok(this) } } impl Drop for TempFile { fn drop(&mut self) { fs::remove_file(&self.path).ok(); } }