Stebalien / tempfile

Temporary file library for rust
http://stebalien.com/projects/tempfile-rs
Apache License 2.0
1.15k stars 113 forks source link

Get the path to a tempfile #267

Closed dvdsk closed 9 months ago

dvdsk commented 9 months ago

I am writing test code where I need to load in a (large) file for multiple tests. As I am doing tdd the tests are going to fail/crash a lot. tempfile is great as it shifts the responsibility of closing the file to the OS.

This is what I would like to write:

fn gen_file_if_not_there() -> PathBuf {
    static PATH: Mutex<Option<(File, PathBuf)>> = Mutex::new(None);

    if let Some((_, path)) = *PATH.lock().unwrap() {
        return path;
    }

    let mut tmp_file: File = tempfile::tempfile().unwrap();
    let path: PathBuf = unimplemented!("get the path for tmp_file");

    todo!("fill the file with specific test data")
    *PATH.lock().unwrap() = (tmp_file, path.clone());
    path
}

I can not use it however since I need the path to the file.

The docs state tempfile() does not rely on paths, on the other hand tempfile_in() exists so it seems like there is some control over the file's path.

Would it be possible to get that same OS driven cleanup while also exposing the file's path?

Stebalien commented 9 months ago

Unfortunately, no (at least on Linux, macOS, etc.). Tempfile cleanup works by immediately unlinking (deleting) the file in question, which means it has no path.

tempfile_in exists so you can create the temporary file in a specific filesystem.