temporary-0.6.4/.cargo_vcs_info.json0000644000000001360000000000100130650ustar { "git": { "sha1": "9b0aae64b64845469962f4f61f1d62eb9c2a6de1" }, "path_in_vcs": "" }temporary-0.6.4/.github/workflows/build.yml000064400000000000000000000010030072674642500171160ustar 00000000000000name: build on: push: branches: - master pull_request: branches: - master workflow_dispatch: jobs: macos: name: macOS runs-on: macos-10.15 steps: - uses: actions/checkout@v1 - name: Run the test suite uses: actions-rs/cargo@v1 with: {command: test} ubuntu: name: Ubuntu runs-on: ubuntu-18.04 steps: - uses: actions/checkout@v1 - name: Run the test suite uses: actions-rs/cargo@v1 with: {command: test} temporary-0.6.4/.gitignore000064400000000000000000000000220072674642500136670ustar 00000000000000target Cargo.lock temporary-0.6.4/Cargo.toml0000644000000015570000000000100110730ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] name = "temporary" version = "0.6.4" authors = ["Ivan Ukhov "] description = "The package provides means of managing temporary files and directories." homepage = "https://github.com/stainless-steel/temporary" documentation = "https://docs.rs/temporary" license = "Apache-2.0/MIT" repository = "https://github.com/stainless-steel/temporary" [dependencies.random] version = "0.12" temporary-0.6.4/Cargo.toml.orig000064400000000000000000000006310072674642500145740ustar 00000000000000[package] name = "temporary" version = "0.6.4" license = "Apache-2.0/MIT" authors = ["Ivan Ukhov "] description = """ The package provides means of managing temporary files and directories.""" documentation = "https://docs.rs/temporary" homepage = "https://github.com/stainless-steel/temporary" repository = "https://github.com/stainless-steel/temporary" [dependencies] random = "0.12" temporary-0.6.4/LICENSE.md000064400000000000000000000037750072674642500133250ustar 00000000000000# License The project is dual licensed under the terms of the Apache License, Version 2.0, and the MIT License. You may obtain copies of the two licenses at * https://www.apache.org/licenses/LICENSE-2.0 and * https://opensource.org/licenses/MIT, respectively. The following two notices apply to every file of the project. ## The Apache License ``` Copyright 2015–2022 The temporary Developers 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. ``` ## The MIT License ``` Copyright 2015–2022 The temporary 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. ``` temporary-0.6.4/README.md000064400000000000000000000025730072674642500131730ustar 00000000000000# Temporary [![Package][package-img]][package-url] [![Documentation][documentation-img]][documentation-url] [![Build][build-img]][build-url] The package provides means of managing temporary files and directories. ## Example ```rust use std::fs::File; use std::io::Write; use temporary::Directory; // Create a temporary directory. let directory = Directory::new("foo").unwrap(); // Do some work. let mut file = File::create(directory.join("foo.txt")).unwrap(); file.write_all(b"Hello, there!").unwrap(); // The directory and its content get removed automatically. ``` ## Acknowledgments The package was originally based on `std::io::TempDir` by Rust’s developers, which was later moved to a separate crate, [tempdir](https://github.com/rust-lang/tempdir). ## Contribution Your contribution is highly appreciated. Do not hesitate to open an issue or a pull request. Note that any contribution submitted for inclusion in the project will be licensed according to the terms given in [LICENSE.md](LICENSE.md). [build-img]: https://github.com/stainless-steel/temporary/workflows/build/badge.svg [build-url]: https://github.com/stainless-steel/temporary/actions/workflows/build.yml [documentation-img]: https://docs.rs/temporary/badge.svg [documentation-url]: https://docs.rs/temporary [package-img]: https://img.shields.io/crates/v/temporary.svg [package-url]: https://crates.io/crates/temporary temporary-0.6.4/src/lib.rs000064400000000000000000000110610072674642500136070ustar 00000000000000//! Temporary files and directories. //! //! ## Example //! //! ```rust //! use std::fs::File; //! use std::io::Write; //! use temporary::Directory; //! //! // Create a temporary directory. //! let directory = Directory::new("foo").unwrap(); //! //! // Do some work. //! let mut file = File::create(directory.join("foo.txt")).unwrap(); //! file.write_all(b"Hello, there!").unwrap(); //! //! // The directory and its content get removed automatically. //! ``` extern crate random; use random::Source; use std::io::{Error, ErrorKind, Result}; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::{env, fmt, fs}; /// A temporary directory. pub struct Directory { path: PathBuf, removed: bool, } impl Directory { /// Create a temporary directory. /// /// The directory will have a name starting from `prefix`, and it will be /// automatically removed when the object goes out of scope. #[inline] pub fn new(prefix: &str) -> Result { Directory::with_parent(env::temp_dir(), prefix) } /// Create a temporary directory in a specific directory. /// /// The directory will have a name starting from `prefix`, and it will be /// automatically removed when the object goes out of scope. pub fn with_parent>(parent: T, prefix: &str) -> Result { const RETRIES: u32 = 1 << 31; const CHARS: usize = 12; let parent = parent.as_ref(); if !parent.is_absolute() { let current = env::current_dir()?; return Directory::with_parent(current.join(parent), prefix); } let mut source = random::default().seed(random_seed(parent, prefix)); for _ in 0..RETRIES { let suffix: String = random_string(CHARS, &mut source); let path = if prefix.is_empty() { parent.join(&suffix) } else { parent.join(&format!("{}.{}", prefix, suffix)) }; match fs::create_dir(&path) { Ok(_) => { return Ok(Directory { path: path.to_path_buf(), removed: false, }) } Err(error) => match error.kind() { ErrorKind::AlreadyExists => {} _ => return Err(error), }, } } Err(Error::new( ErrorKind::AlreadyExists, "failed to find a vacant name", )) } /// Return the path to the directory. #[inline] pub fn path(&self) -> &Path { self.as_ref() } /// Return the path to the directory and dispose the object without removing /// the actual directory. #[inline] pub fn into_path(mut self) -> PathBuf { self.removed = true; self.path.clone() } /// Remove the directory. #[inline] pub fn remove(mut self) -> Result<()> { self.cleanup() } fn cleanup(&mut self) -> Result<()> { if self.removed { return Ok(()); } self.removed = true; fs::remove_dir_all(&self.path) } } impl AsRef for Directory { #[inline] fn as_ref(&self) -> &Path { &self.path } } impl fmt::Debug for Directory { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.path.fmt(formatter) } } impl Deref for Directory { type Target = Path; #[inline] fn deref(&self) -> &Path { &self.path } } impl Drop for Directory { #[allow(unused_must_use)] #[inline] fn drop(&mut self) { self.cleanup(); } } fn random_seed(_: &Path, prefix: &str) -> [u64; 2] { let seed: u64 = prefix.as_bytes().iter().map(|&c| c as u64).sum(); [seed ^ 0x12345678, seed ^ 0x87654321] } fn random_string(length: usize, source: &mut S) -> String { unsafe { String::from_utf8_unchecked((0..length).map(|_| random_letter(source)).collect()) } } fn random_letter(source: &mut S) -> u8 { b'a' + (source.read::() % 26) as u8 } #[cfg(test)] mod tests { use super::Directory; use std::path::Path; #[test] fn new() { use std::fs; let path = { let directory = Directory::new("foo").unwrap(); assert!(fs::metadata(directory.path()).is_ok()); directory.path().to_path_buf() }; assert!(fs::metadata(path).is_err()); } #[test] fn deref() { let directory = Directory::new("bar").unwrap(); work(&directory); fn work(_: &Path) {} } }