Skip to content

Commit

Permalink
Add docs pointing out early dop pitfalls
Browse files Browse the repository at this point in the history
This commit adds a section to the `src/libs.rs` docs
pointing out an easily encounterable error when
ussing `tempdir()` with apis that are generic over
`AsRef<Path>`, like `Command::current_dir`, resulting
in the directory being dropped to early (As pointed out in Stebalien#115).
  • Loading branch information
robinwilliam.hundt committed Feb 15, 2020
1 parent 3f8b97f commit d1df0d2
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,39 @@
//! rely on file paths for _some_ operations. See the security documentation on
//! the `NamedTempFile` type for more information.
//!
//! ## Early drop pitfall
//! Because `TempDir` and `NamedTempFile` rely on their destructors for cleanup, this can lead
//! to an unexpected early removal of the directory/file, usually when working with APIs which are
//! generic over `AsRef<Path>`. Consider the following example:
//!
//! ```
//! # use tempfile::tempdir;
//! # use std::io;
//! # use std::process::Command;
//! # fn main() {
//! # if let Err(_) = run() {
//! # ::std::process::exit(1);
//! # }
//! # }
//! # fn run() -> Result<(), io::Error> {
//! // Create a directory inside of `std::env::temp_dir()`.
//! let temp_dir = tempdir()?;
//! // Spawn the `touch` command inside the temporary directory and collect the exit status
//! // Note that `temp_dir` is **not** moved into `current_dir`, but passed as a reference
//! let exit_status = Command::new("touch").arg("tmp").current_dir(&temp_dir).status()?;
//! assert!(exit_status.success());
//!
//! # Ok(())
//! # }
//! ```
//! This works because a reference to `temp_dir` is passed to `current_dir`, resulting in the
//! destructor of `temp_dir` being run after the `Command` has finished execution. Moving the
//! `TempDir` into the `current_dir` call would result in the `TempDir` being converted into
//! an internal representation, with the original value being dropped and the directory thus
//! being deleted, before the command can be executed.
//! The `touch` command would fail with an `No such file or directory` error.
//!
//!
//! ## Examples
//!
//! Create a temporary file and write some data into it:
Expand Down

0 comments on commit d1df0d2

Please sign in to comment.