1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
//! 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 :