use std::path::{Path, PathBuf};
use tokio::{fs::File as TokioFile, io::AsyncWriteExt};
use uuid::Uuid;
#[derive(Debug)]
pub struct TempFile {
pub path: PathBuf,
dir: tempfile::TempDir,
}
impl TempFile {
pub async fn new(content: &str) -> Self {
let random_name = format!("{}.txt", Uuid::new_v4());
Self::with_name(random_name.as_str(), content).await
}
pub fn empty() -> Self {
let dir = tempfile::TempDir::new().expect("Failed to create temp dir");
let random_name = format!("{}.txt", Uuid::new_v4());
let path = dir.path().join(random_name);
Self { dir, path }
}
pub async fn with_name(name: &str, content: &str) -> Self {
let dir = tempfile::TempDir::new().expect("Failed to create temp dir");
let path = dir.path().join(name);
let mut file = TokioFile::create(&path)
.await
.expect("Failed to create file");
file.write_all(content.as_bytes())
.await
.expect("Failed to write");
file.flush().await.expect("Failed to flush");
drop(file);
Self { dir, path }
}
pub async fn from_bytes(name: &str, bytes: &[u8]) -> Self {
let dir = tempfile::TempDir::new().expect("Failed to create temp dir");
let path = dir.path().join(name);
let mut file = TokioFile::create(&path)
.await
.expect("Failed to create file");
file.write_all(bytes).await.expect("Failed to write");
file.flush().await.expect("Failed to flush");
drop(file);
Self { dir, path }
}
pub fn file_name(&self) -> &str {
self.path
.file_name()
.and_then(|n| n.to_str())
.expect("Invalid file name")
}
pub fn dir_path(&self) -> &Path {
self.dir.path()
}
}