Skip to content

TempDir: Provide an API to not delete-dir-on-drop without consuming the TempDir #31

@vincentdephily

Description

@vincentdephily

The current API offers into_path(self) -> PathBuf which is nice and clean (not sure why PathBuf instead of Path, but I can live with that), but forces you to decide ahead of time if you want a temporary or persisted path.

I'd like to change the behaviour at runtime, but am hitting the following snags:

  • If I call into_path() near the end of my scope, it might not get called because of asserts that triggered earlyer (precisely when I'd have liked to keep the tempdir).
  • If I call it at the beginning of my scope, I either run into PathBuf/TempDir type mismatches, or into temporary value does not live long enough problems:
let tempdir = TempDir::new().unwrap();
// Doesn't compile because of lifetime issues
let cwd = match std::env::var("ASSERTFS_KEEP_TEMP") {
    Ok(_) => tempdir.into_path().as_path(),
    Err(_) => tempdir.path(),
};
assert!(dostuff(cwd).is_ok());
// Too late: assert has fired already.
if std::env::var("ASSERTFS_KEEP_TEMP").is_ok() {
    tempdir.into_path();
}

Perhaps I missed an easy solution, but I doubt it would be as easy as having some kind of delete_on_drop(bool) API:

let tempdir = TempDir::new()
                      .unwrap()
                      .delete_on_drop(std::env::var("ASSERTFS_KEEP_TEMP").is_ok());
assert!(dostuff(cwd).is_ok());

Workaround

let tempdir = TempDir::new().unwrap();
let mut cwd = PathBuf::new();
match env::var("ASSERTFS_KEEP_TEMP") {
    Ok(_) => cwd.push(&tempdir.into_path()),
    Err(_) => cwd.push(tempdir.path()),
}
assert!(dostuff(cwd).is_ok());

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions