Skip to content

Instantly share code, notes, and snippets.

@ben0x539
Created June 24, 2015 18:56
Show Gist options
  • Save ben0x539/367db7cf3bdd6ee45d8f to your computer and use it in GitHub Desktop.
Save ben0x539/367db7cf3bdd6ee45d8f to your computer and use it in GitHub Desktop.
fn with_current_dir<F, T>(path: &Path, f: F) -> std::io::Result<T>
where F: FnOnce() -> T {
let previous_dir = try!(current_dir());
let rewind = || {
match set_current_dir(&previous_dir) {
Err(e) => {
let _ = set_current_dir("/");
let _ = writeln!(
&mut stderr(),
"couldn't chdir back to {:?}: {:?}",
previous_dir, e);
}
_ => ()
}
};
try!(set_current_dir(path));
let r: T = f.finally(rewind);
Ok(r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment