camino-tempfile-1.4.1/.cargo_vcs_info.json0000644000000001640000000000100141110ustar { "git": { "sha1": "7476c92c6236094be099024133088a1afb6154e4" }, "path_in_vcs": "crates/camino-tempfile" }camino-tempfile-1.4.1/CHANGELOG.md000064400000000000000000000052471046102023000145210ustar 00000000000000# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.4.1] - 2025-05-12 Documentation fixes. ## [1.4.0] - 2025-05-11 ### Added Updates corresponding to upstream `tempfile`: - `Builder::disable_cleanup`, `Utf8TempDir::disable_cleanup`, `NamedUtf8TempFile::disable_cleanup`, and `Utf8TempPath::disable_cleanup` conditionally disable cleanup for temporary files and directories. - `Builder::permissions` sets permissions for temporary files and directories. ## [1.3.0] - 2025-05-03 ### Added - References to the new [`camino-tempfile-ext`](https://crates.io/crates/camino-tempfile-ext) crate, which contains quality-of-life extensions that make it easier to write and assert temporary files. Be sure to check it out! ### Changed - MSRV updated to Rust 1.74 to support camino-tempfile-ext (sorry about the quickfire double-bump). ## [1.2.0] - 2025-05-02 ### Added * `Utf8TempDir::with_suffix`, `Utf8TempDir::with_suffix_in`, `NamedUtf8TempFile::with_suffix`, and `NamedUtf8TempFile::with_suffix_in`. ### Changed - MSRV updated to Rust 1.65. ## [1.1.1] - 2023-11-27 ### Fixed - Documentation fixes. ## [1.1.0] - 2023-11-27 ### Added - Mirroring the new API added in tempfile 3.8.0, added `with_prefix` and `with_prefix_in` to `Utf8TempDir` and `NamedUtf8TempFile` to make it easier to create temporary files/directories with nice prefixes. ### Changed - Updated tempfile dependency to 3.8.1. - Updated MSRV to 1.63 to match the MSRV of tempfile. ## [1.0.3] - 2023-11-27 This version was yanked because the MSRV needed to be bumped. ## [1.0.2] - 2023-04-23 Fix another publishing issue. ## [1.0.1] - 2023-04-23 Fix a publishing issue. ## [1.0.0] - 2023-04-23 Initial release. [1.4.1]: https://github.com/camino-rs/camino-tempfile/releases/tag/camino-tempfile-1.4.1 [1.4.0]: https://github.com/camino-rs/camino-tempfile/releases/tag/camino-tempfile-1.4.0 [1.3.0]: https://github.com/camino-rs/camino-tempfile/releases/tag/camino-tempfile-1.3.0 [1.2.0]: https://github.com/camino-rs/camino-tempfile/releases/tag/camino-tempfile-1.2.0 [1.1.1]: https://github.com/camino-rs/camino-tempfile/releases/tag/camino-tempfile-1.1.1 [1.1.0]: https://github.com/camino-rs/camino-tempfile/releases/tag/camino-tempfile-1.1.0 [1.0.3]: https://github.com/camino-rs/camino-tempfile/releases/tag/camino-tempfile-1.0.3 [1.0.2]: https://github.com/camino-rs/camino-tempfile/releases/tag/camino-tempfile-1.0.2 [1.0.1]: https://github.com/camino-rs/camino-tempfile/releases/tag/camino-tempfile-1.0.1 [1.0.0]: https://github.com/camino-rs/camino-tempfile/releases/tag/camino-tempfile-1.0.0 camino-tempfile-1.4.1/Cargo.lock0000644000000126460000000000100120740ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bitflags" version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" [[package]] name = "camino" version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b96ec4966b5813e2c0507c1f86115c8c5abaadc3980879c3424042a02fd1ad3" [[package]] name = "camino-tempfile" version = "1.4.1" dependencies = [ "camino", "fastrand", "tempfile", ] [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "errno" version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e" dependencies = [ "libc", "windows-sys", ] [[package]] name = "fastrand" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "getrandom" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" dependencies = [ "cfg-if", "libc", "r-efi", "wasi", ] [[package]] name = "libc" version = "0.2.172" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "linux-raw-sys" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" [[package]] name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "r-efi" version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" [[package]] name = "rustix" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "tempfile" version = "3.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" dependencies = [ "fastrand", "getrandom", "once_cell", "rustix", "windows-sys", ] [[package]] name = "wasi" version = "0.14.2+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" dependencies = [ "wit-bindgen-rt", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "wit-bindgen-rt" version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ "bitflags", ] camino-tempfile-1.4.1/Cargo.toml0000644000000035310000000000100121100ustar # 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] edition = "2021" rust-version = "1.74" name = "camino-tempfile" version = "1.4.1" build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A library for managing temporary files and directories, with UTF-8 paths." documentation = "https://docs.rs/camino-tempfile" readme = "README.md" keywords = [ "tempfile", "tmpfile", "filesystem", "camino", ] categories = [ "filesystem", "os", ] license = "MIT OR Apache-2.0" repository = "https://github.com/camino-rs/camino-tempfile" [package.metadata.cargo-sync-rdme.rustdoc] html-root-url = "https://camino-rs.github.io/camino-tempfile" [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "src/lib.rs" replace = '#![doc(html_root_url = "https://docs.rs/camino-tempfile/{{version}}")]' search = '^#!\[doc\(html_root_url = "https://docs.rs/camino-tempfile/.*"\)\]$' [features] nightly = ["tempfile/nightly"] [lib] name = "camino_tempfile" path = "src/lib.rs" [[test]] name = "namedtempfile" path = "tests/namedtempfile.rs" [[test]] name = "tempdir" path = "tests/tempdir.rs" [[test]] name = "tempfile" path = "tests/tempfile.rs" [dependencies.camino] version = "1.1.4" [dependencies.tempfile] version = "3.20.0" [dev-dependencies.fastrand] version = "2.0.1" [lints.rust.unexpected_cfgs] level = "warn" priority = 0 check-cfg = ["cfg(doc_cfg)"] camino-tempfile-1.4.1/Cargo.toml.orig000064400000000000000000000016771046102023000156020ustar 00000000000000[package] name = "camino-tempfile" version = "1.4.1" edition = "2021" rust-version = "1.74" license.workspace = true description = "A library for managing temporary files and directories, with UTF-8 paths." readme = "README.md" repository.workspace = true documentation = "https://docs.rs/camino-tempfile" keywords = ["tempfile", "tmpfile", "filesystem", "camino"] categories = ["filesystem", "os"] [lints] workspace = true [dependencies] camino.workspace = true tempfile.workspace = true [dev-dependencies] fastrand.workspace = true [features] nightly = ["tempfile/nightly"] [package.metadata.release] pre-release-replacements = [ { file = "src/lib.rs", search = "^#!\\[doc\\(html_root_url = \"https://docs.rs/camino-tempfile/.*\"\\)\\]$", replace = "#![doc(html_root_url = \"https://docs.rs/camino-tempfile/{{version}}\")]", exactly = 1 }, ] [package.metadata.cargo-sync-rdme.rustdoc] html-root-url = "https://camino-rs.github.io/camino-tempfile" camino-tempfile-1.4.1/LICENSE-APACHE000064400000000000000000000251371046102023000146340ustar 00000000000000 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. camino-tempfile-1.4.1/LICENSE-MIT000064400000000000000000000021701046102023000143340ustar 00000000000000Copyright (c) 2015 Steven Allen Copyright (c) The assert_fs Contributors Copyright (c) The camino-tempfile Contributors 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. camino-tempfile-1.4.1/README.md000064400000000000000000000050051046102023000141570ustar 00000000000000# camino-tempfile [![camino-tempfile on crates.io](https://img.shields.io/crates/v/camino-tempfile)](https://crates.io/crates/camino-tempfile) [![Documentation (latest release)](https://img.shields.io/badge/docs-latest%20version-brightgreen.svg)](https://docs.rs/camino-tempfile) [![Documentation (main)](https://img.shields.io/badge/docs-main-purple.svg)](https://camino-rs.github.io/camino-tempfile/rustdoc/camino_tempfile/) [![License (Apache 2.0)](https://img.shields.io/badge/license-Apache-green.svg)](LICENSE-APACHE) [![License (MIT)](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE-MIT) A secure, cross-platform, temporary file library for Rust with UTF-8 paths. This crate is a wrapper around [`tempfile`](https://crates.io/crates/tempfile) that works with the `Utf8Path` and `Utf8PathBuf` types defined by [`camino`](https://crates.io/crates/camino). If your code mostly uses `camino`, it can be annoying to have to convert temporary paths to `Utf8Path` over and over again. This crate manages that for you. In addition to creating temporary files, this library also allows users to securely open multiple independent references to the same temporary file (useful for consumer/producer patterns and surprisingly difficult to implement securely). This crate closely mirrors tempfile's interface. For extensions that provide quality-of-life improvements such as the ability to create files easily, see [`camino-tempfile-ext`](https://crates.io/crates/camino-tempfile-ext). [Documentation](https://docs.rs/camino-tempfile) ## Usage Add this to your Cargo.toml: ```toml [dependencies] camino-tempfile = "1" ``` ## Example ```rust use std::fs::File; use std::io::{Write, Read, Seek, SeekFrom}; fn main() { // Write let mut tmpfile: File = camino_tempfile::tempfile().unwrap(); write!(tmpfile, "Hello World!").unwrap(); // Seek to start tmpfile.seek(SeekFrom::Start(0)).unwrap(); // Read let mut buf = String::new(); tmpfile.read_to_string(&mut buf).unwrap(); assert_eq!("Hello World!", buf); } ``` ## Minimum supported Rust version (MSRV) camino-tempfile's MSRV is **Rust 1.74**. At any time, at least the last 6 months of Rust releases will be supported. ## License This project is available under the terms of either the [Apache 2.0 license](LICENSE-APACHE) or the [MIT license](LICENSE-MIT). Portions copied and adapted from [tempfile](https://github.com/Stebalien/tempfile) and used under the MIT and Apache 2.0 licenses. tempfile is copyright 2015 Steven Allen and the tempfile authors. camino-tempfile-1.4.1/src/builder.rs000064400000000000000000000450441046102023000154720ustar 00000000000000// Copyright (c) The camino-tempfile Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use crate::{helpers::utf8_env_temp_dir, NamedUtf8TempFile, Utf8TempDir}; use camino::{Utf8Path, Utf8PathBuf}; use std::{convert::TryFrom, io}; /// Create a new temporary file or directory with custom parameters. #[derive(Debug, Clone, Default, Eq, PartialEq)] pub struct Builder<'a, 'b> { inner: tempfile::Builder<'a, 'b>, } impl<'a, 'b> Builder<'a, 'b> { /// Create a new `Builder`. /// /// # Examples /// /// Create a named temporary file and write some data into it: /// /// ``` /// # use std::io; /// # use std::ffi::OsStr; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// use camino_tempfile::Builder; /// /// let named_tempfile = Builder::new() /// .prefix("my-temporary-note") /// .suffix(".txt") /// .rand_bytes(5) /// .tempfile()?; /// /// let name = named_tempfile.path().file_name(); /// /// if let Some(name) = name { /// assert!(name.starts_with("my-temporary-note")); /// assert!(name.ends_with(".txt")); /// assert_eq!(name.len(), "my-temporary-note.txt".len() + 5); /// } /// # Ok(()) /// # } /// ``` /// /// Create a temporary directory and add a file to it: /// /// ``` /// # use std::io::{self, Write}; /// # use std::fs::File; /// # use std::ffi::OsStr; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// use camino_tempfile::Builder; /// /// let dir = Builder::new() /// .prefix("my-temporary-dir") /// .rand_bytes(5) /// .tempdir()?; /// /// let file_path = dir.path().join("my-temporary-note.txt"); /// let mut file = File::create(file_path)?; /// writeln!(file, "Brian was here. Briefly.")?; /// /// // By closing the `Utf8TempDir` explicitly, we can check that it has /// // been deleted successfully. If we don't close it explicitly, /// // the directory will still be deleted when `dir` goes out /// // of scope, but we won't know whether deleting the directory /// // succeeded. /// drop(file); /// dir.close()?; /// # Ok(()) /// # } /// ``` /// /// Create a temporary directory with a chosen prefix under a chosen folder: /// /// ```ignore /// let dir = Builder::new() /// .prefix("my-temporary-dir") /// .tempdir_in("folder-with-tempdirs")?; /// ``` #[must_use] pub fn new() -> Self { Self::default() } /// Set a custom filename prefix. /// /// Path separators are legal but not advisable. /// Default: `.tmp`. /// /// # Examples /// /// ``` /// # use std::io; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// # use camino_tempfile::Builder; /// let named_tempfile = Builder::new() /// .prefix("my-temporary-note") /// .tempfile()?; /// # Ok(()) /// # } /// ``` pub fn prefix + ?Sized>(&mut self, prefix: &'a S) -> &mut Self { self.inner.prefix(prefix.as_ref()); self } /// Set a custom filename suffix. /// /// Path separators are legal but not advisable. /// Default: empty. /// /// # Examples /// /// ``` /// # use std::io; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// # use camino_tempfile::Builder; /// let named_tempfile = Builder::new() /// .suffix(".txt") /// .tempfile()?; /// # Ok(()) /// # } /// ``` pub fn suffix + ?Sized>(&mut self, suffix: &'b S) -> &mut Self { self.inner.suffix(suffix.as_ref()); self } /// Set the number of random bytes. /// /// Default: `6`. /// /// # Examples /// /// ``` /// # use std::io; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// # use camino_tempfile::Builder; /// let named_tempfile = Builder::new() /// .rand_bytes(5) /// .tempfile()?; /// # Ok(()) /// # } /// ``` pub fn rand_bytes(&mut self, rand: usize) -> &mut Self { self.inner.rand_bytes(rand); self } /// Set the file to be opened in append mode. /// /// Default: `false`. /// /// # Examples /// /// ``` /// # use std::io; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// # use camino_tempfile::Builder; /// let named_tempfile = Builder::new() /// .append(true) /// .tempfile()?; /// # Ok(()) /// # } /// ``` pub fn append(&mut self, append: bool) -> &mut Self { self.inner.append(append); self } /// The permissions to create the tempfile or [tempdir](Self::tempdir) with. /// /// # Security /// /// By default, the permissions of tempfiles on Unix are set for it to be /// readable and writable by the owner only, yielding the greatest amount of /// security. As this method allows to widen the permissions, security would /// be reduced in such cases. /// /// # Platform Notes /// /// ## Unix /// /// The actual permission bits set on the tempfile or tempdir will be /// affected by the `umask` applied by the underlying syscall. The actual /// permission bits are calculated via `permissions & !umask`. /// /// Permissions default to `0o600` for tempfiles and `0o777` for tempdirs. /// Note, this doesn't include effects of the current `umask`. For example, /// combined with the standard umask `0o022`, the defaults yield `0o600` for /// tempfiles and `0o755` for tempdirs. /// /// ## Windows and others /// /// This setting is unsupported and trying to set a file or directory /// read-only will return an error. /// /// # Examples /// /// Create a named temporary file that is world-readable. /// /// ``` /// # #[cfg(unix)] /// # { /// use camino_tempfile::Builder; /// use std::os::unix::fs::PermissionsExt; /// /// let all_read_write = std::fs::Permissions::from_mode(0o666); /// let tempfile = Builder::new().permissions(all_read_write).tempfile()?; /// let actual_permissions = tempfile.path().metadata()?.permissions(); /// assert_ne!( /// actual_permissions.mode() & !0o170000, /// 0o600, /// "we get broader permissions than the default despite umask" /// ); /// # } /// # Ok::<(), std::io::Error>(()) /// ``` /// /// Create a named temporary directory that is restricted to the owner. /// /// ``` /// # #[cfg(unix)] /// # { /// use camino_tempfile::Builder; /// use std::os::unix::fs::PermissionsExt; /// /// let owner_rwx = std::fs::Permissions::from_mode(0o700); /// let tempdir = Builder::new().permissions(owner_rwx).tempdir()?; /// let actual_permissions = tempdir.path().metadata()?.permissions(); /// assert_eq!( /// actual_permissions.mode() & !0o170000, /// 0o700, /// "we get the narrow permissions we asked for" /// ); /// # } /// # Ok::<(), std::io::Error>(()) /// ``` pub fn permissions(&mut self, permissions: std::fs::Permissions) -> &mut Self { self.inner.permissions(permissions); self } /// Disable cleanup of the file/folder to even when the /// [`NamedUtf8TempFile`]/[`Utf8TempDir`] goes out of scope. Prefer /// [`NamedUtf8TempFile::keep`] and [`Utf8TempDir::keep`] where possible, /// `disable_cleanup` is provided for testing & debugging. /// /// By default, the file/folder is automatically cleaned up in the /// destructor of [`NamedUtf8TempFile`]/[`Utf8TempDir`]. When /// `disable_cleanup` is set to `true`, this behavior is suppressed. If you /// wish to disable cleanup after creating a temporary file/directory, call /// [`NamedUtf8TempFile::disable_cleanup`] or /// [`Utf8TempDir::disable_cleanup`]. /// /// # Warnings /// /// On some platforms (for now, only Windows), temporary files are marked /// with a special "temporary file" (`FILE_ATTRIBUTE_TEMPORARY`) attribute. /// Disabling cleanup _will not_ unset this attribute while calling /// [`NamedUtf8TempFile::keep`] will. /// /// # Examples /// /// ``` /// use camino_tempfile::Builder; /// /// let named_tempfile = Builder::new() /// .disable_cleanup(true) /// .tempfile()?; /// # Ok::<(), std::io::Error>(()) /// ``` pub fn disable_cleanup(&mut self, disable_cleanup: bool) -> &mut Self { self.inner.disable_cleanup(disable_cleanup); self } /// Create the named temporary file. /// /// # Security /// /// See [the security][security] docs on `NamedUtf8TempFile`. /// /// # Resource leaking /// /// See [the resource leaking][resource-leaking] docs on `NamedUtf8TempFile`. /// /// # Errors /// /// If the file cannot be created, `Err` is returned. /// /// # Examples /// /// ``` /// # use std::io; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// # use camino_tempfile::Builder; /// let tempfile = Builder::new().tempfile()?; /// # Ok(()) /// # } /// ``` /// /// [security]: struct.NamedUtf8TempFile.html#security /// [resource-leaking]: struct.NamedUtf8TempFile.html#resource-leaking pub fn tempfile(&self) -> io::Result { self.tempfile_in(utf8_env_temp_dir()?) } /// Create the named temporary file in the specified directory. /// /// # Security /// /// See [the security][security] docs on `NamedUtf8TempFile`. /// /// # Resource leaking /// /// See [the resource leaking][resource-leaking] docs on `NamedUtf8TempFile`. /// /// # Errors /// /// If the file cannot be created, `Err` is returned. /// /// # Examples /// /// ``` /// # use std::io; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// # use camino_tempfile::Builder; /// let tempfile = Builder::new().tempfile_in("./")?; /// # Ok(()) /// # } /// ``` /// /// [security]: struct.NamedUtf8TempFile.html#security /// [resource-leaking]: struct.NamedUtf8TempFile.html#resource-leaking pub fn tempfile_in>(&self, dir: P) -> io::Result { let temp_file = self.inner.tempfile_in(dir.as_ref())?; NamedUtf8TempFile::from_temp_file(temp_file) } /// Attempts to make a temporary directory inside of [`std::env::temp_dir()`] whose name will /// have the prefix, `prefix`. The directory and everything inside it will be automatically /// deleted once the returned `Utf8TempDir` is destroyed. /// /// # Resource leaking /// /// See [the resource leaking][resource-leaking] docs on `TempDir`. /// /// # Errors /// /// If the directory can not be created, or if [`std::env::temp_dir()`] is non-UTF-8, `Err` is /// returned. /// /// # Examples /// /// ``` /// use std::fs::File; /// use std::io::Write; /// use camino_tempfile::Builder; /// /// # use std::io; /// # fn run() -> Result<(), io::Error> { /// let tmp_dir = Builder::new().tempdir()?; /// # Ok(()) /// # } /// ``` /// /// [resource-leaking]: struct.Utf8TempDir.html#resource-leaking pub fn tempdir(&self) -> io::Result { self.tempdir_in(utf8_env_temp_dir()?) } /// Attempts to make a temporary directory inside of `dir`. /// The directory and everything inside it will be automatically /// deleted once the returned `Utf8TempDir` is destroyed. /// /// # Resource leaking /// /// See [the resource leaking][resource-leaking] docs on `Utf8TempDir`. /// /// # Errors /// /// If the directory can not be created, `Err` is returned. /// /// # Examples /// /// ``` /// use std::fs::{self, File}; /// use std::io::Write; /// use camino_tempfile::Builder; /// /// # use std::io; /// # fn run() -> Result<(), io::Error> { /// let tmp_dir = Builder::new().tempdir_in("./")?; /// # Ok(()) /// # } /// ``` /// /// [resource-leaking]: struct.Utf8TempDir.html#resource-leaking pub fn tempdir_in>(&self, dir: P) -> io::Result { let temp_dir = self.inner.tempdir_in(dir.as_ref())?; Utf8TempDir::from_temp_dir(temp_dir) } /// Attempts to create a temporary file (or file-like object) using the /// provided closure. The closure is passed a temporary file path and /// returns an [`std::io::Result`]. The path provided to the closure will be /// inside of [`std::env::temp_dir()`]. Use [`Builder::make_in`] to provide /// a custom temporary directory. If the closure returns one of the /// following errors, then another randomized file path is tried: /// - [`std::io::ErrorKind::AlreadyExists`] /// - [`std::io::ErrorKind::AddrInUse`] /// /// This can be helpful for taking full control over the file creation, but /// leaving the temporary file path construction up to the library. This /// also enables creating a temporary UNIX domain socket, since it is not /// possible to bind to a socket that already exists. /// /// Note that [`Builder::append`] is ignored when using [`Builder::make`]. /// /// # Security /// /// This has the same [security implications][security] as /// [`NamedUtf8TempFile`], but with additional caveats. Specifically, it is up /// to the closure to ensure that the file does not exist and that such a /// check is *atomic*. Otherwise, a [time-of-check to time-of-use /// bug][TOCTOU] could be introduced. /// /// For example, the following is **not** secure: /// /// ``` /// # use std::io; /// # use std::fs::File; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// # use camino_tempfile::Builder; /// // This is NOT secure! /// let tempfile = Builder::new().make(|path| { /// if path.is_file() { /// return Err(io::ErrorKind::AlreadyExists.into()); /// } /// /// // Between the check above and the usage below, an attacker could /// // have replaced `path` with another file, which would get truncated /// // by `File::create`. /// /// File::create(path) /// })?; /// # Ok(()) /// # } /// ``` /// Note that simply using [`std::fs::File::create`] alone is not correct /// because it does not fail if the file already exists: /// ``` /// # use std::io; /// # use std::fs::File; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// # use camino_tempfile::Builder; /// // This could overwrite an existing file! /// let tempfile = Builder::new().make(|path| File::create(path))?; /// # Ok(()) /// # } /// ``` /// For creating regular temporary files, use [`Builder::tempfile`] instead /// to avoid these problems. This function is meant to enable more exotic /// use-cases. /// /// # Resource leaking /// /// See [the resource leaking][resource-leaking] docs on `NamedUtf8TempFile`. /// /// # Errors /// /// If the closure returns any error besides /// [`std::io::ErrorKind::AlreadyExists`] or /// [`std::io::ErrorKind::AddrInUse`], then `Err` is returned. /// /// # Examples /// ``` /// # use std::io; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// # use camino_tempfile::Builder; /// # #[cfg(unix)] /// use std::os::unix::net::UnixListener; /// # #[cfg(unix)] /// let tempsock = Builder::new().make(|path| UnixListener::bind(path))?; /// # Ok(()) /// # } /// ``` /// /// [TOCTOU]: https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use /// [security]: struct.NamedUtf8TempFile.html#security /// [resource-leaking]: struct.NamedUtf8TempFile.html#resource-leaking pub fn make(&self, f: F) -> io::Result> where F: FnMut(&Utf8Path) -> io::Result, { self.make_in(utf8_env_temp_dir()?, f) } /// This is the same as [`Builder::make`], except `dir` is used as the base /// directory for the temporary file path. /// /// See [`Builder::make`] for more details and security implications. /// /// # Examples /// ``` /// # use std::io; /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// # use camino_tempfile::Builder; /// # #[cfg(unix)] /// use std::os::unix::net::UnixListener; /// # #[cfg(unix)] /// let tempsock = Builder::new().make_in("./", |path| UnixListener::bind(path))?; /// # Ok(()) /// # } /// ``` pub fn make_in(&self, dir: P, mut f: F) -> io::Result> where F: FnMut(&Utf8Path) -> io::Result, P: AsRef, { let temp_file = self.inner.make_in(dir.as_ref(), |path| { // This produces a better error message. let utf8_path = Utf8PathBuf::try_from(path.to_path_buf()).map_err(|error| error.into_io_error())?; f(&utf8_path) })?; NamedUtf8TempFile::from_temp_file(temp_file) } } camino-tempfile-1.4.1/src/dir.rs000064400000000000000000000401011046102023000146070ustar 00000000000000// Copyright (c) The camino-tempfile Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use crate::Builder; use camino::{Utf8Path, Utf8PathBuf}; use std::{ convert::{TryFrom, TryInto}, fmt, io, path::Path, }; use tempfile::TempDir; /// Create a new temporary directory. /// /// The `tempdir` function creates a directory in the file system and returns a [`Utf8TempDir`]. The /// directory will be automatically deleted when the [`Utf8TempDir`]'s destructor is run. /// /// # Resource Leaking /// /// See [the resource leaking][resource-leaking] docs on `Utf8TempDir`. /// /// # Errors /// /// If the directory can not be created, `Err` is returned. /// /// # Examples /// /// ``` /// use camino_tempfile::tempdir; /// use std::fs::File; /// use std::io::{self, Write}; /// /// # 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 dir = tempdir()?; /// /// let file_path = dir.path().join("my-temporary-note.txt"); /// let mut file = File::create(file_path)?; /// writeln!(file, "Brian was here. Briefly.")?; /// /// // `tmp_dir` goes out of scope, the directory as well as /// // `tmp_file` will be deleted here. /// drop(file); /// dir.close()?; /// # Ok(()) /// # } /// ``` /// /// [resource-leaking]: struct.Utf8TempDir.html#resource-leaking pub fn tempdir() -> io::Result { Utf8TempDir::new() } /// Create a new temporary directory in a specific directory. /// /// The `tempdir_in` function creates a directory in the specified directory and returns a /// [`Utf8TempDir`]. The directory will be automatically deleted when the [`Utf8TempDir`]'s /// destructor is run. /// /// # Resource Leaking /// /// See [the resource leaking][resource-leaking] docs on `Utf8TempDir`. /// /// # Errors /// /// If the directory can not be created, `Err` is returned. /// /// # Examples /// /// ``` /// use camino_tempfile::tempdir_in; /// use std::fs::File; /// use std::io::{self, Write}; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// // Create a directory inside of the current directory. /// let dir = tempdir_in(".")?; /// /// let file_path = dir.path().join("my-temporary-note.txt"); /// let mut file = File::create(file_path)?; /// writeln!(file, "Brian was here. Briefly.")?; /// /// // `tmp_dir` goes out of scope, the directory as well as /// // `tmp_file` will be deleted here. /// drop(file); /// dir.close()?; /// # Ok(()) /// # } /// ``` /// /// [resource-leaking]: struct.TempDir.html#resource-leaking pub fn tempdir_in>(dir: P) -> io::Result { Utf8TempDir::new_in(dir) } /// A directory in the filesystem that is automatically deleted when it goes out of scope. /// /// The [`Utf8TempDir`] type creates a directory on the file system that is deleted once it goes out /// of scope. At construction, the [`Utf8TempDir`] creates a new directory with a randomly generated /// name. /// /// The default constructor, [`Utf8TempDir::new()`], creates directories in the location returned by /// [`std::env::temp_dir()`], but `Utf8TempDir` can be configured to manage a temporary directory in /// any location by constructing with a [`Builder`]. /// /// After creating a `Utf8TempDir`, work with the file system by doing standard [`std::fs`] file /// system operations on its [`Utf8Path`], which can be retrieved with [`Utf8TempDir::path()`]. Once /// the `Utf8TempDir` 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. /// /// # Resource Leaking /// /// Various platform-specific conditions may cause `Utf8TempDir` to fail to delete the underlying /// directory. It's important to ensure that handles (like [`File`](std::fs::File) and /// [`ReadDir`](std::fs::ReadDir)) to files inside the directory are dropped before the `TempDir` /// goes out of scope. The `Utf8TempDir` destructor will silently ignore any errors in deleting the /// directory; to instead handle errors call [`Utf8TempDir::close()`]. /// /// Note that if the program exits before the `Utf8TempDir` 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. /// /// # Examples /// /// Create a temporary directory with a generated name: /// /// ``` /// use std::fs::File; /// use std::io::Write; /// use camino_tempfile::Utf8TempDir; /// /// # use std::io; /// # fn run() -> Result<(), io::Error> { /// // Create a directory inside of `std::env::temp_dir()` /// let tmp_dir = Utf8TempDir::new()?; /// # Ok(()) /// # } /// ``` /// /// Create a temporary directory with a prefix in its name: /// /// ``` /// use std::fs::File; /// use std::io::Write; /// use camino_tempfile::Builder; /// /// # use std::io; /// # fn run() -> Result<(), io::Error> { /// // Create a directory inside of `std::env::temp_dir()`, /// // whose name will begin with 'example'. /// let tmp_dir = Builder::new().prefix("example").tempdir()?; /// # Ok(()) /// # } /// ``` pub struct Utf8TempDir { inner: TempDir, } impl Utf8TempDir { pub(crate) fn from_temp_dir(inner: TempDir) -> io::Result { let path = inner.path(); // This produces a better error message. Utf8PathBuf::try_from(path.to_path_buf()).map_err(|error| error.into_io_error())?; Ok(Self { inner }) } /// Attempts to make a temporary directory inside of `env::temp_dir()`. /// /// See [`Builder`] for more configuration. /// /// The directory and everything inside it will be automatically deleted once the returned /// `Utf8TempDir` is destroyed. /// /// # Errors /// /// If the directory can not be created, or if `env::temp_dir` is a non-UTF-8 path, `Err` is /// returned. /// /// # Examples /// /// ``` /// use std::fs::File; /// use std::io::Write; /// use camino_tempfile::Utf8TempDir; /// /// # use std::io; /// # fn run() -> Result<(), io::Error> { /// // Create a directory inside of `std::env::temp_dir()` /// let tmp_dir = Utf8TempDir::new()?; /// /// 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() -> io::Result { Builder::new().tempdir() } /// Attempts to make a temporary directory inside of `dir`. The directory and everything inside /// it will be automatically deleted once the returned `Utf8TempDir` is destroyed. /// /// # Errors /// /// If the directory can not be created, `Err` is returned. /// /// # Examples /// /// ``` /// use std::fs::{self, File}; /// use std::io::Write; /// use camino_tempfile::Utf8TempDir; /// /// # use std::io; /// # fn run() -> Result<(), io::Error> { /// // Create a directory inside of the current directory /// let tmp_dir = Utf8TempDir::new_in(".")?; /// 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>(dir: P) -> io::Result { Builder::new().tempdir_in(dir) } /// Attempts to make a temporary directory with the specified prefix inside of /// `env::temp_dir()`. The directory and everything inside it will be automatically /// deleted once the returned `Utf8TempDir` is destroyed. /// /// # Errors /// /// If the directory can not be created, `Err` is returned. /// /// # Examples /// /// ``` /// use std::fs::{self, File}; /// use std::io::Write; /// use camino_tempfile::Utf8TempDir; /// /// # use std::io; /// # fn run() -> Result<(), io::Error> { /// // Create a directory inside of the current directory /// let tmp_dir = Utf8TempDir::with_prefix("foo-")?; /// let tmp_name = tmp_dir.path().file_name().unwrap(); /// assert!(tmp_name.starts_with("foo-")); /// # Ok(()) /// # } /// ``` pub fn with_prefix>(prefix: S) -> io::Result { Builder::new().prefix(&prefix).tempdir() } /// Attempts to make a temporary directory with the specified prefix inside /// the specified directory. The directory and everything inside it will be /// automatically deleted once the returned `Utf8TempDir` is destroyed. /// /// # Errors /// /// If the directory can not be created, `Err` is returned. /// /// # Examples /// /// ``` /// use std::fs::{self, File}; /// use std::io::Write; /// use camino_tempfile::Utf8TempDir; /// /// # use std::io; /// # fn run() -> Result<(), io::Error> { /// // Create a directory inside of the current directory /// let tmp_dir = Utf8TempDir::with_prefix_in("foo-", ".")?; /// let tmp_name = tmp_dir.path().file_name().unwrap(); /// assert!(tmp_name.starts_with("foo-")); /// # Ok(()) /// # } /// ``` pub fn with_prefix_in, P: AsRef>( prefix: S, dir: P, ) -> io::Result { Builder::new().prefix(&prefix).tempdir_in(dir) } /// Attempts to make a temporary directory with the specified suffix inside of /// `env::temp_dir()`. 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 camino_tempfile::Utf8TempDir; /// /// // Create a directory inside of the current directory /// let tmp_dir = Utf8TempDir::with_suffix("-foo")?; /// let tmp_name = tmp_dir.path().file_name().unwrap(); /// assert!(tmp_name.ends_with("-foo")); /// # Ok::<(), std::io::Error>(()) /// ``` pub fn with_suffix>(suffix: S) -> io::Result { Builder::new().suffix(&suffix).tempdir() } /// Attempts to make a temporary directory with the specified suffix inside /// the specified directory. 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 camino_tempfile::Utf8TempDir; /// /// // Create a directory inside of the current directory /// let tmp_dir = Utf8TempDir::with_suffix_in("-foo", ".")?; /// let tmp_name = tmp_dir.path().file_name().unwrap(); /// assert!(tmp_name.ends_with("-foo")); /// # Ok::<(), std::io::Error>(()) /// ``` pub fn with_suffix_in, P: AsRef>( suffix: S, dir: P, ) -> io::Result { Builder::new().suffix(&suffix).tempdir_in(dir) } /// Accesses the [`Utf8Path`] to the temporary directory. /// /// # Examples /// /// ``` /// use camino_tempfile::Utf8TempDir; /// /// # use std::io; /// # fn run() -> Result<(), io::Error> { /// let tmp_path; /// /// { /// let tmp_dir = Utf8TempDir::new()?; /// 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(()) /// # } /// ``` #[must_use] pub fn path(&self) -> &Utf8Path { self.as_ref() } /// Deprecated alias for [`Utf8TempDir::keep`]. #[must_use] #[deprecated(since = "1.4.0", note = "use Utf8TempDir::keep")] pub fn into_path(self) -> Utf8PathBuf { self.keep() } /// Persist the temporary directory to disk, returning the [`Utf8PathBuf`] where it is located. /// /// This consumes the [`Utf8TempDir`] without deleting directory on the filesystem, meaning that /// the directory will no longer be automatically deleted. /// /// # Examples /// /// ``` /// use std::fs; /// use camino_tempfile::Utf8TempDir; /// /// # use std::io; /// # fn run() -> Result<(), io::Error> { /// let tmp_dir = Utf8TempDir::new()?; /// /// // Persist the temporary directory to disk, /// // getting the path where it is. /// let tmp_path = tmp_dir.keep(); /// /// // Delete the temporary directory ourselves. /// fs::remove_dir_all(tmp_path)?; /// # Ok(()) /// # } /// ``` #[must_use] pub fn keep(self) -> Utf8PathBuf { self.inner .keep() .try_into() .expect("invariant: path is valid UTF-8") } /// Disable cleanup of the temporary directory. If `disable_cleanup` is /// `true`, the temporary directory will not be deleted when this /// `Utf8TempDir` is dropped. This method is equivalent to calling /// [`Builder::disable_cleanup`] when creating the `Utf8TempDir`. /// /// **NOTE:** this method is primarily useful for testing/debugging. If you /// want to simply turn a temporary directory into a non-temporary /// directory, prefer [`Utf8TempDir::keep`]. pub fn disable_cleanup(&mut self, disable_cleanup: bool) { self.inner.disable_cleanup(disable_cleanup); } /// Closes and removes the temporary directory, returning a `Result`. /// /// Although `Utf8TempDir` 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. /// /// # Examples /// /// ``` /// use std::fs::File; /// use std::io::Write; /// use camino_tempfile::Utf8TempDir; /// /// # use std::io; /// # fn run() -> Result<(), io::Error> { /// // Create a directory inside of `std::env::temp_dir()`. /// let tmp_dir = Utf8TempDir::new()?; /// 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 `Utf8TempDir` 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(self) -> io::Result<()> { self.inner.close() } } impl AsRef for Utf8TempDir { #[inline] fn as_ref(&self) -> &Utf8Path { let path: &Path = self.as_ref(); path.try_into().expect("invariant: path is valid UTF-8") } } impl AsRef for Utf8TempDir { fn as_ref(&self) -> &Path { self.inner.path() } } impl fmt::Debug for Utf8TempDir { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Utf8TempDir") .field("path", &self.path()) .finish() } } // The Drop impl is implicit since `Utf8TempDir` wraps a `TempDir`. camino-tempfile-1.4.1/src/errors.rs000064400000000000000000000021121046102023000153450ustar 00000000000000// Copyright (c) The camino-tempfile Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use camino::Utf8PathBuf; use std::{error, fmt, io}; #[derive(Debug)] struct Utf8PathError { path: Utf8PathBuf, err: io::Error, } impl fmt::Display for Utf8PathError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} at path {}", self.err, self.path) } } impl error::Error for Utf8PathError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { self.err.source() } } pub(crate) trait IoResultExt { fn with_err_path(self, path: F) -> Self where F: FnOnce() -> P, P: Into; } impl IoResultExt for Result { fn with_err_path(self, path: F) -> Self where F: FnOnce() -> P, P: Into, { self.map_err(|e| { io::Error::new( e.kind(), Utf8PathError { path: path().into(), err: e, }, ) }) } } camino-tempfile-1.4.1/src/file.rs000064400000000000000000001033671046102023000147660ustar 00000000000000// Copyright (c) The camino-tempfile Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use crate::{errors::IoResultExt, Builder}; use camino::{Utf8Path, Utf8PathBuf}; use std::{ convert::{TryFrom, TryInto}, error, ffi::OsStr, fmt, fs::File, io, io::{Read, Seek, SeekFrom, Write}, ops::Deref, path::Path, }; use tempfile::{NamedTempFile, TempPath}; /// Create a new temporary file. /// /// The file will be created in the location returned by [`std::env::temp_dir()`]. /// /// # Security /// /// This variant is secure/reliable in the presence of a pathological temporary file cleaner. /// /// # Resource Leaking /// /// The temporary file will be automatically removed by the OS when the last handle to it is closed. /// This doesn't rely on Rust destructors being run, so will (almost) never fail to clean up the /// temporary file. /// /// # Errors /// /// If the file can not be created, `Err` is returned. /// /// # Examples /// /// ``` /// use camino_tempfile::tempfile; /// use std::io::{self, Write}; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// // Create a file inside of `std::env::temp_dir()`. /// let mut file = tempfile()?; /// /// writeln!(file, "Brian was here. Briefly.")?; /// # Ok(()) /// # } /// ``` pub fn tempfile() -> io::Result { tempfile::tempfile() } /// Create a new temporary file in the specified directory. /// /// This method accepts `AsRef` rather than `AsRef` because it returns a /// [`std::fs::File`]. /// /// # Security /// /// This variant is secure/reliable in the presence of a pathological temporary file cleaner. If the /// temporary file isn't created in [`std::env::temp_dir()`] then temporary file cleaners aren't an /// issue. /// /// # Resource Leaking /// /// The temporary file will be automatically removed by the OS when the last handle to it is closed. /// This doesn't rely on Rust destructors being run, so will (almost) never fail to clean up the /// temporary file. /// /// # Errors /// /// If the file can not be created, `Err` is returned. /// /// # Examples /// /// ``` /// use camino_tempfile::tempfile_in; /// use std::io::{self, Write}; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// // Create a file inside of the current working directory /// let mut file = tempfile_in("./")?; /// /// writeln!(file, "Brian was here. Briefly.")?; /// # Ok(()) /// # } /// ``` pub fn tempfile_in>(dir: P) -> io::Result { tempfile::tempfile_in(dir) } /// Error returned when persisting a temporary file path fails. #[derive(Debug)] pub struct Utf8PathPersistError { /// The underlying IO error. pub error: io::Error, /// The temporary file path that couldn't be persisted. pub path: Utf8TempPath, } impl From for io::Error { #[inline] fn from(error: Utf8PathPersistError) -> io::Error { error.error } } impl From for Utf8TempPath { #[inline] fn from(error: Utf8PathPersistError) -> Utf8TempPath { error.path } } impl fmt::Display for Utf8PathPersistError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "failed to persist temporary file path: {}", self.error) } } impl error::Error for Utf8PathPersistError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { Some(&self.error) } } /// A path to a named temporary file without an open file handle. /// /// This is useful when the temporary file needs to be used by a child process, /// for example. /// /// When dropped, the temporary file is deleted. pub struct Utf8TempPath { // Invariant: inner stores a UTF-8 path. inner: TempPath, } impl Utf8TempPath { pub(crate) fn from_temp_path(inner: TempPath) -> io::Result { let path: &Path = inner.as_ref(); // This produces a better error message. Utf8PathBuf::try_from(path.to_path_buf()).map_err(|error| error.into_io_error())?; Ok(Self { inner }) } /// Close and remove the temporary file. /// /// Use this if you want to detect errors in deleting the file. /// /// # Errors /// /// If the file cannot be deleted, `Err` is returned. /// /// # Examples /// /// ```no_run /// # use std::io; /// use camino_tempfile::NamedUtf8TempFile; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// let file = NamedUtf8TempFile::new()?; /// /// // Close the file, but keep the path to it around. /// let path = file.into_temp_path(); /// /// // By closing the `Utf8TempPath` explicitly, we can check that it has /// // been deleted successfully. If we don't close it explicitly, the /// // file will still be deleted when `file` goes out of scope, but we /// // won't know whether deleting the file succeeded. /// path.close()?; /// # Ok(()) /// # } /// ``` pub fn close(self) -> io::Result<()> { self.inner.close() } /// Persist the temporary file at the target path. /// /// If a file exists at the target path, persist will atomically replace it. If this method /// fails, it will return `self` in the resulting [`Utf8PathPersistError`]. /// /// # Notes /// /// * This method accepts `AsRef` rather than `AsRef`, because in the success /// case it does not return anything. /// * Temporary files cannot be persisted across filesystems. /// * Neither the file contents nor the containing directory are synchronized, so the update may /// not yet have reached the disk when `persist` returns. /// /// # Security /// /// Only use this method if you're positive that a temporary file cleaner won't have deleted /// your file. Otherwise, you might end up persisting an attacker controlled file. /// /// # Errors /// /// If the file cannot be moved to the new location, `Err` is returned. /// /// # Examples /// /// ```no_run /// # use std::io::{self, Write}; /// use camino_tempfile::NamedUtf8TempFile; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// let mut file = NamedUtf8TempFile::new()?; /// writeln!(file, "Brian was here. Briefly.")?; /// /// let path = file.into_temp_path(); /// path.persist("./saved_file.txt")?; /// # Ok(()) /// # } /// ``` /// /// [`PathPersistError`]: struct.PathPersistError.html pub fn persist>(self, new_path: P) -> Result<(), Utf8PathPersistError> { self.inner.persist(new_path.as_ref()).map_err(|error| { Utf8PathPersistError { error: error.error, // This is OK because the path returned here is self path: Self { inner: error.path }, } }) } /// Persist the temporary file at the target path if and only if no file exists there. /// /// If a file exists at the target path, fail. If this method fails, it will return `self` in /// the resulting [`Utf8PathPersistError`]. /// /// # Notes /// /// * This method accepts `AsRef` rather than `AsRef`, because in the success /// case it does not return anything. /// * Temporary files cannot be persisted across filesystems. /// * This method is not atomic. It can leave the original link to the temporary file behind. /// /// # Security /// /// Only use this method if you're positive that a temporary file cleaner won't have deleted /// your file. Otherwise, you might end up persisting an attacker controlled file. /// /// # Errors /// /// If the file cannot be moved to the new location or a file already exists there, `Err` is /// returned. /// /// # Examples /// /// ```no_run /// # use std::io::{self, Write}; /// use camino_tempfile::NamedUtf8TempFile; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// let mut file = NamedUtf8TempFile::new()?; /// writeln!(file, "Brian was here. Briefly.")?; /// /// let path = file.into_temp_path(); /// path.persist_noclobber("./saved_file.txt")?; /// # Ok(()) /// # } /// ``` /// /// [`PathPersistError`]: struct.PathPersistError.html pub fn persist_noclobber>( self, new_path: P, ) -> Result<(), Utf8PathPersistError> { self.inner .persist_noclobber(new_path.as_ref()) .map_err(|error| { Utf8PathPersistError { error: error.error, // This is OK because the path returned here is self path: Self { inner: error.path }, } }) } /// Keep the temporary file from being deleted. This function will turn the temporary file into /// a non-temporary file without moving it. /// /// /// # Errors /// /// On some platforms (e.g., Windows), we need to mark the file as non-temporary. This operation /// could fail. /// /// # Examples /// /// ```no_run /// # use std::io::{self, Write}; /// use camino_tempfile::NamedUtf8TempFile; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// let mut file = NamedUtf8TempFile::new()?; /// writeln!(file, "Brian was here. Briefly.")?; /// /// let path = file.into_temp_path(); /// let path = path.keep()?; /// # Ok(()) /// # } /// ``` pub fn keep(self) -> Result { match self.inner.keep() { Ok(path) => Ok(Utf8PathBuf::try_from(path).expect("invariant: path is UTF-8")), Err(error) => { Err(Utf8PathPersistError { error: error.error, // This is OK because the path returned here is self path: Self { inner: error.path }, }) } } } /// Disable cleanup of the temporary file. If `disable_cleanup` is `true`, /// the temporary file will not be deleted when this `Utf8TempPath` is /// dropped. This method is equivalent to calling /// [`Builder::disable_cleanup`] when creating the original `Utf8TempPath`, /// which see for relevant warnings. /// /// **NOTE:** this method is primarily useful for testing/debugging. If you /// want to simply turn a temporary file-path into a non-temporary /// file-path, prefer [`Utf8TempPath::keep`]. pub fn disable_cleanup(&mut self, disable_cleanup: bool) { self.inner.disable_cleanup(disable_cleanup); } /// Create a new `Utf8TempPath` from an existing path. This can be done even if no file exists /// at the given path. /// /// This is mostly useful for interacting with libraries and external components that provide /// files to be consumed or expect a path with no existing file to be given. pub fn from_path(path: impl Into) -> Self { Self { inner: TempPath::from_path(path.into()), } } } impl fmt::Debug for Utf8TempPath { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.inner.fmt(f) } } impl Deref for Utf8TempPath { type Target = Utf8Path; fn deref(&self) -> &Utf8Path { self.inner .deref() .try_into() .expect("invariant: path is UTF-8") } } impl AsRef for Utf8TempPath { #[inline] fn as_ref(&self) -> &Utf8Path { let path: &Path = self.as_ref(); path.try_into().expect("invariant: path is valid UTF-8") } } impl AsRef for Utf8TempPath { #[inline] fn as_ref(&self) -> &Path { self.inner.as_ref() } } impl AsRef for Utf8TempPath { #[inline] fn as_ref(&self) -> &str { let path: &Utf8Path = self.as_ref(); path.as_str() } } impl AsRef for Utf8TempPath { #[inline] fn as_ref(&self) -> &OsStr { let path: &Path = self.as_ref(); path.as_os_str() } } /// A named temporary file. /// /// The default constructor, [`NamedUtf8TempFile::new()`], creates files in /// the location returned by [`std::env::temp_dir()`], but `NamedUtf8TempFile` /// can be configured to manage a temporary file in any location /// by constructing with [`NamedUtf8TempFile::new_in()`]. /// /// # Security /// /// Most operating systems employ temporary file cleaners to delete old /// temporary files. Unfortunately these temporary file cleaners don't always /// reliably _detect_ whether the temporary file is still being used. /// /// Specifically, the following sequence of events can happen: /// /// 1. A user creates a temporary file with `NamedUtf8TempFile::new()`. /// 2. Time passes. /// 3. The temporary file cleaner deletes (unlinks) the temporary file from the /// filesystem. /// 4. Some other program creates a new file to replace this deleted temporary /// file. /// 5. The user tries to re-open the temporary file (in the same program or in a /// different program) by path. Unfortunately, they'll end up opening the /// file created by the other program, not the original file. /// /// ## Operating System Specific Concerns /// /// The behavior of temporary files and temporary file cleaners differ by /// operating system. /// /// ### Windows /// /// On Windows, open files _can't_ be deleted. This removes most of the concerns /// around temporary file cleaners. /// /// Furthermore, temporary files are, by default, created in per-user temporary /// file directories so only an application running as the same user would be /// able to interfere (which they could do anyways). However, an application /// running as the same user can still _accidentally_ re-create deleted /// temporary files if the number of random bytes in the temporary file name is /// too small. /// /// So, the only real concern on Windows is: /// /// 1. Opening a named temporary file in a world-writable directory. /// 2. Using the `into_temp_path()` and/or `into_parts()` APIs to close the file /// handle without deleting the underlying file. /// 3. Continuing to use the file by path. /// /// ### UNIX /// /// Unlike on Windows, UNIX (and UNIX like) systems allow open files to be /// "unlinked" (deleted). /// /// #### MacOS /// /// Like on Windows, temporary files are created in per-user temporary file /// directories by default so calling `NamedUtf8TempFile::new()` should be /// relatively safe. /// /// #### Linux /// /// Unfortunately, most _Linux_ distributions don't create per-user temporary /// file directories. Worse, systemd's tmpfiles daemon (a common temporary file /// cleaner) will happily remove open temporary files if they haven't been /// modified within the last 10 days. /// /// # Resource Leaking /// /// If the program exits before the `NamedUtf8TempFile` destructor is /// run, the temporary file will not be deleted. This can happen /// if the process exits using [`std::process::exit()`], a segfault occurs, /// receiving an interrupt signal like `SIGINT` that is not handled, or by using /// a statically declared `NamedUtf8TempFile` instance (like with `lazy_static`). /// /// Use the [`tempfile()`] function unless you need a named file path. pub struct NamedUtf8TempFile { // Invariant: inner.path is a valid Utf8TempPath inner: NamedTempFile, } impl NamedUtf8TempFile { pub(crate) fn from_temp_file(inner: NamedTempFile) -> io::Result { let path = inner.path(); // This produces a better error message. Utf8PathBuf::try_from(path.to_owned()).map_err(|error| error.into_io_error())?; Ok(Self { inner }) } } impl fmt::Debug for NamedUtf8TempFile { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "NamedUtf8TempFile({})", self.path()) } } impl AsRef for NamedUtf8TempFile { #[inline] fn as_ref(&self) -> &Utf8Path { self.path() } } impl AsRef for NamedUtf8TempFile { #[inline] fn as_ref(&self) -> &Path { self.path().as_std_path() } } impl NamedUtf8TempFile { /// Create a new named temporary file. /// /// See [`Builder`] for more configuration. /// /// # Security /// /// This will create a temporary file in the default temporary file /// directory (platform dependent). This has security implications on many /// platforms so please read the security section of this type's /// documentation. /// /// Reasons to use this method: /// /// 1. The file has a short lifetime and your temporary file cleaner is /// sane (doesn't delete recently accessed files). /// /// 2. You trust every user on your system (i.e. you are the only user). /// /// 3. You have disabled your system's temporary file cleaner or verified /// that your system doesn't have a temporary file cleaner. /// /// Reasons not to use this method: /// /// 1. You'll fix it later. No you won't. /// /// 2. You don't care about the security of the temporary file. If none of /// the "reasons to use this method" apply, referring to a temporary /// file by name may allow an attacker to create/overwrite your /// non-temporary files. There are exceptions but if you don't already /// know them, don't use this method. /// /// # Errors /// /// If the file can not be created, `Err` is returned. /// /// # Examples /// /// Create a named temporary file and write some data to it: /// /// ```no_run /// # use std::io::{self, Write}; /// use camino_tempfile::NamedUtf8TempFile; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), ::std::io::Error> { /// let mut file = NamedUtf8TempFile::new()?; /// /// writeln!(file, "Brian was here. Briefly.")?; /// # Ok(()) /// # } /// ``` /// /// [`Builder`]: struct.Builder.html pub fn new() -> io::Result { Builder::new().tempfile() } /// Create a new named temporary file in the specified directory. /// /// See [`NamedUtf8TempFile::new()`] for details. pub fn new_in>(dir: P) -> io::Result { Builder::new().tempfile_in(dir) } /// Create a new named temporary file with the specified filename prefix. /// /// See [`NamedUtf8TempFile::new()`] for details. pub fn with_prefix>(prefix: S) -> io::Result { Builder::new().prefix(&prefix).tempfile() } /// Create a new named temporary file with the specified filename prefix, /// in the specified directory. /// /// This is equivalent to: /// /// ```ignore /// Builder::new().prefix(&prefix).tempfile_in(directory) /// ``` /// /// See [`NamedUtf8TempFile::new()`] for details. pub fn with_prefix_in, P: AsRef>( prefix: S, dir: P, ) -> io::Result { Builder::new().prefix(&prefix).tempfile_in(dir) } /// Create a new named temporary file with the specified filename suffix. /// /// See [`NamedUtf8TempFile::new()`] for details. pub fn with_suffix>(suffix: S) -> io::Result { Builder::new().suffix(&suffix).tempfile() } /// Create a new named temporary file with the specified filename suffix, /// in the specified directory. /// /// This is equivalent to: /// /// ```ignore /// Builder::new().suffix(&suffix).tempfile_in(directory) /// ``` /// /// See [`NamedUtf8TempFile::new()`] for details. pub fn with_suffix_in, P: AsRef>( suffix: S, dir: P, ) -> io::Result { Builder::new().suffix(&suffix).tempfile_in(dir) } } impl NamedUtf8TempFile { /// Get the temporary file's path. /// /// # Security /// /// Referring to a temporary file's path may not be secure in all cases. /// Please read the security section on the top level documentation of this /// type for details. /// /// # Examples /// /// ```no_run /// # use std::io::{self, Write}; /// use camino_tempfile::NamedUtf8TempFile; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), ::std::io::Error> { /// let file = NamedUtf8TempFile::new()?; /// /// println!("{}", file.path()); /// # Ok(()) /// # } /// ``` #[inline] pub fn path(&self) -> &Utf8Path { self.inner .path() .try_into() .expect("invariant: path is valid UTF-8") } /// Close and remove the temporary file. /// /// Use this if you want to detect errors in deleting the file. /// /// # Errors /// /// If the file cannot be deleted, `Err` is returned. /// /// # Examples /// /// ```no_run /// # use std::io; /// use camino_tempfile::NamedUtf8TempFile; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// let file = NamedUtf8TempFile::new()?; /// /// // By closing the `NamedUtf8TempFile` explicitly, we can check that it /// // has been deleted successfully. If we don't close it explicitly, /// // the file will still be deleted when `file` goes out /// // of scope, but we won't know whether deleting the file /// // succeeded. /// file.close()?; /// # Ok(()) /// # } /// ``` pub fn close(self) -> io::Result<()> { self.inner.close() } /// Persist the temporary file at the target path. /// /// If a file exists at the target path, persist will atomically replace it. If this method /// fails, it will return `self` in the resulting [`Utf8PersistError`]. /// /// # Notes /// /// * This method accepts `AsRef` rather than `AsRef` because it returns the /// underlying file type `F`. /// * Temporary files cannot be persisted across filesystems. /// * Neither the file contents nor the containing directory are synchronized, so the update may /// not yet have reached the disk when `persist` returns. /// /// # Security /// /// This method persists the temporary file using its path and may not be secure in the in all /// cases. Please read the security section on the top level documentation of this type for /// details. /// /// # Errors /// /// If the file cannot be moved to the new location, `Err` is returned. /// /// # Examples /// /// ```no_run /// # use std::io::{self, Write}; /// use camino_tempfile::NamedUtf8TempFile; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// let file = NamedUtf8TempFile::new()?; /// /// let mut persisted_file = file.persist("./saved_file.txt")?; /// writeln!(persisted_file, "Brian was here. Briefly.")?; /// # Ok(()) /// # } /// ``` /// /// [`PersistError`]: struct.PersistError.html pub fn persist>(self, new_path: P) -> Result> { self.inner.persist(new_path).map_err(|error| { Utf8PersistError { // This is valid because self is exactly error.file. file: NamedUtf8TempFile { inner: error.file }, error: error.error, } }) } /// Persist the temporary file at the target path if and only if no file exists there. /// /// If a file exists at the target path, fail. If this method fails, it will return `self` in /// the resulting [`Utf8PersistError`]. /// /// # Notes /// /// * This method accepts `AsRef` rather than `AsRef` because it returns the /// underlying file type `F`. /// * Temporary files cannot be persisted across filesystems. /// * This method is not atomic. It can leave the original link to the temporary file behind. /// /// # Security /// /// This method persists the temporary file using its path and may not be secure in the in all /// cases. Please read the security section on the top level documentation of this type for /// details. /// /// # Errors /// /// If the file cannot be moved to the new location or a file already exists there, `Err` is /// returned. /// /// # Examples /// /// ```no_run /// # use std::io::{self, Write}; /// use camino_tempfile::NamedUtf8TempFile; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// let file = NamedUtf8TempFile::new()?; /// /// let mut persisted_file = file.persist_noclobber("./saved_file.txt")?; /// writeln!(persisted_file, "Brian was here. Briefly.")?; /// # Ok(()) /// # } /// ``` pub fn persist_noclobber>(self, new_path: P) -> Result> { self.inner.persist_noclobber(new_path).map_err(|error| { Utf8PersistError { // This is valid because self is exactly error.file. file: NamedUtf8TempFile { inner: error.file }, error: error.error, } }) } /// Keep the temporary file from being deleted. This function will turn the /// temporary file into a non-temporary file without moving it. /// /// /// # Errors /// /// On some platforms (e.g., Windows), we need to mark the file as /// non-temporary. This operation could fail. /// /// # Examples /// /// ```no_run /// # use std::io::{self, Write}; /// use camino_tempfile::NamedUtf8TempFile; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// let mut file = NamedUtf8TempFile::new()?; /// writeln!(file, "Brian was here. Briefly.")?; /// /// let (file, path) = file.keep()?; /// # Ok(()) /// # } /// ``` /// /// [`PathPersistError`]: struct.PathPersistError.html pub fn keep(self) -> Result<(F, Utf8PathBuf), Utf8PersistError> { match self.inner.keep() { Ok((file, path)) => Ok(( file, path.try_into().expect("invariant: path is valid UTF-8"), )), Err(error) => Err(Utf8PersistError { // This is valid because self is exactly error.file. file: NamedUtf8TempFile { inner: error.file }, error: error.error, }), } } /// Disable cleanup of the temporary file. If `disable_cleanup` is `true`, /// the temporary file will not be deleted when this `NamedUtf8TempFile` is /// dropped. This method is equivalent to calling /// [`Builder::disable_cleanup`] when creating the original /// `NamedUtf8TempFile`, which see for relevant warnings. /// /// **NOTE:** this method is primarily useful for testing/debugging. If you /// want to simply turn a temporary file into a non-temporary file, prefer /// [`NamedUtf8TempFile::keep`]. pub fn disable_cleanup(&mut self, disable_cleanup: bool) { self.inner.disable_cleanup(disable_cleanup); } /// Get a reference to the underlying file. pub fn as_file(&self) -> &F { self.inner.as_file() } /// Get a mutable reference to the underlying file. pub fn as_file_mut(&mut self) -> &mut F { self.inner.as_file_mut() } /// Convert the temporary file into a `std::fs::File`. /// /// The inner file will be deleted. pub fn into_file(self) -> F { self.inner.into_file() } /// Closes the file, leaving only the temporary file path. /// /// This is useful when another process must be able to open the temporary /// file. pub fn into_temp_path(self) -> Utf8TempPath { Utf8TempPath::from_temp_path(self.inner.into_temp_path()) .expect("invariant: inner path is UTF-8") } /// Converts the named temporary file into its constituent parts. /// /// Note: When the path is dropped, the file is deleted but the file handle /// is still usable. pub fn into_parts(self) -> (F, Utf8TempPath) { let (file, path) = self.inner.into_parts(); let path = Utf8TempPath::from_temp_path(path).expect("invariant: inner path is UTF-8"); (file, path) } /// Creates a `NamedUtf8TempFile` from its constituent parts. /// /// This can be used with [`NamedUtf8TempFile::into_parts`] to reconstruct the /// `NamedUtf8TempFile`. pub fn from_parts(file: F, path: Utf8TempPath) -> Self { let inner = NamedTempFile::from_parts(file, path.inner); // This is valid because it was constructed from a Utf8TempPath Self { inner } } } impl NamedUtf8TempFile { /// Securely reopen the temporary file. /// /// This function is useful when you need multiple independent handles to the same file. It's /// perfectly fine to drop the original `NamedUtf8TempFile` while holding on to `File`s returned /// by this function; the `File`s will remain usable. However, they may not be nameable. /// /// # Errors /// /// If the file cannot be reopened, `Err` is returned. /// /// # Security /// /// Unlike `File::open(my_temp_file.path())`, `NamedUtf8TempFile::reopen()` guarantees that the /// re-opened file is the _same_ file, even in the presence of pathological temporary file /// cleaners. /// /// # Examples /// /// ```no_run /// # use std::io; /// use camino_tempfile::NamedUtf8TempFile; /// /// # fn main() { /// # if let Err(_) = run() { /// # ::std::process::exit(1); /// # } /// # } /// # fn run() -> Result<(), io::Error> { /// let file = NamedUtf8TempFile::new()?; /// /// let another_handle = file.reopen()?; /// # Ok(()) /// # } /// ``` pub fn reopen(&self) -> io::Result { self.inner.reopen() } } impl Read for NamedUtf8TempFile { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.as_file_mut().read(buf).with_err_path(|| self.path()) } } impl Read for &NamedUtf8TempFile { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.as_file().read(buf).with_err_path(|| self.path()) } } impl Write for NamedUtf8TempFile { fn write(&mut self, buf: &[u8]) -> io::Result { self.as_file_mut().write(buf).with_err_path(|| self.path()) } #[inline] fn flush(&mut self) -> io::Result<()> { self.as_file_mut().flush().with_err_path(|| self.path()) } } impl Write for &NamedUtf8TempFile { fn write(&mut self, buf: &[u8]) -> io::Result { self.as_file().write(buf).with_err_path(|| self.path()) } #[inline] fn flush(&mut self) -> io::Result<()> { self.as_file().flush().with_err_path(|| self.path()) } } impl Seek for NamedUtf8TempFile { fn seek(&mut self, pos: SeekFrom) -> io::Result { self.as_file_mut().seek(pos).with_err_path(|| self.path()) } } impl Seek for &NamedUtf8TempFile { fn seek(&mut self, pos: SeekFrom) -> io::Result { self.as_file().seek(pos).with_err_path(|| self.path()) } } #[cfg(unix)] impl std::os::unix::io::AsRawFd for NamedUtf8TempFile where F: std::os::unix::io::AsRawFd, { #[inline] fn as_raw_fd(&self) -> std::os::unix::io::RawFd { self.as_file().as_raw_fd() } } #[cfg(windows)] impl std::os::windows::io::AsRawHandle for NamedUtf8TempFile where F: std::os::windows::io::AsRawHandle, { #[inline] fn as_raw_handle(&self) -> std::os::windows::io::RawHandle { self.as_file().as_raw_handle() } } /// Error returned when persisting a temporary file fails. pub struct Utf8PersistError { /// The underlying IO error. pub error: io::Error, /// The temporary file that couldn't be persisted. pub file: NamedUtf8TempFile, } impl fmt::Debug for Utf8PersistError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Utf8PersistError({:?})", self.error) } } impl From> for io::Error { #[inline] fn from(error: Utf8PersistError) -> io::Error { error.error } } impl From> for NamedUtf8TempFile { #[inline] fn from(error: Utf8PersistError) -> NamedUtf8TempFile { error.file } } impl fmt::Display for Utf8PersistError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "failed to persist temporary file: {}", self.error) } } impl error::Error for Utf8PersistError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { Some(&self.error) } } camino-tempfile-1.4.1/src/helpers.rs000064400000000000000000000004641046102023000155030ustar 00000000000000// Copyright (c) The camino-tempfile Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use camino::Utf8PathBuf; use std::{convert::TryFrom, env, io}; pub(crate) fn utf8_env_temp_dir() -> io::Result { Utf8PathBuf::try_from(env::temp_dir()).map_err(|error| error.into_io_error()) } camino-tempfile-1.4.1/src/lib.rs000064400000000000000000000147131046102023000146110ustar 00000000000000// Copyright (c) The camino-tempfile Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 // Setting html_root_url allows links from camino-tempfile-ext to work. This // line is updated by cargo-release. #![doc(html_root_url = "https://docs.rs/camino-tempfile/1.4.1")] //! Temporary files and directories with UTF-8 paths. //! //! `camino-tempfile` is a wrapper around the [`tempfile`](mod@::tempfile) crate that returns //! [`Utf8Path`](camino::Utf8Path) rather than [`Path`](std::path::Path). //! //! If your code mostly uses [`camino`], it can be annoying to have to convert temporary paths to //! `Utf8Path` over and over again. This crate takes care of that for you. //! //! This library and its documentation are adapted from the [`tempfile`](mod@::tempfile) crate, and //! are used under the MIT and Apache 2.0 licenses. //! //! This crate closely mirrors tempfile's interface. For extensions that provide //! quality-of-life improvements such as the ability to create files easily, see //! [`camino-tempfile-ext`](https://crates.io/crates/camino-tempfile-ext). //! //! # Synopsis //! //! - Use the [`tempfile()`] function for temporary files //! - Use the [`tempdir()`] function for temporary directories. //! //! # Design //! //! This crate provides several approaches to creating temporary files and directories. //! [`tempfile()`] relies on the OS to remove the temporary file once the last handle is closed. //! [`Utf8TempDir`] and [`NamedUtf8TempFile`] both rely on Rust destructors for cleanup. //! //! When choosing between the temporary file variants, prefer `tempfile` unless you either need to //! know the file's path or to be able to persist it. //! //! ## Resource Leaking //! //! [`tempfile()`] will (almost) never fail to cleanup temporary resources. However, [`Utf8TempDir`] //! and [`NamedUtf8TempFile`] will fail if their destructors don't run. This is because //! [`tempfile()`] relies on the OS to cleanup the underlying file, while [`Utf8TempDir`] and //! [`NamedUtf8TempFile`] rely on Rust destructors to do so. Destructors may fail to run if the //! process exits through an unhandled signal interrupt (like `SIGINT`), or if the instance is //! declared statically, among other possible reasons. //! //! ## Security //! //! In the presence of pathological temporary file cleaner, relying on file paths is unsafe because //! a temporary file cleaner could delete the temporary file which an attacker could then replace. //! //! [`tempfile()`] doesn't rely on file paths so this isn't an issue. However, [`NamedUtf8TempFile`] //! does rely on file paths for _some_ operations. See the security documentation on the //! [`NamedUtf8TempFile`] type for more information. //! //! ## Early drop pitfall //! //! Because [`Utf8TempDir`] and [`NamedUtf8TempFile`] 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` or `AsRef`. Consider the following example: //! //! ```no_run //! # use camino_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 //! [`Utf8TempDir`] into the `current_dir` call would result in the [`Utf8TempDir`] 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: //! //! ``` //! use camino_tempfile::tempfile; //! use std::io::{self, Write}; //! //! # fn main() { //! # if let Err(_) = run() { //! # ::std::process::exit(1); //! # } //! # } //! # fn run() -> Result<(), io::Error> { //! // Create a file inside of `std::env::temp_dir()`. //! let mut file = tempfile()?; //! //! writeln!(file, "Brian was here. Briefly.")?; //! # Ok(()) //! # } //! ``` //! //! Create a named temporary file and open an independent file handle: //! //! ``` //! use camino_tempfile::NamedUtf8TempFile; //! use std::io::{self, Write, Read}; //! //! # fn main() { //! # if let Err(_) = run() { //! # ::std::process::exit(1); //! # } //! # } //! # fn run() -> Result<(), io::Error> { //! let text = "Brian was here. Briefly."; //! //! // Create a file inside of `std::env::temp_dir()`. //! let mut file1 = NamedUtf8TempFile::new()?; //! //! // Re-open it. //! let mut file2 = file1.reopen()?; //! //! // Write some test data to the first handle. //! file1.write_all(text.as_bytes())?; //! //! // Read the test data using the second handle. //! let mut buf = String::new(); //! file2.read_to_string(&mut buf)?; //! assert_eq!(buf, text); //! # Ok(()) //! # } //! ``` //! //! Create a temporary directory and add a file to it: //! //! ``` //! use camino_tempfile::tempdir; //! use std::fs::File; //! use std::io::{self, Write}; //! //! # 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 dir = tempdir()?; //! //! let file_path = dir.path().join("my-temporary-note.txt"); //! let mut file = File::create(file_path)?; //! writeln!(file, "Brian was here. Briefly.")?; //! //! // By closing the `Utf8TempDir` explicitly, we can check that it has //! // been deleted successfully. If we don't close it explicitly, //! // the directory will still be deleted when `dir` goes out //! // of scope, but we won't know whether deleting the directory //! // succeeded. //! drop(file); //! dir.close()?; //! # Ok(()) //! # } //! ``` #![deny(rust_2018_idioms)] mod builder; mod dir; mod errors; mod file; mod helpers; pub use builder::*; pub use dir::*; pub use file::*; camino-tempfile-1.4.1/tests/namedtempfile.rs000064400000000000000000000255301046102023000172270ustar 00000000000000#![deny(rust_2018_idioms)] use camino::{Utf8Path, Utf8PathBuf}; use camino_tempfile::{tempdir, Builder, NamedUtf8TempFile, Utf8TempPath}; use std::{ env, fs::File, io::{Read, Seek, SeekFrom, Write}, path::Path, }; fn exists>(path: P) -> bool { std::fs::metadata(path.as_ref()).is_ok() } #[test] fn test_basic() { let mut tmpfile = NamedUtf8TempFile::new().unwrap(); write!(tmpfile, "abcde").unwrap(); tmpfile.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); tmpfile.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); } #[test] fn test_deleted() { let tmpfile = NamedUtf8TempFile::new().unwrap(); let path = tmpfile.path().to_path_buf(); assert!(exists(&path)); drop(tmpfile); assert!(!exists(&path)); } #[test] fn test_persist() { let mut tmpfile = NamedUtf8TempFile::new().unwrap(); let old_path = tmpfile.path().to_path_buf(); let persist_path = env::temp_dir().join("persisted_temporary_file"); write!(tmpfile, "abcde").unwrap(); { assert!(exists(&old_path)); let mut f = tmpfile.persist(&persist_path).unwrap(); assert!(!exists(&old_path)); // Check original file f.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); f.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); } { // Try opening it at the new path. let mut f = File::open(&persist_path).unwrap(); f.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); f.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); } std::fs::remove_file(&persist_path).unwrap(); } #[test] fn test_persist_noclobber() { let mut tmpfile = NamedUtf8TempFile::new().unwrap(); let old_path = tmpfile.path().to_path_buf(); let persist_target = NamedUtf8TempFile::new().unwrap(); let persist_path = persist_target.path().to_path_buf(); write!(tmpfile, "abcde").unwrap(); assert!(exists(&old_path)); { tmpfile = tmpfile.persist_noclobber(&persist_path).unwrap_err().into(); assert!(exists(&old_path)); std::fs::remove_file(&persist_path).unwrap(); drop(persist_target); } tmpfile.persist_noclobber(&persist_path).unwrap(); // Try opening it at the new path. let mut f = File::open(&persist_path).unwrap(); f.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); f.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); std::fs::remove_file(&persist_path).unwrap(); } #[test] fn test_customnamed() { let tmpfile = Builder::new() .prefix("tmp") .suffix(&".rs") .rand_bytes(12) .tempfile() .unwrap(); let name = tmpfile.path().file_name().unwrap(); assert!(name.starts_with("tmp")); assert!(name.ends_with(".rs")); assert_eq!(name.len(), 18); } #[test] fn test_append() { let mut tmpfile = Builder::new().append(true).tempfile().unwrap(); tmpfile.write_all(b"a").unwrap(); tmpfile.seek(SeekFrom::Start(0)).unwrap(); tmpfile.write_all(b"b").unwrap(); tmpfile.seek(SeekFrom::Start(0)).unwrap(); let mut buf = vec![0u8; 1]; tmpfile.read_exact(&mut buf).unwrap(); assert_eq!(buf, b"a"); } #[test] fn test_reopen() { let source = NamedUtf8TempFile::new().unwrap(); let mut first = source.reopen().unwrap(); let mut second = source.reopen().unwrap(); drop(source); write!(first, "abcde").expect("write failed"); let mut buf = String::new(); second.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); } #[test] fn test_into_file() { let mut file = NamedUtf8TempFile::new().unwrap(); let path = file.path().to_owned(); write!(file, "abcde").expect("write failed"); assert!(path.exists()); let mut file = file.into_file(); assert!(!path.exists()); file.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); file.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); } #[test] fn test_immut() { let tmpfile = NamedUtf8TempFile::new().unwrap(); (&tmpfile).write_all(b"abcde").unwrap(); (&tmpfile).seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); (&tmpfile).read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); } #[test] fn test_temppath() { let mut tmpfile = NamedUtf8TempFile::new().unwrap(); write!(tmpfile, "abcde").unwrap(); let path = tmpfile.into_temp_path(); assert!(path.is_file()); } #[test] fn test_temppath_persist() { let mut tmpfile = NamedUtf8TempFile::new().unwrap(); write!(tmpfile, "abcde").unwrap(); let tmppath = tmpfile.into_temp_path(); let old_path = tmppath.to_path_buf(); let persist_path = env::temp_dir().join("persisted_temppath_file"); { assert!(exists(&old_path)); tmppath.persist(&persist_path).unwrap(); assert!(!exists(&old_path)); } { // Try opening it at the new path. let mut f = File::open(&persist_path).unwrap(); f.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); f.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); } std::fs::remove_file(&persist_path).unwrap(); } #[test] fn test_temppath_persist_noclobber() { let mut tmpfile = NamedUtf8TempFile::new().unwrap(); write!(tmpfile, "abcde").unwrap(); let mut tmppath = tmpfile.into_temp_path(); let old_path = tmppath.to_path_buf(); let persist_target = NamedUtf8TempFile::new().unwrap(); let persist_path = persist_target.path().to_path_buf(); assert!(exists(&old_path)); { tmppath = tmppath.persist_noclobber(&persist_path).unwrap_err().into(); assert!(exists(&old_path)); std::fs::remove_file(&persist_path).unwrap(); drop(persist_target); } tmppath.persist_noclobber(&persist_path).unwrap(); // Try opening it at the new path. let mut f = File::open(&persist_path).unwrap(); f.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); f.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); std::fs::remove_file(&persist_path).unwrap(); } #[test] fn temp_path_from_existing() { let tmp_dir = tempdir().unwrap(); let tmp_file_path_1 = tmp_dir.path().join("testfile1"); let tmp_file_path_2 = tmp_dir.path().join("testfile2"); File::create(&tmp_file_path_1).unwrap(); assert!(tmp_file_path_1.exists(), "Test file 1 hasn't been created"); File::create(&tmp_file_path_2).unwrap(); assert!(tmp_file_path_2.exists(), "Test file 2 hasn't been created"); let tmp_path = Utf8TempPath::from_path(&tmp_file_path_1); assert!( tmp_file_path_1.exists(), "Test file has been deleted before dropping TempPath" ); drop(tmp_path); assert!( !tmp_file_path_1.exists(), "Test file exists after dropping TempPath" ); assert!( tmp_file_path_2.exists(), "Test file 2 has been deleted before dropping TempDir" ); } #[test] #[allow(unreachable_code)] fn temp_path_from_argument_types() { // This just has to compile return; Utf8TempPath::from_path(""); Utf8TempPath::from_path(String::new()); Utf8TempPath::from_path(Utf8Path::new("")); Utf8TempPath::from_path(Utf8PathBuf::new()); Utf8TempPath::from_path(Utf8PathBuf::new().into_boxed_path()); } #[test] fn test_write_after_close() { let path = NamedUtf8TempFile::new().unwrap().into_temp_path(); File::create(path).unwrap().write_all(b"test").unwrap(); } #[test] fn test_change_dir() { env::set_current_dir(env::temp_dir()).unwrap(); let tmpfile = NamedUtf8TempFile::new_in(".").unwrap(); let path = env::current_dir().unwrap().join(tmpfile.path()); env::set_current_dir("/").unwrap(); drop(tmpfile); assert!(!exists(path)) } #[test] fn test_into_parts() { let mut file = NamedUtf8TempFile::new().unwrap(); write!(file, "abcd").expect("write failed"); let (mut file, temp_path) = file.into_parts(); let path = temp_path.to_path_buf(); assert!(path.exists()); drop(temp_path); assert!(!path.exists()); write!(file, "efgh").expect("write failed"); file.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); file.read_to_string(&mut buf).unwrap(); assert_eq!("abcdefgh", buf); } #[test] fn test_from_parts() { let mut file = NamedUtf8TempFile::new().unwrap(); write!(file, "abcd").expect("write failed"); let (file, temp_path) = file.into_parts(); let file = NamedUtf8TempFile::from_parts(file, temp_path); assert!(file.path().exists()); } #[test] fn test_keep() { let mut tmpfile = NamedUtf8TempFile::new().unwrap(); write!(tmpfile, "abcde").unwrap(); let (mut f, temp_path) = tmpfile.into_parts(); let path; { assert!(exists(&temp_path)); path = temp_path.keep().unwrap(); assert!(exists(&path)); // Check original file f.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); f.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); } { // Try opening it again. let mut f = File::open(&path).unwrap(); f.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); f.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); } std::fs::remove_file(&path).unwrap(); } #[test] fn test_make() { let tmpfile = Builder::new().make(|path| File::create(path)).unwrap(); assert!(tmpfile.path().is_file()); } #[test] fn test_make_in() { let tmp_dir = tempdir().unwrap(); let tmpfile = Builder::new() .make_in(tmp_dir.path(), |path| File::create(path)) .unwrap(); assert!(tmpfile.path().is_file()); assert_eq!(tmpfile.path().parent(), Some(tmp_dir.path())); } #[test] fn test_make_fnmut() { let mut count = 0; // Show that an FnMut can be used. let tmpfile = Builder::new() .make(|path| { count += 1; File::create(path) }) .unwrap(); assert!(tmpfile.path().is_file()); } #[cfg(unix)] #[test] fn test_make_uds() { use std::os::unix::net::UnixListener; let temp_sock = Builder::new() .prefix("tmp") .suffix(".sock") .rand_bytes(12) .make(|path| UnixListener::bind(path)) .unwrap(); assert!(temp_sock.path().exists()); } // Issue #224 on tempfile-rs. #[test] fn test_overly_generic_bounds() { pub struct Foo(T); impl Foo where T: Sync + Send + 'static, for<'a> &'a T: Write + Read, { pub fn new(foo: T) -> Self { Self(foo) } } // Don't really need to run this. Only care if it compiles. if let Ok(file) = File::open("i_do_not_exist") { let mut f; let _x = { f = Foo::new(file); &mut f }; } } camino-tempfile-1.4.1/tests/tempdir.rs000064400000000000000000000145721046102023000160650ustar 00000000000000// 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 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(rust_2018_idioms)] use camino::Utf8Path; use camino_tempfile::{Builder, Utf8TempDir}; use std::{env, fs, path::Path, sync::mpsc::channel, thread}; macro_rules! t { ($e:expr) => { match $e { Ok(n) => n, Err(e) => panic!("error: {}", e), } }; } fn test_tempdir() { let path = { let p = t!(Builder::new() .prefix("foobar") .tempdir_in(Utf8Path::new("."))); let p = p.path(); assert!(p.as_str().contains("foobar")); p.to_path_buf() }; assert!(!path.exists()); } #[test] fn test_customnamed() { let tmpfile = Builder::new() .prefix("prefix") .suffix("suffix") .rand_bytes(12) .tempdir() .unwrap(); let name = tmpfile.path().file_name().unwrap(); assert!(name.starts_with("prefix")); assert!(name.ends_with("suffix")); assert_eq!(name.len(), 24); } fn test_rm_tempdir() { let (tx, rx) = channel(); let f = move || { let tmp = t!(Utf8TempDir::new()); 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!(Utf8TempDir::new()); 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!(Utf8TempDir::new()); let tmp = thread::spawn(f).join().unwrap(); path = tmp.path().to_path_buf(); assert!(path.exists()); } assert!(!path.exists()); let path; { let tmp = t!(Utf8TempDir::new()); path = tmp.keep(); } 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!(Utf8TempDir::new()); 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!(Utf8TempDir::new()); 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!(Utf8TempDir::new()); 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!(Utf8TempDir::new()); path = tmp.keep(); } 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!(Utf8TempDir::new()); let tmpdir = tmpdir.path(); let root = tmpdir.join("foo"); println!("making {}", root); 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 = Utf8TempDir::new().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) where F: FnOnce(), { let tmpdir = t!(Utf8TempDir::new()); assert!(env::set_current_dir(tmpdir.path()).is_ok()); f(); } pub fn pass_as_asref_path() { let tempdir = t!(Utf8TempDir::new()); takes_asref_path(&tempdir); fn takes_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); } camino-tempfile-1.4.1/tests/tempfile.rs000064400000000000000000000041151046102023000162160ustar 00000000000000#![deny(rust_2018_idioms)] use std::{ fs, io::{Read, Seek, SeekFrom, Write}, }; #[cfg(target_os = "linux")] use std::{ sync::mpsc::{sync_channel, TryRecvError}, thread, }; #[test] fn test_basic() { let mut tmpfile = camino_tempfile::tempfile().unwrap(); write!(tmpfile, "abcde").unwrap(); tmpfile.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); tmpfile.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); } #[test] fn test_cleanup() { let tmpdir = camino_tempfile::tempdir().unwrap(); { let mut tmpfile = camino_tempfile::tempfile_in(&tmpdir).unwrap(); write!(tmpfile, "abcde").unwrap(); } let num_files = fs::read_dir(&tmpdir).unwrap().count(); assert!(num_files == 0); } // Only run this test on Linux. MacOS doesn't like us creating so many files, apparently. #[cfg(target_os = "linux")] #[test] fn test_pathological_cleaner() { let tmpdir = camino_tempfile::tempdir().unwrap(); let (tx, rx) = sync_channel(0); let cleaner_thread = thread::spawn(move || { let tmp_path = rx.recv().unwrap(); while rx.try_recv() == Err(TryRecvError::Empty) { let files = fs::read_dir(&tmp_path).unwrap(); for f in files { // skip errors if f.is_err() { continue; } let f = f.unwrap(); let _ = fs::remove_file(f.path()); } } }); // block until cleaner_thread makes progress tx.send(tmpdir.path().to_owned()).unwrap(); // need 40-400 iterations to encounter race with cleaner on original system for _ in 0..10000 { let mut tmpfile = camino_tempfile::tempfile_in(&tmpdir).unwrap(); write!(tmpfile, "abcde").unwrap(); tmpfile.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); tmpfile.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); } // close the channel to make cleaner_thread exit drop(tx); cleaner_thread.join().expect("The cleaner thread failed"); }