use crate::error::Result;
use std::{
env, fs, ops::Deref,
path::{ Path, PathBuf }
};
#[derive(Debug)]
pub struct Tempdir {
path: PathBuf
}
impl Tempdir {
pub(in crate::packagedir) fn with_path<T>(path: T) -> Result<Self> where T: AsRef<Path> {
let path = path.as_ref().to_path_buf();
if !path.is_dir() {
Err(eio!("No such directory: {:?}", path))?;
}
Ok(Self { path })
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for Tempdir {
fn drop(&mut self) {
if let Err(err) = fs::remove_dir_all(&self.path) {
eprintln!("Failed to delete temp directory: {:?} ({})", &self.path, err);
}
}
}
pub struct Packagedir {
path: PathBuf
}
impl Packagedir {
pub fn new() -> Result<Self> {
let home = env::var("HOME").map_err(|e| eio!("Failed to get home directory ({})", e))?;
let path = Path::new(&home).join(".ezinstall");
Self::with_path(path)
}
pub fn with_path<T>(path: T) -> Result<Self> where T: AsRef<Path> {
let path = path.as_ref().to_path_buf();
if !path.is_dir() {
fs::create_dir_all(&path)?;
}
Ok(Self { path })
}
pub fn tempdir(&self) -> Result<Tempdir> {
let tempdir_path = self.path.join("tempdir");
if tempdir_path.is_dir() {
fs::remove_dir_all(&tempdir_path)?;
}
fs::create_dir(&tempdir_path)?;
Tempdir::with_path(tempdir_path)
}
}
impl AsRef<Path> for Packagedir {
fn as_ref(&self) -> &Path {
&self.path
}
}
impl Deref for Packagedir {
type Target = Path;
fn deref(&self) -> &Self::Target {
&self.path
}
}