workdir 0.1.0

Tools for working with temporary work directories.
Documentation
use std::fs;
use std::path::{Path, PathBuf};

/// RIIA temporary working directory.
///
/// Creating an instance of this represents a directory and dropping it
/// represents removing it.
///
/// # Platform considerations
/// Some platforms protect directories from removal while a process is using
/// the directory.  Make sure the process is not using the directory when the
/// `Drop` handler is run.
pub struct TmpDir {
  dir: PathBuf,
  autoremove: bool
}

impl TmpDir {
  /// Create a new temporary work directory.
  ///
  /// An error is returned if the directory already exists.
  pub fn mk<P: AsRef<Path>>(wd: P) -> Result<Self, std::io::Error> {
    let workdir = wd.as_ref();
    if workdir.exists() {
      return Err(
        std::io::Error::new(
          std::io::ErrorKind::AlreadyExists,
          "work directory  already exists"
        )
        .into()
      );
    }
    fs::create_dir_all(workdir)?;
    Ok(Self {
      dir: workdir.into(),
      autoremove: true
    })
  }

  /// Get a reference to the path that this object represents.
  pub fn path(&self) -> &Path {
    self.dir.as_ref()
  }


  /// Request to keep the work dir.
  pub fn keep(&mut self) {
    self.autoremove = false;
  }
}

impl Drop for TmpDir {
  fn drop(&mut self) {
    if self.autoremove {
      if let Err(e) = fs::remove_dir_all(&self.dir) {
        eprintln!("Unable to remove temporary work directory; {}", e);
      }
    }
  }
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :