diff options
Diffstat (limited to 'vendor/tempdir')
-rw-r--r-- | vendor/tempdir/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | vendor/tempdir/Cargo.toml | 34 | ||||
-rw-r--r-- | vendor/tempdir/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | vendor/tempdir/LICENSE-MIT | 25 | ||||
-rw-r--r-- | vendor/tempdir/README.md | 62 | ||||
-rw-r--r-- | vendor/tempdir/appveyor.yml | 17 | ||||
-rw-r--r-- | vendor/tempdir/src/lib.rs | 360 | ||||
-rw-r--r-- | vendor/tempdir/tests/smoke.rs | 229 |
8 files changed, 929 insertions, 0 deletions
diff --git a/vendor/tempdir/.cargo-checksum.json b/vendor/tempdir/.cargo-checksum.json new file mode 100644 index 0000000..fff1235 --- /dev/null +++ b/vendor/tempdir/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"62067fea435000c8f0eced94d7d7737602f4616e8fe7c384e2b0f96ae1536a71","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"037867e0346ff775991de78c76c80b62bea8c86b3b9076edef00af18d74f7bfd","appveyor.yml":"da991211b72fa6f231af7adb84c9fb72f5a9131d1c0a3d47b8ceffe5a82c8542","src/lib.rs":"3db9d19cdb313e5b303f9969468b62f050a0b7f69c35a162f3af0b38c3d54575","tests/smoke.rs":"f10712bc24cc693b8300b90b8b014f2880106a58bdf891075b44344170c3a63b"},"package":"15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8"}
\ No newline at end of file diff --git a/vendor/tempdir/Cargo.toml b/vendor/tempdir/Cargo.toml new file mode 100644 index 0000000..599480b --- /dev/null +++ b/vendor/tempdir/Cargo.toml @@ -0,0 +1,34 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "tempdir" +version = "0.3.7" +authors = ["The Rust Project Developers"] +description = "A library for managing a temporary directory and deleting all contents when it's\ndropped.\n" +homepage = "https://github.com/rust-lang/tempdir" +documentation = "https://doc.rust-lang.org/tempdir" +readme = "README.md" +keywords = ["fs", "file", "filesystem"] +categories = ["filesystem"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-lang/tempdir" +[dependencies.rand] +version = "0.4" + +[dependencies.remove_dir_all] +version = "0.5" +[badges.appveyor] +repository = "rust-lang-libs/tempdir" + +[badges.travis-ci] +repository = "rust-lang-nursery/tempdir" diff --git a/vendor/tempdir/LICENSE-APACHE b/vendor/tempdir/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/vendor/tempdir/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/tempdir/LICENSE-MIT b/vendor/tempdir/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/vendor/tempdir/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/vendor/tempdir/README.md b/vendor/tempdir/README.md new file mode 100644 index 0000000..dd81db0 --- /dev/null +++ b/vendor/tempdir/README.md @@ -0,0 +1,62 @@ +tempdir +======= + +A Rust library for creating a temporary directory and deleting its entire +contents when the directory is dropped. + +[![Build Status](https://travis-ci.org/rust-lang-nursery/tempdir.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/tempdir) +[![Build status](https://ci.appveyor.com/api/projects/status/2mp24396db5t4hul/branch/master?svg=true)](https://ci.appveyor.com/project/rust-lang-libs/tempdir/branch/master) + +[Documentation](https://doc.rust-lang.org/tempdir) + +## Deprecation Note + +The `tempdir` crate is being merged into [`tempfile`](https://github.com/Stebalien/tempfile). Please see [this issue](https://github.com/Stebalien/tempfile/issues/43) to track progress and direct new issues and pull requests to `tempfile`. + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +tempdir = "0.3" +``` + +and this to your crate root: + +```rust +extern crate tempdir; +``` + +## Example + +This sample method does the following: + +1. Create a temporary directory in the default location with the given prefix. +2. Determine a file path in the directory and print it out. +3. Create a file inside the temp folder. +4. Write to the file and sync it to disk. +5. Close the directory, deleting the contents in the process. + +```rust +use std::io::{self, Write}; +use std::fs::File; +use tempdir::TempDir; + +fn write_temp_folder_with_files() -> io::Result<()> { + let dir = TempDir::new("my_directory_prefix")?; + let file_path = dir.path().join("foo.txt"); + println!("{:?}", file_path); + + let mut f = File::create(file_path)?; + f.write_all(b"Hello, world!")?; + f.sync_all()?; + dir.close()?; + + Ok(()) +} +``` + +**Note:** Closing the directory is actually optional, as it would be done on +drop. The benefit of closing here is that it allows possible errors to be +handled. diff --git a/vendor/tempdir/appveyor.yml b/vendor/tempdir/appveyor.yml new file mode 100644 index 0000000..6a1b8dc --- /dev/null +++ b/vendor/tempdir/appveyor.yml @@ -0,0 +1,17 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --verbose diff --git a/vendor/tempdir/src/lib.rs b/vendor/tempdir/src/lib.rs new file mode 100644 index 0000000..278af7c --- /dev/null +++ b/vendor/tempdir/src/lib.rs @@ -0,0 +1,360 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://docs.rs/tempdir/0.3.7")] +#![cfg_attr(test, deny(warnings))] + +//! Temporary directories of files. +//! +//! The [`TempDir`] type creates a directory on the file system that +//! is deleted once it goes out of scope. At construction, the +//! `TempDir` creates a new directory with a randomly generated name +//! and a prefix of your choosing. +//! +//! [`TempDir`]: struct.TempDir.html +//! [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html +//! +//! # Examples +//! +//! ``` +//! extern crate tempdir; +//! +//! use std::fs::File; +//! use std::io::{self, Write}; +//! use tempdir::TempDir; +//! +//! fn main() { +//! if let Err(_) = run() { +//! ::std::process::exit(1); +//! } +//! } +//! +//! fn run() -> Result<(), io::Error> { +//! // Create a directory inside of `std::env::temp_dir()`, named with +//! // the prefix "example". +//! let tmp_dir = TempDir::new("example")?; +//! let file_path = tmp_dir.path().join("my-temporary-note.txt"); +//! let mut tmp_file = File::create(file_path)?; +//! writeln!(tmp_file, "Brian was here. Briefly.")?; +//! +//! // By closing the `TempDir` explicitly, we can check that it has +//! // been deleted successfully. If we don't close it explicitly, +//! // the directory will still be deleted when `tmp_dir` goes out +//! // of scope, but we won't know whether deleting the directory +//! // succeeded. +//! drop(tmp_file); +//! tmp_dir.close()?; +//! Ok(()) +//! } +//! ``` + +extern crate rand; +extern crate remove_dir_all; + +use std::env; +use std::io::{self, Error, ErrorKind}; +use std::fmt; +use std::fs; +use std::path::{self, PathBuf, Path}; +use rand::{thread_rng, Rng}; +use remove_dir_all::remove_dir_all; + +/// A directory in the filesystem that is automatically deleted when +/// it goes out of scope. +/// +/// The [`TempDir`] type creates a directory on the file system that +/// is deleted once it goes out of scope. At construction, the +/// `TempDir` creates a new directory with a randomly generated name, +/// and with a prefix of your choosing. +/// +/// The default constructor, [`TempDir::new`], creates directories in +/// the location returned by [`std::env::temp_dir()`], but `TempDir` +/// can be configured to manage a temporary directory in any location +/// by constructing with [`TempDir::new_in`]. +/// +/// After creating a `TempDir`, work with the file system by doing +/// standard [`std::fs`] file system operations on its [`Path`], +/// which can be retrieved with [`TempDir::path`]. Once the `TempDir` +/// value is dropped, the directory at the path will be deleted, along +/// with any files and directories it contains. It is your responsibility +/// to ensure that no further file system operations are attempted +/// inside the temporary directory once it has been deleted. +/// +/// Various platform-specific conditions may cause `TempDir` to fail +/// to delete the underlying directory. It's important to ensure that +/// handles (like [`File`] and [`ReadDir`]) to files inside the +/// directory are dropped before the `TempDir` goes out of scope. The +/// `TempDir` destructor will silently ignore any errors in deleting +/// the directory; to instead handle errors call [`TempDir::close`]. +/// +/// Note that if the program exits before the `TempDir` destructor is +/// run, such as via [`std::process::exit`], by segfaulting, or by +/// receiving a signal like `SIGINT`, then the temporary directory +/// will not be deleted. +/// +/// [`File`]: http://doc.rust-lang.org/std/fs/struct.File.html +/// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html +/// [`ReadDir`]: http://doc.rust-lang.org/std/fs/struct.ReadDir.html +/// [`TempDir::close`]: struct.TempDir.html#method.close +/// [`TempDir::new`]: struct.TempDir.html#method.new +/// [`TempDir::new_in`]: struct.TempDir.html#method.new_in +/// [`TempDir::path`]: struct.TempDir.html#method.path +/// [`TempDir`]: struct.TempDir.html +/// [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html +/// [`std::fs`]: http://doc.rust-lang.org/std/fs/index.html +/// [`std::process::exit`]: http://doc.rust-lang.org/std/process/fn.exit.html +pub struct TempDir { + path: Option<PathBuf>, +} + +// How many times should we (re)try finding an unused random name? It should be +// enough that an attacker will run out of luck before we run out of patience. +const NUM_RETRIES: u32 = 1 << 31; +// How many characters should we include in a random file name? It needs to +// be enough to dissuade an attacker from trying to preemptively create names +// of that length, but not so huge that we unnecessarily drain the random number +// generator of entropy. +const NUM_RAND_CHARS: usize = 12; + +impl TempDir { + /// Attempts to make a temporary directory inside of `env::temp_dir()` whose + /// name will have the prefix, `prefix`. The directory and + /// everything inside it will be automatically deleted once the + /// returned `TempDir` is destroyed. + /// + /// # Errors + /// + /// If the directory can not be created, `Err` is returned. + /// + /// # Examples + /// + /// ``` + /// use std::fs::File; + /// use std::io::Write; + /// use tempdir::TempDir; + /// + /// # use std::io; + /// # fn run() -> Result<(), io::Error> { + /// // Create a directory inside of `std::env::temp_dir()`, named with + /// // the prefix, "example". + /// let tmp_dir = TempDir::new("example")?; + /// let file_path = tmp_dir.path().join("my-temporary-note.txt"); + /// let mut tmp_file = File::create(file_path)?; + /// writeln!(tmp_file, "Brian was here. Briefly.")?; + /// + /// // `tmp_dir` goes out of scope, the directory as well as + /// // `tmp_file` will be deleted here. + /// # Ok(()) + /// # } + /// ``` + pub fn new(prefix: &str) -> io::Result<TempDir> { + TempDir::new_in(&env::temp_dir(), prefix) + } + + /// Attempts to make a temporary directory inside of `tmpdir` + /// whose name will have the prefix `prefix`. The directory and + /// everything inside it will be automatically deleted once the + /// returned `TempDir` is destroyed. + /// + /// # Errors + /// + /// If the directory can not be created, `Err` is returned. + /// + /// # Examples + /// + /// ``` + /// use std::fs::{self, File}; + /// use std::io::Write; + /// use tempdir::TempDir; + /// + /// # use std::io; + /// # fn run() -> Result<(), io::Error> { + /// // Create a directory inside of the current directory, named with + /// // the prefix, "example". + /// let tmp_dir = TempDir::new_in(".", "example")?; + /// let file_path = tmp_dir.path().join("my-temporary-note.txt"); + /// let mut tmp_file = File::create(file_path)?; + /// writeln!(tmp_file, "Brian was here. Briefly.")?; + /// # Ok(()) + /// # } + /// ``` + pub fn new_in<P: AsRef<Path>>(tmpdir: P, prefix: &str) -> io::Result<TempDir> { + let storage; + let mut tmpdir = tmpdir.as_ref(); + if !tmpdir.is_absolute() { + let cur_dir = env::current_dir()?; + storage = cur_dir.join(tmpdir); + tmpdir = &storage; + // return TempDir::new_in(&cur_dir.join(tmpdir), prefix); + } + + let mut rng = thread_rng(); + for _ in 0..NUM_RETRIES { + let suffix: String = rng.gen_ascii_chars().take(NUM_RAND_CHARS).collect(); + let leaf = if !prefix.is_empty() { + format!("{}.{}", prefix, suffix) + } else { + // If we're given an empty string for a prefix, then creating a + // directory starting with "." would lead to it being + // semi-invisible on some systems. + suffix + }; + let path = tmpdir.join(&leaf); + match fs::create_dir(&path) { + Ok(_) => return Ok(TempDir { path: Some(path) }), + Err(ref e) if e.kind() == ErrorKind::AlreadyExists => {} + Err(e) => return Err(e), + } + } + + Err(Error::new(ErrorKind::AlreadyExists, + "too many temporary directories already exist")) + } + + /// Accesses the [`Path`] to the temporary directory. + /// + /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html + /// + /// # Examples + /// + /// ``` + /// use tempdir::TempDir; + /// + /// # use std::io; + /// # fn run() -> Result<(), io::Error> { + /// let tmp_path; + /// + /// { + /// let tmp_dir = TempDir::new("example")?; + /// tmp_path = tmp_dir.path().to_owned(); + /// + /// // Check that the temp directory actually exists. + /// assert!(tmp_path.exists()); + /// + /// // End of `tmp_dir` scope, directory will be deleted + /// } + /// + /// // Temp directory should be deleted by now + /// assert_eq!(tmp_path.exists(), false); + /// # Ok(()) + /// # } + /// ``` + pub fn path(&self) -> &path::Path { + self.path.as_ref().unwrap() + } + + /// Unwraps the [`Path`] contained in the `TempDir` and + /// returns it. This destroys the `TempDir` without deleting the + /// directory represented by the returned `Path`. + /// + /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html + /// + /// # Examples + /// + /// ``` + /// use std::fs; + /// use tempdir::TempDir; + /// + /// # use std::io; + /// # fn run() -> Result<(), io::Error> { + /// let tmp_dir = TempDir::new("example")?; + /// + /// // Convert `tmp_dir` into a `Path`, destroying the `TempDir` + /// // without deleting the directory. + /// let tmp_path = tmp_dir.into_path(); + /// + /// // Delete the temporary directory ourselves. + /// fs::remove_dir_all(tmp_path)?; + /// # Ok(()) + /// # } + /// ``` + pub fn into_path(mut self) -> PathBuf { + self.path.take().unwrap() + } + + /// Closes and removes the temporary directory, returing a `Result`. + /// + /// Although `TempDir` removes the directory on drop, in the destructor + /// any errors are ignored. To detect errors cleaning up the temporary + /// directory, call `close` instead. + /// + /// # Errors + /// + /// This function may return a variety of [`std::io::Error`]s that result from deleting + /// the files and directories contained with the temporary directory, + /// as well as from deleting the temporary directory itself. These errors + /// may be platform specific. + /// + /// [`std::io::Error`]: http://doc.rust-lang.org/std/io/struct.Error.html + /// + /// # Examples + /// + /// ``` + /// use std::fs::File; + /// use std::io::Write; + /// use tempdir::TempDir; + /// + /// # use std::io; + /// # fn run() -> Result<(), io::Error> { + /// // Create a directory inside of `std::env::temp_dir()`, named with + /// // the prefix, "example". + /// let tmp_dir = TempDir::new("example")?; + /// let file_path = tmp_dir.path().join("my-temporary-note.txt"); + /// let mut tmp_file = File::create(file_path)?; + /// writeln!(tmp_file, "Brian was here. Briefly.")?; + /// + /// // By closing the `TempDir` explicitly we can check that it has + /// // been deleted successfully. If we don't close it explicitly, + /// // the directory will still be deleted when `tmp_dir` goes out + /// // of scope, but we won't know whether deleting the directory + /// // succeeded. + /// drop(tmp_file); + /// tmp_dir.close()?; + /// # Ok(()) + /// # } + /// ``` + pub fn close(mut self) -> io::Result<()> { + let result = remove_dir_all(self.path()); + + // Prevent the Drop impl from removing the dir a second time. + self.path = None; + + result + } +} + +impl AsRef<Path> for TempDir { + fn as_ref(&self) -> &Path { + self.path() + } +} + +impl fmt::Debug for TempDir { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("TempDir") + .field("path", &self.path()) + .finish() + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + // Path is `None` if `close()` or `into_path()` has been called. + if let Some(ref p) = self.path { + let _ = remove_dir_all(p); + } + } +} + +// the tests for this module need to change the path using change_dir, +// and this doesn't play nicely with other tests so these unit tests are located +// in src/test/run-pass/tempfile.rs diff --git a/vendor/tempdir/tests/smoke.rs b/vendor/tempdir/tests/smoke.rs new file mode 100644 index 0000000..44535e0 --- /dev/null +++ b/vendor/tempdir/tests/smoke.rs @@ -0,0 +1,229 @@ +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern crate tempdir; + +use std::env; +use std::fs; +use std::path::Path; +use std::sync::mpsc::channel; +use std::thread; + +use tempdir::TempDir; + +macro_rules! t { + ($e:expr) => (match $e { Ok(n) => n, Err(e) => panic!("error: {}", e) }) +} + +trait PathExt { + fn exists(&self) -> bool; + fn is_dir(&self) -> bool; +} + +impl PathExt for Path { + fn exists(&self) -> bool { fs::metadata(self).is_ok() } + fn is_dir(&self) -> bool { + fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false) + } +} + +fn test_tempdir() { + let path = { + let p = t!(TempDir::new_in(&Path::new("."), "foobar")); + let p = p.path(); + assert!(p.to_str().unwrap().contains("foobar")); + p.to_path_buf() + }; + assert!(!path.exists()); +} + +fn test_rm_tempdir() { + let (tx, rx) = channel(); + let f = move|| -> () { + let tmp = t!(TempDir::new("test_rm_tempdir")); + tx.send(tmp.path().to_path_buf()).unwrap(); + panic!("panic to unwind past `tmp`"); + }; + let _ = thread::spawn(f).join(); + let path = rx.recv().unwrap(); + assert!(!path.exists()); + + let tmp = t!(TempDir::new("test_rm_tempdir")); + let path = tmp.path().to_path_buf(); + let f = move|| -> () { + let _tmp = tmp; + panic!("panic to unwind past `tmp`"); + }; + let _ = thread::spawn(f).join(); + assert!(!path.exists()); + + let path; + { + let f = move || { + t!(TempDir::new("test_rm_tempdir")) + }; + + let tmp = thread::spawn(f).join().unwrap(); + path = tmp.path().to_path_buf(); + assert!(path.exists()); + } + assert!(!path.exists()); + + let path; + { + let tmp = t!(TempDir::new("test_rm_tempdir")); + path = tmp.into_path(); + } + assert!(path.exists()); + t!(fs::remove_dir_all(&path)); + assert!(!path.exists()); +} + +fn test_rm_tempdir_close() { + let (tx, rx) = channel(); + let f = move|| -> () { + let tmp = t!(TempDir::new("test_rm_tempdir")); + tx.send(tmp.path().to_path_buf()).unwrap(); + t!(tmp.close()); + panic!("panic when unwinding past `tmp`"); + }; + let _ = thread::spawn(f).join(); + let path = rx.recv().unwrap(); + assert!(!path.exists()); + + let tmp = t!(TempDir::new("test_rm_tempdir")); + let path = tmp.path().to_path_buf(); + let f = move|| -> () { + let tmp = tmp; + t!(tmp.close()); + panic!("panic when unwinding past `tmp`"); + }; + let _ = thread::spawn(f).join(); + assert!(!path.exists()); + + let path; + { + let f = move || { + t!(TempDir::new("test_rm_tempdir")) + }; + + let tmp = thread::spawn(f).join().unwrap(); + path = tmp.path().to_path_buf(); + assert!(path.exists()); + t!(tmp.close()); + } + assert!(!path.exists()); + + let path; + { + let tmp = t!(TempDir::new("test_rm_tempdir")); + path = tmp.into_path(); + } + assert!(path.exists()); + t!(fs::remove_dir_all(&path)); + assert!(!path.exists()); +} + +// Ideally these would be in std::os but then core would need +// to depend on std +fn recursive_mkdir_rel() { + let path = Path::new("frob"); + let cwd = env::current_dir().unwrap(); + println!("recursive_mkdir_rel: Making: {} in cwd {} [{}]", path.display(), + cwd.display(), path.exists()); + t!(fs::create_dir(&path)); + assert!(path.is_dir()); + t!(fs::create_dir_all(&path)); + assert!(path.is_dir()); +} + +fn recursive_mkdir_dot() { + let dot = Path::new("."); + t!(fs::create_dir_all(&dot)); + let dotdot = Path::new(".."); + t!(fs::create_dir_all(&dotdot)); +} + +fn recursive_mkdir_rel_2() { + let path = Path::new("./frob/baz"); + let cwd = env::current_dir().unwrap(); + println!("recursive_mkdir_rel_2: Making: {} in cwd {} [{}]", path.display(), + cwd.display(), path.exists()); + t!(fs::create_dir_all(&path)); + assert!(path.is_dir()); + assert!(path.parent().unwrap().is_dir()); + let path2 = Path::new("quux/blat"); + println!("recursive_mkdir_rel_2: Making: {} in cwd {}", path2.display(), + cwd.display()); + t!(fs::create_dir("quux")); + t!(fs::create_dir_all(&path2)); + assert!(path2.is_dir()); + assert!(path2.parent().unwrap().is_dir()); +} + +// Ideally this would be in core, but needs TempFile +pub fn test_remove_dir_all_ok() { + let tmpdir = t!(TempDir::new("test")); + let tmpdir = tmpdir.path(); + let root = tmpdir.join("foo"); + + println!("making {}", root.display()); + t!(fs::create_dir(&root)); + t!(fs::create_dir(&root.join("foo"))); + t!(fs::create_dir(&root.join("foo").join("bar"))); + t!(fs::create_dir(&root.join("foo").join("bar").join("blat"))); + t!(fs::remove_dir_all(&root)); + assert!(!root.exists()); + assert!(!root.join("bar").exists()); + assert!(!root.join("bar").join("blat").exists()); +} + +pub fn dont_double_panic() { + let r: Result<(), _> = thread::spawn(move|| { + let tmpdir = TempDir::new("test").unwrap(); + // Remove the temporary directory so that TempDir sees + // an error on drop + t!(fs::remove_dir(tmpdir.path())); + // Panic. If TempDir panics *again* due to the rmdir + // error then the process will abort. + panic!(); + }).join(); + assert!(r.is_err()); +} + +fn in_tmpdir<F>(f: F) where F: FnOnce() { + let tmpdir = t!(TempDir::new("test")); + assert!(env::set_current_dir(tmpdir.path()).is_ok()); + + f(); +} + +pub fn pass_as_asref_path() { + let tempdir = t!(TempDir::new("test")); + takes_asref_path(&tempdir); + + fn takes_asref_path<T: AsRef<Path>>(path: T) { + let path = path.as_ref(); + assert!(path.exists()); + } +} + +#[test] +fn main() { + in_tmpdir(test_tempdir); + in_tmpdir(test_rm_tempdir); + in_tmpdir(test_rm_tempdir_close); + in_tmpdir(recursive_mkdir_rel); + in_tmpdir(recursive_mkdir_dot); + in_tmpdir(recursive_mkdir_rel_2); + in_tmpdir(test_remove_dir_all_ok); + in_tmpdir(dont_double_panic); + in_tmpdir(pass_as_asref_path); +} |