workdir 0.1.0

Tools for working with temporary work directories.
Documentation
//! Utility functions for working with "work directories".

//use std::env;
//use std::fs;
use std::path::Path;

pub mod dirswitch;
pub use dirswitch::DirSwitch;

pub mod tmpdir;
pub use tmpdir::TmpDir;


/*
pub trait Worker {
  type RetVal;
  type Error;
  fn work(&mut self) -> Result<Self::RetVal, Self::Error>;
}

/// Switch to a directory, call a closure, and switch back to previous
/// directory.
fn work_in_dir<P>(dir: P, handler: &dyn Worker) -> Result<(), std::io::Error>
where
  P: AsRef<Path>
{
  //
  // Switch to new directory
  //
  let old = env::current_dir()?;
  env::set_current_dir(dir.as_ref())?;

  //
  // Run worker
  //
  let ret = handler.work();

  //
  // Always return to previous directory
  //
  env::set_current_dir(old)?;

  Ok(())
}
*/


/*
/// Switch to a directory, call a closure, and switch back to previous
/// directory.
fn work_in_dir<P, F>(dir: P, f: F) -> Result<(), Error>
where
  P: AsRef<Path>,
  F: FnMut()
{
  //
  // Switch to new directory
  //
  let old = env::current_dir()?;
  env::set_current_dir(tmpdir.as_ref())?;

  //
  // Run closure
  //
  f();

  //
  // Always return to previous directory
  //
  env::set_current_dir(old)?;

  Ok(())
}
*/


/*
/// Create the specified temporary directory, switch to it, call closure,
/// switch back to previous directory and clean up temporary directory.
fn work_in_tmpdir(tmpdir: P, f: F) -> Result<(), Error>
where
  P: AsRef<Path>,
  F: FnMut()
{
  //
  // Croak if the work directory already exists
  //
  if tmpdir.as_ref().exists() {
    return Err(
      std::io::Error::new(
        std::io::ErrorKind::AlreadyExists,
        "work directory already exists"
      )
      .into()
    );
  }

  //
  // Create temporary directory
  //
  fs::create_dir_all(&dir)?;

  //
  // Remember current directory, and switch to temporary
  //
  let old = env::current_dir()?;
  env::set_current_dir(tmpdir.as_ref())?;

  //
  // Call closure
  //
  f();

  //
  // Return to previous directory
  //
  env::set_current_dir(old)?;

  fs::remove_dir_all(&self.dir)?;
}
*/


pub fn tmpwork<P, F>(workdir: P, handler: F) -> Result<(), std::io::Error>
where
  P: AsRef<Path>,
  F: FnOnce() -> Result<(), std::io::Error>
{
  let wd = TmpDir::mk(&workdir)?;
  let _ds = DirSwitch::switch(wd.path())?;

  handler()
}


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