You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.0 KiB

3 years ago
use crate::{UError, UResult};
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 }
}
3 years ago
pub fn write_all(&self, data: &[u8]) -> UResult<()> {
fs::write(&self.path, data).map_err(|e| UError::FSError(self.get_path(), e.to_string()))?;
Ok(())
}
3 years ago
pub fn write_exec(data: &[u8]) -> UResult<Self> {
let this = Self::new();
let path = this.get_path();
3 years ago
this.write_all(data)?;
let perms = fs::Permissions::from_mode(0o555);
3 years ago
fs::set_permissions(&path, perms).map_err(|e| UError::FSError(path, e.to_string()))?;
Ok(this)
}
}
impl Drop for TempFile {
fn drop(&mut self) {
fs::remove_file(&self.path).ok();
}
}