Initial vendor packages

Signed-off-by: Valentin Popov <valentin@popov.link>
This commit is contained in:
2024-01-08 01:21:28 +04:00
parent 5ecd8cf2cb
commit 1b6a04ca55
7309 changed files with 2160054 additions and 0 deletions

1
vendor/tempfile/.cargo-checksum.json vendored Normal file
View File

@ -0,0 +1 @@
{"files":{"CHANGELOG.md":"6ca436fe5f63922174c061cb402e9b5a1e455b66a3b5677d1c191c04962b5832","Cargo.toml":"c79c844a01b8c7aec169d6506a3c588edacdfcdc835d2577b14dc064b342ac75","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"8b427f5bc501764575e52ba4f9d95673cf8f6d80a86d0d06599852e1a9a20a36","README.md":"972f1c35ec653943e067fd2c3d09e78f593b2e9e1eafd5b9668bf3653513de3e","deny.toml":"cb4c35327cbf8a20a6b19ac3fdf2c47b665da1662c90e3eae8a3825f9b72596e","src/dir.rs":"3b515f42feb934ba83ba56d506116e5e932c6b863b764fd61d26994eff28700a","src/error.rs":"cc7d8eace0fff11cb342158d2885d5637bfb14b24ef30755e808554772039c5f","src/file/imp/mod.rs":"f6da9fcd93f11889670a251fdd8231b5f4614e5a971b7b183f52b44af68568d5","src/file/imp/other.rs":"501cd1b444a5821127ea831fc8018706148f2d9f47c478f502b069963a42a2c7","src/file/imp/unix.rs":"0fa63a8b831947fdc7307e889d129adef6f47b19965b963a5e25d70cb3106e62","src/file/imp/windows.rs":"fa4211087c36290064de9a41b5e533e4e8c24a10fb8f8908835a67e00555c06e","src/file/mod.rs":"3a51ab219e0adab18324cab072fed01b0805781d6f15e79ca8b8a36543683bcc","src/lib.rs":"6303e7470c680ad785f32eb717de2e512b88c2c5da0e1684e3704471fabd7398","src/spooled.rs":"de848218bb7c0733d9c46e337564137673c95f5a6cf9f6bb28baf218b2503247","src/util.rs":"63737b9180cb769c1fcac56f1fa928221ae41a8917872d3e878d0a915e877710","tests/namedtempfile.rs":"87dd6a8bba2fdd77418ec2b50b8aec5e26d05a2f780182b4e9ff464b3404d47c","tests/spooled.rs":"a97e96404dc5136421ac027b965070c0d5b44c93d06d456e12dc85f81755d064","tests/tempdir.rs":"f5a86f56df6bb60aa5dfa136ce75f8d0f29c2e87546dccfe1fb680d209be525e","tests/tempfile.rs":"9a2f8142151a6aa2fd047aa3749f9982ece4b080a3ace0d3c58d6bdb3f883c81"},"package":"01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa"}

267
vendor/tempfile/CHANGELOG.md vendored Normal file
View File

@ -0,0 +1,267 @@
# Changelog
## 3.9.0
- Updates windows-sys to 0.52
- Updates minimum rustix version to 0.38.25
## 3.8.1
- Update rustix to fix a potential panic on `persist_noclobber` on android.
- Update redox_syscall to 0.4 (on redox).
- Fix some docs typos.
## 3.8.0
- Added `with_prefix` and `with_prefix_in` to `TempDir` and `NamedTempFile` to make it easier to create temporary files/directories with nice prefixes.
- Misc cleanups.
## 3.7.1
- Tempfile builds on haiku again.
- Under the hood, we've switched from the unlinkat/linkat syscalls to the regular unlink/link syscalls where possible.
## 3.7.0
BREAKING: This release updates the MSRV to 1.63. This isn't an API-breaking change (so no major
release) but it's still a breaking change for some users.
- Update fastrand from 1.6 to 2.0
- Update rustix to 0.38
- Updates the MSRV to 1.63.
- Provide AsFd/AsRawFd on wasi.
## 3.6.0
- Update windows-sys to 0.48.
- Update rustix min version to 0.37.11
- Forward some `NamedTempFile` and `SpooledTempFile` methods to the underlying `File` object for
better performance (especially vectorized writes, etc.).
- Implement `AsFd` and `AsHandle`.
- Misc documentation fixes and code cleanups.
## 3.5.0
- Update rustix from 0.36 to 0.37.1. This makes wasi work on rust stable
- Update `windows-sys`, `redox_syscall`
- BREAKING: Remove the implementation of `Write for &NamedTempFile<F> where &F: Write`. Unfortunately, this can cause compile issues in unrelated code (https://github.com/Stebalien/tempfile/issues/224).
## 3.4.0
SECURITY: Prior `tempfile` releases depended on `remove_dir_all` version 0.5.0 which was vulnerable to a [TOCTOU race](https://github.com/XAMPPRocky/remove_dir_all/security/advisories/GHSA-mc8h-8q98-g5hr). This same race is present in rust versions prior to 1.58.1.
Features:
- Generalized temporary files: `NamedTempFile` can now abstract over different kinds of files (e.g.,
unix domain sockets, pipes, etc.):
- Add `Builder::make` and `Builder::make_in` for generalized temp file
creation.
- Add `NamedTempFile::from_parts` to complement `NamedTempFile::into_parts`.
- Add generic parameter to `NamedTempFile` to support wrapping non-File types.
Bug Fixes/Improvements:
- Don't try to create a temporary file multiple times if the file path has been fully specified by
the user (no random characters).
- `NamedTempFile::persist_noclobber` is now always atomic on linux when `renameat_with` is
supported. Previously, it would first link the new path, then unlink the previous path.
- Fix compiler warnings on windows.
Trivia:
- Switch from `libc` to `rustix` on wasi/unix. This now makes direct syscalls instead of calling
through libc.
- Remove `remove_dir_all` dependency. The rust standard library has optimized their internal version
significantly.
- Switch to official windows-sys windows bindings.
Breaking:
- The minimum rust version is now `1.48.0`.
- Mark most functions as `must_use`.
- Uses direct syscalls on linux by default, instead of libc.
- The new type parameter in `NamedTempFile` may lead to type inference issues in some cases.
## 3.3.0
Features:
- Replace rand with fastrand for a significantly smaller dependency tree. Cryptographic randomness
isn't necessary for temporary file names, and isn't all that helpful either.
- Add limited WASI support.
- Add a function to extract the inner data from a `SpooledTempFile`.
Bug Fixes:
- Make it possible to persist unnamed temporary files on linux by removing the `O_EXCL` flag.
- Fix redox minimum crate version.
## 3.2.0
Features:
- Bump rand dependency to `0.8`.
- Bump cfg-if dependency to `1.0`
Other than that, this release mostly includes small cleanups and simplifications.
Breaking: The minimum rust version is now `1.40.0`.
## 3.1.0
Features:
- Bump rand dependency to `0.7`.
Breaking: The minimum rust version is now `1.32.0`.
## 3.0.9
Documentation:
- Add an example for reopening a named temporary file.
- Flesh out the security documentation.
Features:
- Introduce an `append` option to the builder.
- Errors:
- No longer implement the soft-deprecated `description`.
- Implement `source` instead of `cause`.
Breaking: The minimum rust version is now 1.30.
## 3.0.8
This is a bugfix release.
Fixes:
- Export `PathPersistError`.
- Fix a bug where flushing a `SpooledTempFile` to disk could fail to write part
of the file in some rare, yet-to-reproduced cases.
## 3.0.7
Breaking:
- `Builder::prefix` and `Builder::suffix` now accept a generic `&AsRef<OsStr>`.
This could affect type inference.
- Temporary files (except unnamed temporary files on Windows and Linux >= 3.11)
now use absolute path names. This will break programs that create temporary
files relative to their current working directory when they don't have the
search permission (x) on some ancestor directory. This is only likely to
affect programs with strange chroot-less filesystem sandboxes. If you believe
you're affected by this issue, please comment on #40.
Features:
- Accept anything implementing `&AsRef<OsStr>` in the builder: &OsStr, &OsString, &Path, etc.
Fixes:
- Fix LFS support.
- Use absolute paths for named temporary files to guard against changes in the
current directory.
- Use absolute paths when creating unnamed temporary files on platforms that
can't create unlinked or auto-deleted temporary files. This fixes a very
unlikely race where the current directory could change while the temporary
file is being created.
Misc:
- Use modern stdlib features to avoid custom unsafe code. This reduces the
number of unsafe blocks from 12 to 4.
## 3.0.6
- Don't hide temporary files on windows, fixing #66 and #69.
## 3.0.5
Features:
- Added a spooled temporary file implementation. This temporary file variant
starts out as an in-memory temporary file but "rolls-over" onto disk when it
grows over a specified size (#68).
- Errors are now annotated with paths to make debugging easier (#73).
Misc:
- The rand version has been bumped to 0.6 (#74).
Bugs:
- Tempfile compiles again on Redox (#75).
## 3.0.4
- Now compiles on unsupported platforms.
## 3.0.3
- update rand to 0.5
## 3.0.2
- Actually *delete* temporary files on non-Linux unix systems (thanks to
@oliverhenshaw for the fix and a test case).
## 3.0.1
- Restore NamedTempFile::new_in
## 3.0.0
- Adds temporary directory support (@KodrAus)
- Allow closing named temporary files without deleting them (@jasonwhite)
## 2.2.0
- Redox Support
## 2.1.6
- Remove build script and bump minimum rustc version to 1.9.0
## 2.1.5
- Don't build platform-specific dependencies on all platforms.
- Cleanup some documentation.
## 2.1.4
- Fix crates.io tags. No interesting changes.
## 2.1.3
Export `PersistError`.
## 2.1.2
Add `Read`/`Write`/`Seek` impls on `&NamedTempFile`. This mirrors the
implementations on `&File`. One can currently just deref to a `&File` but these
implementations are more discoverable.
## 2.1.1
Add LFS Support.
## 2.1.0
- Implement `AsRef<File>` for `NamedTempFile` allowing named temporary files to
be borrowed as `File`s.
- Add a method to convert a `NamedTempFile` to an unnamed temporary `File`.
## 2.0.1
- Arm bugfix
## 2.0.0
This release replaces `TempFile` with a `tempfile()` function that returns
`std::fs::File` objects. These are significantly more useful because most rust
libraries expect normal `File` objects.
To continue supporting shared temporary files, this new version adds a
`reopen()` method to `NamedTempFile`.

59
vendor/tempfile/Cargo.toml vendored Normal file
View File

@ -0,0 +1,59 @@
# 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 = "2018"
rust-version = "1.63"
name = "tempfile"
version = "3.9.0"
authors = [
"Steven Allen <steven@stebalien.com>",
"The Rust Project Developers",
"Ashley Mannix <ashleymannix@live.com.au>",
"Jason White <me@jasonwhite.io>",
]
description = "A library for managing temporary files and directories."
homepage = "https://stebalien.com/projects/tempfile-rs/"
documentation = "https://docs.rs/tempfile"
readme = "README.md"
keywords = [
"tempfile",
"tmpfile",
"filesystem",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/Stebalien/tempfile"
[dependencies.cfg-if]
version = "1"
[dependencies.fastrand]
version = "2.0.0"
[dev-dependencies.doc-comment]
version = "0.3"
[features]
nightly = []
[target."cfg(any(unix, target_os = \"wasi\"))".dependencies.rustix]
version = "0.38.26"
features = ["fs"]
[target."cfg(target_os = \"redox\")".dependencies.redox_syscall]
version = "0.4"
[target."cfg(windows)".dependencies.windows-sys]
version = "0.52"
features = [
"Win32_Storage_FileSystem",
"Win32_Foundation",
]

201
vendor/tempfile/LICENSE-APACHE vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
vendor/tempfile/LICENSE-MIT vendored Normal file
View File

@ -0,0 +1,25 @@
Copyright (c) 2015 Steven Allen
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.

46
vendor/tempfile/README.md vendored Normal file
View File

@ -0,0 +1,46 @@
tempfile
========
[![Crate](https://img.shields.io/crates/v/tempfile.svg)](https://crates.io/crates/tempfile)
[![Build Status](https://github.com/Stebalien/tempfile/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/Stebalien/tempfile/actions/workflows/ci.yml?query=branch%3Amaster)
A secure, cross-platform, temporary file library for Rust. 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).
[Documentation](https://docs.rs/tempfile/)
Usage
-----
Minimum required Rust version: 1.63.0
Add this to your `Cargo.toml`:
```toml
[dependencies]
tempfile = "3"
```
Example
-------
```rust
use std::fs::File;
use std::io::{Write, Read, Seek, SeekFrom};
fn main() {
// Write
let mut tmpfile: File = 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);
}
```

40
vendor/tempfile/deny.toml vendored Normal file
View File

@ -0,0 +1,40 @@
[advisories]
notice = "deny"
unmaintained = "deny"
vulnerability = "deny"
yanked = "deny"
ignore = []
[licenses]
allow = [
"Apache-2.0",
"MIT",
]
default = "deny"
confidence-threshold = 1.0
unlicensed = "deny"
[bans]
allow = []
deny = []
multiple-versions = "deny"
skip = [
# Transitive dependency of both redox_syscall and rustix (rustix has newer).
#
# Only one version of bitflags ultimately gets compiled in due to OS-based feature flags in tempfile.
{ name = "bitflags" },
]
skip-tree = []
wildcards = "deny"
[sources]
allow-git = []
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
unknown-git = "deny"
unknown-registry = "deny"
[sources.allow-org]
github = []
gitlab = []
bitbucket = []

477
vendor/tempfile/src/dir.rs vendored Normal file
View File

@ -0,0 +1,477 @@
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::ffi::OsStr;
use std::fs::remove_dir_all;
use std::mem;
use std::path::{self, Path, PathBuf};
use std::{fmt, fs, io};
use crate::error::IoResultExt;
use crate::Builder;
/// Create a new temporary directory.
///
/// The `tempdir` function creates a directory in the file system
/// and returns a [`TempDir`].
/// The directory will be automatically deleted when the `TempDir`s
/// destructor is run.
///
/// # Resource Leaking
///
/// See [the resource leaking][resource-leaking] docs on `TempDir`.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use 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 tmp_dir = tempdir()?;
///
/// 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.
/// drop(tmp_file);
/// tmp_dir.close()?;
/// # Ok(())
/// # }
/// ```
///
/// [`TempDir`]: struct.TempDir.html
/// [resource-leaking]: struct.TempDir.html#resource-leaking
pub fn tempdir() -> io::Result<TempDir> {
TempDir::new()
}
/// Create a new temporary directory in a specific directory.
///
/// The `tempdir_in` function creates a directory in the specified directory
/// and returns a [`TempDir`].
/// The directory will be automatically deleted when the `TempDir`s
/// destructor is run.
///
/// # Resource Leaking
///
/// See [the resource leaking][resource-leaking] docs on `TempDir`.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use 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 tmp_dir = tempdir_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.")?;
///
/// // `tmp_dir` goes out of scope, the directory as well as
/// // `tmp_file` will be deleted here.
/// drop(tmp_file);
/// tmp_dir.close()?;
/// # Ok(())
/// # }
/// ```
///
/// [`TempDir`]: struct.TempDir.html
/// [resource-leaking]: struct.TempDir.html#resource-leaking
pub fn tempdir_in<P: AsRef<Path>>(dir: P) -> io::Result<TempDir> {
TempDir::new_in(dir)
}
/// A directory in the filesystem that is automatically deleted when
/// it goes out of scope.
///
/// The [`TempDir`] type creates a directory on the file system that
/// is deleted once it goes out of scope. At construction, the
/// `TempDir` creates a new directory with a randomly generated name.
///
/// The default constructor, [`TempDir::new()`], creates directories in
/// the location returned by [`std::env::temp_dir()`], but `TempDir`
/// can be configured to manage a temporary directory in any location
/// by constructing with a [`Builder`].
///
/// After creating a `TempDir`, work with the file system by doing
/// standard [`std::fs`] file system operations on its [`Path`],
/// which can be retrieved with [`TempDir::path()`]. Once the `TempDir`
/// value is dropped, the directory at the path will be deleted, along
/// with any files and directories it contains. It is your responsibility
/// to ensure that no further file system operations are attempted
/// inside the temporary directory once it has been deleted.
///
/// # Resource Leaking
///
/// Various platform-specific conditions may cause `TempDir` to fail
/// to delete the underlying directory. It's important to ensure that
/// handles (like [`File`] and [`ReadDir`]) to files inside the
/// directory are dropped before the `TempDir` goes out of scope. The
/// `TempDir` destructor will silently ignore any errors in deleting
/// the directory; to instead handle errors call [`TempDir::close()`].
///
/// Note that if the program exits before the `TempDir` destructor is
/// run, such as via [`std::process::exit()`], by segfaulting, or by
/// receiving a signal like `SIGINT`, then the temporary directory
/// will not be deleted.
///
/// # Examples
///
/// Create a temporary directory with a generated name:
///
/// ```
/// use std::fs::File;
/// use std::io::Write;
/// use tempfile::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// // Create a directory inside of `std::env::temp_dir()`
/// let tmp_dir = TempDir::new()?;
/// # Ok(())
/// # }
/// ```
///
/// Create a temporary directory with a prefix in its name:
///
/// ```
/// use std::fs::File;
/// use std::io::Write;
/// use 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(())
/// # }
/// ```
///
/// [`File`]: http://doc.rust-lang.org/std/fs/struct.File.html
/// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
/// [`ReadDir`]: http://doc.rust-lang.org/std/fs/struct.ReadDir.html
/// [`Builder`]: struct.Builder.html
/// [`TempDir::close()`]: struct.TempDir.html#method.close
/// [`TempDir::new()`]: struct.TempDir.html#method.new
/// [`TempDir::path()`]: struct.TempDir.html#method.path
/// [`TempDir`]: struct.TempDir.html
/// [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html
/// [`std::fs`]: http://doc.rust-lang.org/std/fs/index.html
/// [`std::process::exit()`]: http://doc.rust-lang.org/std/process/fn.exit.html
pub struct TempDir {
path: Box<Path>,
}
impl TempDir {
/// 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 `TempDir` is destroyed.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use std::fs::File;
/// use std::io::Write;
/// use tempfile::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// // Create a directory inside of `std::env::temp_dir()`
/// let tmp_dir = TempDir::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(())
/// # }
/// ```
///
/// [`Builder`]: struct.Builder.html
pub fn new() -> io::Result<TempDir> {
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 `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 tempfile::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// // Create a directory inside of the current directory
/// let tmp_dir = TempDir::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<P: AsRef<Path>>(dir: P) -> io::Result<TempDir> {
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 `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 tempfile::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// // Create a directory inside of the current directory
/// let tmp_dir = TempDir::with_prefix("foo-")?;
/// let tmp_name = tmp_dir.path().file_name().unwrap().to_str().unwrap();
/// assert!(tmp_name.starts_with("foo-"));
/// # Ok(())
/// # }
/// ```
pub fn with_prefix<S: AsRef<OsStr>>(prefix: S) -> io::Result<TempDir> {
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 `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 tempfile::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// // Create a directory inside of the current directory
/// let tmp_dir = TempDir::with_prefix_in("foo-", ".")?;
/// let tmp_name = tmp_dir.path().file_name().unwrap().to_str().unwrap();
/// assert!(tmp_name.starts_with("foo-"));
/// # Ok(())
/// # }
/// ```
pub fn with_prefix_in<S: AsRef<OsStr>, P: AsRef<Path>>(
prefix: S,
dir: P,
) -> io::Result<TempDir> {
Builder::new().prefix(&prefix).tempdir_in(dir)
}
/// Accesses the [`Path`] to the temporary directory.
///
/// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
///
/// # Examples
///
/// ```
/// use tempfile::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let tmp_path;
///
/// {
/// let tmp_dir = TempDir::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) -> &path::Path {
self.path.as_ref()
}
/// Persist the temporary directory to disk, returning the [`PathBuf`] where it is located.
///
/// This consumes the [`TempDir`] without deleting directory on the filesystem, meaning that
/// the directory will no longer be automatically deleted.
///
/// [`TempDir`]: struct.TempDir.html
/// [`PathBuf`]: http://doc.rust-lang.org/std/path/struct.PathBuf.html
///
/// # Examples
///
/// ```
/// use std::fs;
/// use tempfile::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let tmp_dir = TempDir::new()?;
///
/// // Persist the temporary directory to disk,
/// // getting the path where it is.
/// let tmp_path = tmp_dir.into_path();
///
/// // Delete the temporary directory ourselves.
/// fs::remove_dir_all(tmp_path)?;
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn into_path(self) -> PathBuf {
// Prevent the Drop impl from being called.
let mut this = mem::ManuallyDrop::new(self);
// replace this.path with an empty Box, since an empty Box does not
// allocate any heap memory.
mem::replace(&mut this.path, PathBuf::new().into_boxed_path()).into()
}
/// Closes and removes the temporary directory, returning a `Result`.
///
/// Although `TempDir` removes the directory on drop, in the destructor
/// any errors are ignored. To detect errors cleaning up the temporary
/// directory, call `close` instead.
///
/// # Errors
///
/// This function may return a variety of [`std::io::Error`]s that result from deleting
/// the files and directories contained with the temporary directory,
/// as well as from deleting the temporary directory itself. These errors
/// may be platform specific.
///
/// [`std::io::Error`]: http://doc.rust-lang.org/std/io/struct.Error.html
///
/// # Examples
///
/// ```
/// use std::fs::File;
/// use std::io::Write;
/// use tempfile::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// // Create a directory inside of `std::env::temp_dir()`.
/// let tmp_dir = TempDir::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 `TempDir` explicitly we can check that it has
/// // been deleted successfully. If we don't close it explicitly,
/// // the directory will still be deleted when `tmp_dir` goes out
/// // of scope, but we won't know whether deleting the directory
/// // succeeded.
/// drop(tmp_file);
/// tmp_dir.close()?;
/// # Ok(())
/// # }
/// ```
pub fn close(mut self) -> io::Result<()> {
let result = remove_dir_all(self.path()).with_err_path(|| self.path());
// Set self.path to empty Box to release the memory, since an empty
// Box does not allocate any heap memory.
self.path = PathBuf::new().into_boxed_path();
// Prevent the Drop impl from being called.
mem::forget(self);
result
}
}
impl AsRef<Path> for TempDir {
fn as_ref(&self) -> &Path {
self.path()
}
}
impl fmt::Debug for TempDir {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TempDir")
.field("path", &self.path())
.finish()
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = remove_dir_all(self.path());
}
}
pub(crate) fn create(path: PathBuf) -> io::Result<TempDir> {
fs::create_dir(&path)
.with_err_path(|| &path)
.map(|_| TempDir {
path: path.into_boxed_path(),
})
}

45
vendor/tempfile/src/error.rs vendored Normal file
View File

@ -0,0 +1,45 @@
use std::path::PathBuf;
use std::{error, fmt, io};
#[derive(Debug)]
struct PathError {
path: PathBuf,
err: io::Error,
}
impl fmt::Display for PathError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} at path {:?}", self.err, self.path)
}
}
impl error::Error for PathError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
self.err.source()
}
}
pub(crate) trait IoResultExt<T> {
fn with_err_path<F, P>(self, path: F) -> Self
where
F: FnOnce() -> P,
P: Into<PathBuf>;
}
impl<T> IoResultExt<T> for Result<T, io::Error> {
fn with_err_path<F, P>(self, path: F) -> Self
where
F: FnOnce() -> P,
P: Into<PathBuf>,
{
self.map_err(|e| {
io::Error::new(
e.kind(),
PathError {
path: path().into(),
err: e,
},
)
})
}
}

12
vendor/tempfile/src/file/imp/mod.rs vendored Normal file
View File

@ -0,0 +1,12 @@
cfg_if::cfg_if! {
if #[cfg(any(unix, target_os = "redox", target_os = "wasi"))] {
mod unix;
pub use self::unix::*;
} else if #[cfg(windows)] {
mod windows;
pub use self::windows::*;
} else {
mod other;
pub use self::other::*;
}
}

30
vendor/tempfile/src/file/imp/other.rs vendored Normal file
View File

@ -0,0 +1,30 @@
use std::fs::{File, OpenOptions};
use std::io;
use std::path::Path;
fn not_supported<T>() -> io::Result<T> {
Err(io::Error::new(
io::ErrorKind::Other,
"operation not supported on this platform",
))
}
pub fn create_named(_path: &Path, _open_options: &mut OpenOptions) -> io::Result<File> {
not_supported()
}
pub fn create(_dir: &Path) -> io::Result<File> {
not_supported()
}
pub fn reopen(_file: &File, _path: &Path) -> io::Result<File> {
not_supported()
}
pub fn persist(_old_path: &Path, _new_path: &Path, _overwrite: bool) -> io::Result<()> {
not_supported()
}
pub fn keep(_path: &Path) -> io::Result<()> {
not_supported()
}

149
vendor/tempfile/src/file/imp/unix.rs vendored Normal file
View File

@ -0,0 +1,149 @@
use std::env;
use std::ffi::OsStr;
use std::fs::{self, File, OpenOptions};
use std::io;
cfg_if::cfg_if! {
if #[cfg(not(target_os = "wasi"))] {
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
} else {
#[cfg(feature = "nightly")]
use std::os::wasi::fs::MetadataExt;
}
}
use crate::util;
use std::path::Path;
#[cfg(not(target_os = "redox"))]
use {
rustix::fs::{rename, unlink},
std::fs::hard_link,
};
pub fn create_named(path: &Path, open_options: &mut OpenOptions) -> io::Result<File> {
open_options.read(true).write(true).create_new(true);
#[cfg(not(target_os = "wasi"))]
{
open_options.mode(0o600);
}
open_options.open(path)
}
fn create_unlinked(path: &Path) -> io::Result<File> {
let tmp;
// shadow this to decrease the lifetime. It can't live longer than `tmp`.
let mut path = path;
if !path.is_absolute() {
let cur_dir = env::current_dir()?;
tmp = cur_dir.join(path);
path = &tmp;
}
let f = create_named(path, &mut OpenOptions::new())?;
// don't care whether the path has already been unlinked,
// but perhaps there are some IO error conditions we should send up?
let _ = fs::remove_file(path);
Ok(f)
}
#[cfg(target_os = "linux")]
pub fn create(dir: &Path) -> io::Result<File> {
use rustix::{fs::OFlags, io::Errno};
OpenOptions::new()
.read(true)
.write(true)
.custom_flags(OFlags::TMPFILE.bits() as i32) // do not mix with `create_new(true)`
.open(dir)
.or_else(|e| {
match Errno::from_io_error(&e) {
// These are the three "not supported" error codes for O_TMPFILE.
Some(Errno::OPNOTSUPP) | Some(Errno::ISDIR) | Some(Errno::NOENT) => {
create_unix(dir)
}
_ => Err(e),
}
})
}
#[cfg(not(target_os = "linux"))]
pub fn create(dir: &Path) -> io::Result<File> {
create_unix(dir)
}
fn create_unix(dir: &Path) -> io::Result<File> {
util::create_helper(
dir,
OsStr::new(".tmp"),
OsStr::new(""),
crate::NUM_RAND_CHARS,
|path| create_unlinked(&path),
)
}
#[cfg(any(not(target_os = "wasi"), feature = "nightly"))]
pub fn reopen(file: &File, path: &Path) -> io::Result<File> {
let new_file = OpenOptions::new().read(true).write(true).open(path)?;
let old_meta = file.metadata()?;
let new_meta = new_file.metadata()?;
if old_meta.dev() != new_meta.dev() || old_meta.ino() != new_meta.ino() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"original tempfile has been replaced",
));
}
Ok(new_file)
}
#[cfg(all(target_os = "wasi", not(feature = "nightly")))]
pub fn reopen(_file: &File, _path: &Path) -> io::Result<File> {
return Err(io::Error::new(
io::ErrorKind::Other,
"this operation is supported on WASI only on nightly Rust (with `nightly` feature enabled)",
));
}
#[cfg(not(target_os = "redox"))]
pub fn persist(old_path: &Path, new_path: &Path, overwrite: bool) -> io::Result<()> {
if overwrite {
rename(old_path, new_path)?;
} else {
// On Linux, use `renameat_with` to avoid overwriting an existing name,
// if the kernel and the filesystem support it.
#[cfg(any(target_os = "android", target_os = "linux"))]
{
use rustix::fs::{renameat_with, RenameFlags, CWD};
use rustix::io::Errno;
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};
static NOSYS: AtomicBool = AtomicBool::new(false);
if !NOSYS.load(Relaxed) {
match renameat_with(CWD, old_path, CWD, new_path, RenameFlags::NOREPLACE) {
Ok(()) => return Ok(()),
Err(Errno::NOSYS) => NOSYS.store(true, Relaxed),
Err(Errno::INVAL) => {}
Err(e) => return Err(e.into()),
}
}
}
// Otherwise use `hard_link` to create the new filesystem name, which
// will fail if the name already exists, and then `unlink` to remove
// the old name.
hard_link(old_path, new_path)?;
// Ignore unlink errors. Can we do better?
let _ = unlink(old_path);
}
Ok(())
}
#[cfg(target_os = "redox")]
pub fn persist(_old_path: &Path, _new_path: &Path, _overwrite: bool) -> io::Result<()> {
// XXX implement when possible
Err(io::Error::from_raw_os_error(syscall::ENOSYS))
}
pub fn keep(_: &Path) -> io::Result<()> {
Ok(())
}

104
vendor/tempfile/src/file/imp/windows.rs vendored Normal file
View File

@ -0,0 +1,104 @@
use std::ffi::OsStr;
use std::fs::{File, OpenOptions};
use std::os::windows::ffi::OsStrExt;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, RawHandle};
use std::path::Path;
use std::{io, iter};
use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Storage::FileSystem::{
MoveFileExW, ReOpenFile, SetFileAttributesW, FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_TEMPORARY,
FILE_FLAG_DELETE_ON_CLOSE, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_DELETE,
FILE_SHARE_READ, FILE_SHARE_WRITE, MOVEFILE_REPLACE_EXISTING,
};
use crate::util;
fn to_utf16(s: &Path) -> Vec<u16> {
s.as_os_str().encode_wide().chain(iter::once(0)).collect()
}
pub fn create_named(path: &Path, open_options: &mut OpenOptions) -> io::Result<File> {
open_options
.create_new(true)
.read(true)
.write(true)
.custom_flags(FILE_ATTRIBUTE_TEMPORARY)
.open(path)
}
pub fn create(dir: &Path) -> io::Result<File> {
util::create_helper(
dir,
OsStr::new(".tmp"),
OsStr::new(""),
crate::NUM_RAND_CHARS,
|path| {
OpenOptions::new()
.create_new(true)
.read(true)
.write(true)
.share_mode(0)
.custom_flags(FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE)
.open(path)
},
)
}
pub fn reopen(file: &File, _path: &Path) -> io::Result<File> {
let handle = file.as_raw_handle();
unsafe {
let handle = ReOpenFile(
handle as HANDLE,
FILE_GENERIC_READ | FILE_GENERIC_WRITE,
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
);
if handle == INVALID_HANDLE_VALUE {
Err(io::Error::last_os_error())
} else {
Ok(FromRawHandle::from_raw_handle(handle as RawHandle))
}
}
}
pub fn keep(path: &Path) -> io::Result<()> {
unsafe {
let path_w = to_utf16(path);
if SetFileAttributesW(path_w.as_ptr(), FILE_ATTRIBUTE_NORMAL) == 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
}
pub fn persist(old_path: &Path, new_path: &Path, overwrite: bool) -> io::Result<()> {
unsafe {
let old_path_w = to_utf16(old_path);
let new_path_w = to_utf16(new_path);
// Don't succeed if this fails. We don't want to claim to have successfully persisted a file
// still marked as temporary because this file won't have the same consistency guarantees.
if SetFileAttributesW(old_path_w.as_ptr(), FILE_ATTRIBUTE_NORMAL) == 0 {
return Err(io::Error::last_os_error());
}
let mut flags = 0;
if overwrite {
flags |= MOVEFILE_REPLACE_EXISTING;
}
if MoveFileExW(old_path_w.as_ptr(), new_path_w.as_ptr(), flags) == 0 {
let e = io::Error::last_os_error();
// If this fails, the temporary file is now un-hidden and no longer marked temporary
// (slightly less efficient) but it will still work.
let _ = SetFileAttributesW(old_path_w.as_ptr(), FILE_ATTRIBUTE_TEMPORARY);
Err(e)
} else {
Ok(())
}
}
}

1124
vendor/tempfile/src/file/mod.rs vendored Normal file

File diff suppressed because it is too large Load Diff

701
vendor/tempfile/src/lib.rs vendored Normal file
View File

@ -0,0 +1,701 @@
//! Temporary files and directories.
//!
//! - 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.
//! [`TempDir`] and [`NamedTempFile`] 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 `TempDir` and `NamedTempFile` will
//! fail if their destructors don't run. This is because `tempfile` relies on the OS to cleanup the
//! underlying file, while `TempDir` and `NamedTempFile` 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 (like with [`lazy_static`]), 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, `NamedTempFile` does
//! rely on file paths for _some_ operations. See the security documentation on
//! the `NamedTempFile` type for more information.
//!
//! ## Early drop pitfall
//!
//! Because `TempDir` and `NamedTempFile` rely on their destructors for cleanup, this can lead
//! to an unexpected early removal of the directory/file, usually when working with APIs which are
//! generic over `AsRef<Path>`. Consider the following example:
//!
//! ```no_run
//! # use tempfile::tempdir;
//! # use std::io;
//! # use std::process::Command;
//! # fn main() {
//! # if let Err(_) = run() {
//! # ::std::process::exit(1);
//! # }
//! # }
//! # fn run() -> Result<(), io::Error> {
//! // Create a directory inside of `std::env::temp_dir()`.
//! let temp_dir = tempdir()?;
//!
//! // Spawn the `touch` command inside the temporary directory and collect the exit status
//! // Note that `temp_dir` is **not** moved into `current_dir`, but passed as a reference
//! let exit_status = Command::new("touch").arg("tmp").current_dir(&temp_dir).status()?;
//! assert!(exit_status.success());
//!
//! # Ok(())
//! # }
//! ```
//!
//! This works because a reference to `temp_dir` is passed to `current_dir`, resulting in the
//! destructor of `temp_dir` being run after the `Command` has finished execution. Moving the
//! `TempDir` into the `current_dir` call would result in the `TempDir` being converted into
//! an internal representation, with the original value being dropped and the directory thus
//! being deleted, before the command can be executed.
//!
//! The `touch` command would fail with an `No such file or directory` error.
//!
//! ## Examples
//!
//! Create a temporary file and write some data into it:
//!
//! ```
//! use 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 tempfile::NamedTempFile;
//! 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 = NamedTempFile::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 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 `TempDir` explicitly, we can check that it has
//! // been deleted successfully. If we don't close it explicitly,
//! // the directory will still be deleted when `dir` goes out
//! // of scope, but we won't know whether deleting the directory
//! // succeeded.
//! drop(file);
//! dir.close()?;
//! # Ok(())
//! # }
//! ```
//!
//! [`tempfile()`]: fn.tempfile.html
//! [`tempdir()`]: fn.tempdir.html
//! [`TempDir`]: struct.TempDir.html
//! [`NamedTempFile`]: struct.NamedTempFile.html
//! [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html
//! [`lazy_static`]: https://github.com/rust-lang-nursery/lazy-static.rs/issues/62
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://docs.rs/tempfile/3.1.0"
)]
#![cfg_attr(test, deny(warnings))]
#![deny(rust_2018_idioms)]
#![allow(clippy::redundant_field_names)]
#![cfg_attr(all(feature = "nightly", target_os = "wasi"), feature(wasi_ext))]
#[cfg(doctest)]
doc_comment::doctest!("../README.md");
const NUM_RETRIES: u32 = 1 << 31;
const NUM_RAND_CHARS: usize = 6;
use std::ffi::OsStr;
use std::fs::OpenOptions;
use std::path::Path;
use std::{env, io};
mod dir;
mod error;
mod file;
mod spooled;
mod util;
pub use crate::dir::{tempdir, tempdir_in, TempDir};
pub use crate::file::{
tempfile, tempfile_in, NamedTempFile, PathPersistError, PersistError, TempPath,
};
pub use crate::spooled::{spooled_tempfile, SpooledTempFile};
/// Create a new temporary file or directory with custom parameters.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Builder<'a, 'b> {
random_len: usize,
prefix: &'a OsStr,
suffix: &'b OsStr,
append: bool,
}
impl<'a, 'b> Default for Builder<'a, 'b> {
fn default() -> Self {
Builder {
random_len: crate::NUM_RAND_CHARS,
prefix: OsStr::new(".tmp"),
suffix: OsStr::new(""),
append: false,
}
}
}
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 tempfile::Builder;
///
/// let named_tempfile = Builder::new()
/// .prefix("my-temporary-note")
/// .suffix(".txt")
/// .rand_bytes(5)
/// .tempfile()?;
///
/// let name = named_tempfile
/// .path()
/// .file_name().and_then(OsStr::to_str);
///
/// 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 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 `TempDir` explicitly, we can check that it has
/// // been deleted successfully. If we don't close it explicitly,
/// // the directory will still be deleted when `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 tempfile::Builder;
/// let named_tempfile = Builder::new()
/// .prefix("my-temporary-note")
/// .tempfile()?;
/// # Ok(())
/// # }
/// ```
pub fn prefix<S: AsRef<OsStr> + ?Sized>(&mut self, prefix: &'a S) -> &mut Self {
self.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 tempfile::Builder;
/// let named_tempfile = Builder::new()
/// .suffix(".txt")
/// .tempfile()?;
/// # Ok(())
/// # }
/// ```
pub fn suffix<S: AsRef<OsStr> + ?Sized>(&mut self, suffix: &'b S) -> &mut Self {
self.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 tempfile::Builder;
/// let named_tempfile = Builder::new()
/// .rand_bytes(5)
/// .tempfile()?;
/// # Ok(())
/// # }
/// ```
pub fn rand_bytes(&mut self, rand: usize) -> &mut Self {
self.random_len = 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 tempfile::Builder;
/// let named_tempfile = Builder::new()
/// .append(true)
/// .tempfile()?;
/// # Ok(())
/// # }
/// ```
pub fn append(&mut self, append: bool) -> &mut Self {
self.append = append;
self
}
/// Create the named temporary file.
///
/// # Security
///
/// See [the security][security] docs on `NamedTempFile`.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # 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 tempfile::Builder;
/// let tempfile = Builder::new().tempfile()?;
/// # Ok(())
/// # }
/// ```
///
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn tempfile(&self) -> io::Result<NamedTempFile> {
self.tempfile_in(env::temp_dir())
}
/// Create the named temporary file in the specified directory.
///
/// # Security
///
/// See [the security][security] docs on `NamedTempFile`.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # 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 tempfile::Builder;
/// let tempfile = Builder::new().tempfile_in("./")?;
/// # Ok(())
/// # }
/// ```
///
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn tempfile_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<NamedTempFile> {
util::create_helper(
dir.as_ref(),
self.prefix,
self.suffix,
self.random_len,
|path| file::create_named(path, OpenOptions::new().append(self.append)),
)
}
/// Attempts to make a temporary directory inside of `env::temp_dir()` whose
/// name will have the prefix, `prefix`. The directory and
/// everything inside it will be automatically deleted once the
/// returned `TempDir` is destroyed.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `TempDir`.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use std::fs::File;
/// use std::io::Write;
/// use tempfile::Builder;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let tmp_dir = Builder::new().tempdir()?;
/// # Ok(())
/// # }
/// ```
///
/// [resource-leaking]: struct.TempDir.html#resource-leaking
pub fn tempdir(&self) -> io::Result<TempDir> {
self.tempdir_in(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 `TempDir` is destroyed.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `TempDir`.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use std::fs::{self, File};
/// use std::io::Write;
/// use tempfile::Builder;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let tmp_dir = Builder::new().tempdir_in("./")?;
/// # Ok(())
/// # }
/// ```
///
/// [resource-leaking]: struct.TempDir.html#resource-leaking
pub fn tempdir_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<TempDir> {
let storage;
let mut dir = dir.as_ref();
if !dir.is_absolute() {
let cur_dir = env::current_dir()?;
storage = cur_dir.join(dir);
dir = &storage;
}
util::create_helper(dir, self.prefix, self.suffix, self.random_len, dir::create)
}
/// 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
/// [`NamedTempFile`], 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 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 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 `NamedTempFile`.
///
/// # 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 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.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn make<F, R>(&self, f: F) -> io::Result<NamedTempFile<R>>
where
F: FnMut(&Path) -> io::Result<R>,
{
self.make_in(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 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<F, R, P>(&self, dir: P, mut f: F) -> io::Result<NamedTempFile<R>>
where
F: FnMut(&Path) -> io::Result<R>,
P: AsRef<Path>,
{
util::create_helper(
dir.as_ref(),
self.prefix,
self.suffix,
self.random_len,
move |path| {
Ok(NamedTempFile::from_parts(
f(&path)?,
TempPath::from_path(path),
))
},
)
}
}

203
vendor/tempfile/src/spooled.rs vendored Normal file
View File

@ -0,0 +1,203 @@
use crate::file::tempfile;
use std::fs::File;
use std::io::{self, Cursor, Read, Seek, SeekFrom, Write};
/// A wrapper for the two states of a `SpooledTempFile`.
#[derive(Debug)]
pub enum SpooledData {
InMemory(Cursor<Vec<u8>>),
OnDisk(File),
}
/// An object that behaves like a regular temporary file, but keeps data in
/// memory until it reaches a configured size, at which point the data is
/// written to a temporary file on disk, and further operations use the file
/// on disk.
#[derive(Debug)]
pub struct SpooledTempFile {
max_size: usize,
inner: SpooledData,
}
/// Create a new spooled temporary file.
///
/// # 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.
///
/// # Examples
///
/// ```
/// use tempfile::spooled_tempfile;
/// use std::io::{self, Write};
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// let mut file = spooled_tempfile(15);
///
/// writeln!(file, "short line")?;
/// assert!(!file.is_rolled());
///
/// // as a result of this write call, the size of the data will exceed
/// // `max_size` (15), so it will be written to a temporary file on disk,
/// // and the in-memory buffer will be dropped
/// writeln!(file, "marvin gardens")?;
/// assert!(file.is_rolled());
///
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn spooled_tempfile(max_size: usize) -> SpooledTempFile {
SpooledTempFile::new(max_size)
}
impl SpooledTempFile {
#[must_use]
pub fn new(max_size: usize) -> SpooledTempFile {
SpooledTempFile {
max_size,
inner: SpooledData::InMemory(Cursor::new(Vec::new())),
}
}
/// Returns true if the file has been rolled over to disk.
#[must_use]
pub fn is_rolled(&self) -> bool {
match self.inner {
SpooledData::InMemory(_) => false,
SpooledData::OnDisk(_) => true,
}
}
/// Rolls over to a file on disk, regardless of current size. Does nothing
/// if already rolled over.
pub fn roll(&mut self) -> io::Result<()> {
if !self.is_rolled() {
let mut file = tempfile()?;
if let SpooledData::InMemory(cursor) = &mut self.inner {
file.write_all(cursor.get_ref())?;
file.seek(SeekFrom::Start(cursor.position()))?;
}
self.inner = SpooledData::OnDisk(file);
}
Ok(())
}
pub fn set_len(&mut self, size: u64) -> Result<(), io::Error> {
if size as usize > self.max_size {
self.roll()?; // does nothing if already rolled over
}
match &mut self.inner {
SpooledData::InMemory(cursor) => {
cursor.get_mut().resize(size as usize, 0);
Ok(())
}
SpooledData::OnDisk(file) => file.set_len(size),
}
}
/// Consumes and returns the inner `SpooledData` type.
#[must_use]
pub fn into_inner(self) -> SpooledData {
self.inner
}
}
impl Read for SpooledTempFile {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match &mut self.inner {
SpooledData::InMemory(cursor) => cursor.read(buf),
SpooledData::OnDisk(file) => file.read(buf),
}
}
fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
match &mut self.inner {
SpooledData::InMemory(cursor) => cursor.read_vectored(bufs),
SpooledData::OnDisk(file) => file.read_vectored(bufs),
}
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
match &mut self.inner {
SpooledData::InMemory(cursor) => cursor.read_to_end(buf),
SpooledData::OnDisk(file) => file.read_to_end(buf),
}
}
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
match &mut self.inner {
SpooledData::InMemory(cursor) => cursor.read_to_string(buf),
SpooledData::OnDisk(file) => file.read_to_string(buf),
}
}
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
match &mut self.inner {
SpooledData::InMemory(cursor) => cursor.read_exact(buf),
SpooledData::OnDisk(file) => file.read_exact(buf),
}
}
}
impl Write for SpooledTempFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
// roll over to file if necessary
if matches! {
&self.inner, SpooledData::InMemory(cursor)
if cursor.position() as usize + buf.len() > self.max_size
} {
self.roll()?;
}
// write the bytes
match &mut self.inner {
SpooledData::InMemory(cursor) => cursor.write(buf),
SpooledData::OnDisk(file) => file.write(buf),
}
}
fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
if matches! {
&self.inner, SpooledData::InMemory(cursor)
// Borrowed from the rust standard library.
if cursor.position() as usize + bufs.iter()
.fold(0usize, |a, b| a.saturating_add(b.len())) > self.max_size
} {
self.roll()?;
}
match &mut self.inner {
SpooledData::InMemory(cursor) => cursor.write_vectored(bufs),
SpooledData::OnDisk(file) => file.write_vectored(bufs),
}
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
match &mut self.inner {
SpooledData::InMemory(cursor) => cursor.flush(),
SpooledData::OnDisk(file) => file.flush(),
}
}
}
impl Seek for SpooledTempFile {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
match &mut self.inner {
SpooledData::InMemory(cursor) => cursor.seek(pos),
SpooledData::OnDisk(file) => file.seek(pos),
}
}
}

47
vendor/tempfile/src/util.rs vendored Normal file
View File

@ -0,0 +1,47 @@
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::{io, iter::repeat_with};
use crate::error::IoResultExt;
fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
let mut buf = OsString::with_capacity(prefix.len() + suffix.len() + rand_len);
buf.push(prefix);
let mut char_buf = [0u8; 4];
for c in repeat_with(fastrand::alphanumeric).take(rand_len) {
buf.push(c.encode_utf8(&mut char_buf));
}
buf.push(suffix);
buf
}
pub fn create_helper<R>(
base: &Path,
prefix: &OsStr,
suffix: &OsStr,
random_len: usize,
mut f: impl FnMut(PathBuf) -> io::Result<R>,
) -> io::Result<R> {
let num_retries = if random_len != 0 {
crate::NUM_RETRIES
} else {
1
};
for _ in 0..num_retries {
let path = base.join(tmpname(prefix, suffix, random_len));
return match f(path) {
Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists && num_retries > 1 => continue,
// AddrInUse can happen if we're creating a UNIX domain socket and
// the path already exists.
Err(ref e) if e.kind() == io::ErrorKind::AddrInUse && num_retries > 1 => continue,
res => res,
};
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"too many temporary files exist",
))
.with_err_path(|| base)
}

473
vendor/tempfile/tests/namedtempfile.rs vendored Normal file
View File

@ -0,0 +1,473 @@
#![deny(rust_2018_idioms)]
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use tempfile::{tempdir, Builder, NamedTempFile, TempPath};
fn exists<P: AsRef<Path>>(path: P) -> bool {
std::fs::metadata(path.as_ref()).is_ok()
}
#[test]
fn test_prefix() {
let tmpfile = NamedTempFile::with_prefix("prefix").unwrap();
let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
assert!(name.starts_with("prefix"));
}
#[test]
fn test_basic() {
let mut tmpfile = NamedTempFile::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 = NamedTempFile::new().unwrap();
let path = tmpfile.path().to_path_buf();
assert!(exists(&path));
drop(tmpfile);
assert!(!exists(&path));
}
#[test]
fn test_persist() {
let mut tmpfile = NamedTempFile::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 = NamedTempFile::new().unwrap();
let old_path = tmpfile.path().to_path_buf();
let persist_target = NamedTempFile::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().to_str().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 = NamedTempFile::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 = NamedTempFile::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 = NamedTempFile::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 = NamedTempFile::new().unwrap();
write!(tmpfile, "abcde").unwrap();
let path = tmpfile.into_temp_path();
assert!(path.is_file());
}
#[test]
fn test_temppath_persist() {
let mut tmpfile = NamedTempFile::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 = NamedTempFile::new().unwrap();
write!(tmpfile, "abcde").unwrap();
let mut tmppath = tmpfile.into_temp_path();
let old_path = tmppath.to_path_buf();
let persist_target = NamedTempFile::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 = TempPath::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;
TempPath::from_path("");
TempPath::from_path(String::new());
TempPath::from_path(OsStr::new(""));
TempPath::from_path(OsString::new());
TempPath::from_path(Path::new(""));
TempPath::from_path(PathBuf::new());
TempPath::from_path(PathBuf::new().into_boxed_path());
}
#[test]
fn test_write_after_close() {
let path = NamedTempFile::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 = NamedTempFile::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 = NamedTempFile::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 = NamedTempFile::new().unwrap();
write!(file, "abcd").expect("write failed");
let (file, temp_path) = file.into_parts();
let file = NamedTempFile::from_parts(file, temp_path);
assert!(file.path().exists());
}
#[test]
fn test_keep() {
let mut tmpfile = NamedTempFile::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());
}
#[cfg(unix)]
#[test]
fn test_make_uds_conflict() {
use std::os::unix::net::UnixListener;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
// Check that retries happen correctly by racing N different threads.
const NTHREADS: usize = 20;
// The number of times our callback was called.
let tries = Arc::new(AtomicUsize::new(0));
let mut threads = Vec::with_capacity(NTHREADS);
for _ in 0..NTHREADS {
let tries = tries.clone();
threads.push(std::thread::spawn(move || {
// Ensure that every thread uses the same seed so we are guaranteed
// to retry. Note that fastrand seeds are thread-local.
fastrand::seed(42);
Builder::new()
.prefix("tmp")
.suffix(".sock")
.rand_bytes(12)
.make(|path| {
tries.fetch_add(1, Ordering::Relaxed);
UnixListener::bind(path)
})
}));
}
// Join all threads, but don't drop the temp file yet. Otherwise, we won't
// get a deterministic number of `tries`.
let sockets: Vec<_> = threads
.into_iter()
.map(|thread| thread.join().unwrap().unwrap())
.collect();
// Number of tries is exactly equal to (n*(n+1))/2.
assert_eq!(
tries.load(Ordering::Relaxed),
(NTHREADS * (NTHREADS + 1)) / 2
);
for socket in sockets {
assert!(socket.path().exists());
}
}
// Issue #224.
#[test]
fn test_overly_generic_bounds() {
pub struct Foo<T>(T);
impl<T> Foo<T>
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
};
}
}

307
vendor/tempfile/tests/spooled.rs vendored Normal file
View File

@ -0,0 +1,307 @@
#![deny(rust_2018_idioms)]
use std::io::{Read, Seek, SeekFrom, Write};
use tempfile::{spooled_tempfile, SpooledTempFile};
#[test]
fn test_automatic_rollover() {
let mut t = spooled_tempfile(10);
let mut buf = Vec::new();
assert!(!t.is_rolled());
assert_eq!(t.stream_position().unwrap(), 0);
assert_eq!(t.read_to_end(&mut buf).unwrap(), 0);
assert_eq!(buf.as_slice(), b"");
buf.clear();
assert_eq!(t.write(b"abcde").unwrap(), 5);
assert!(!t.is_rolled());
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
assert_eq!(t.read_to_end(&mut buf).unwrap(), 5);
assert_eq!(buf.as_slice(), b"abcde");
assert_eq!(t.write(b"fghijklmno").unwrap(), 10);
assert_eq!(t.stream_position().unwrap(), 15);
assert!(t.is_rolled());
}
#[test]
fn test_explicit_rollover() {
let mut t = SpooledTempFile::new(100);
assert_eq!(t.write(b"abcdefghijklmnopqrstuvwxyz").unwrap(), 26);
assert_eq!(t.stream_position().unwrap(), 26);
assert!(!t.is_rolled());
// roll over explicitly
assert!(t.roll().is_ok());
assert!(t.is_rolled());
assert_eq!(t.stream_position().unwrap(), 26);
let mut buf = Vec::new();
assert_eq!(t.read_to_end(&mut buf).unwrap(), 0);
assert_eq!(buf.as_slice(), b"");
buf.clear();
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
assert_eq!(t.read_to_end(&mut buf).unwrap(), 26);
assert_eq!(buf.as_slice(), b"abcdefghijklmnopqrstuvwxyz");
assert_eq!(t.stream_position().unwrap(), 26);
}
// called by test_seek_{buffer, file}
// assumes t is empty and offset is 0 to start
fn test_seek(t: &mut SpooledTempFile) {
assert_eq!(t.write(b"abcdefghijklmnopqrstuvwxyz").unwrap(), 26);
assert_eq!(t.stream_position().unwrap(), 26); // tell()
assert_eq!(t.seek(SeekFrom::Current(-1)).unwrap(), 25);
assert_eq!(t.seek(SeekFrom::Current(1)).unwrap(), 26);
assert_eq!(t.seek(SeekFrom::Current(1)).unwrap(), 27);
assert_eq!(t.seek(SeekFrom::Current(-27)).unwrap(), 0);
assert!(t.seek(SeekFrom::Current(-1)).is_err());
assert!(t.seek(SeekFrom::Current(-1245)).is_err());
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
assert_eq!(t.seek(SeekFrom::Start(1)).unwrap(), 1);
assert_eq!(t.seek(SeekFrom::Start(26)).unwrap(), 26);
assert_eq!(t.seek(SeekFrom::Start(27)).unwrap(), 27);
// // these are build errors
// assert!(t.seek(SeekFrom::Start(-1)).is_err());
// assert!(t.seek(SeekFrom::Start(-1000)).is_err());
assert_eq!(t.seek(SeekFrom::End(0)).unwrap(), 26);
assert_eq!(t.seek(SeekFrom::End(-1)).unwrap(), 25);
assert_eq!(t.seek(SeekFrom::End(-26)).unwrap(), 0);
assert!(t.seek(SeekFrom::End(-27)).is_err());
assert!(t.seek(SeekFrom::End(-99)).is_err());
assert_eq!(t.seek(SeekFrom::End(1)).unwrap(), 27);
assert_eq!(t.seek(SeekFrom::End(1)).unwrap(), 27);
}
#[test]
fn test_seek_buffer() {
let mut t = spooled_tempfile(100);
test_seek(&mut t);
}
#[test]
fn test_seek_file() {
let mut t = SpooledTempFile::new(10);
test_seek(&mut t);
}
fn test_seek_read(t: &mut SpooledTempFile) {
assert_eq!(t.write(b"abcdefghijklmnopqrstuvwxyz").unwrap(), 26);
let mut buf = Vec::new();
// we're at the end
assert_eq!(t.read_to_end(&mut buf).unwrap(), 0);
assert_eq!(buf.as_slice(), b"");
buf.clear();
// seek to start, read whole thing
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
assert_eq!(t.read_to_end(&mut buf).unwrap(), 26);
assert_eq!(buf.as_slice(), b"abcdefghijklmnopqrstuvwxyz");
buf.clear();
// now we're at the end again
assert_eq!(t.stream_position().unwrap(), 26); // tell()
assert_eq!(t.read_to_end(&mut buf).unwrap(), 0);
assert_eq!(buf.as_slice(), b"");
buf.clear();
// seek to somewhere in the middle, read a bit
assert_eq!(t.seek(SeekFrom::Start(5)).unwrap(), 5);
let mut buf = [0; 5];
assert!(t.read_exact(&mut buf).is_ok());
assert_eq!(buf, *b"fghij");
// read again from current spot
assert_eq!(t.stream_position().unwrap(), 10); // tell()
assert!(t.read_exact(&mut buf).is_ok());
assert_eq!(buf, *b"klmno");
let mut buf = [0; 15];
// partial read
assert_eq!(t.read(&mut buf).unwrap(), 11);
assert_eq!(buf[0..11], *b"pqrstuvwxyz");
// try to read off the end: UnexpectedEof
assert!(t.read_exact(&mut buf).is_err());
}
#[test]
fn test_seek_read_buffer() {
let mut t = spooled_tempfile(100);
test_seek_read(&mut t);
}
#[test]
fn test_seek_read_file() {
let mut t = SpooledTempFile::new(10);
test_seek_read(&mut t);
}
fn test_overwrite_middle(t: &mut SpooledTempFile) {
assert_eq!(t.write(b"abcdefghijklmnopqrstuvwxyz").unwrap(), 26);
assert_eq!(t.seek(SeekFrom::Start(10)).unwrap(), 10);
assert_eq!(t.write(b"0123456789").unwrap(), 10);
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
let mut buf = Vec::new();
assert_eq!(t.read_to_end(&mut buf).unwrap(), 26);
assert_eq!(buf.as_slice(), b"abcdefghij0123456789uvwxyz");
}
#[test]
fn test_overwrite_middle_of_buffer() {
let mut t = spooled_tempfile(100);
test_overwrite_middle(&mut t);
}
#[test]
fn test_overwrite_middle_of_file() {
let mut t = SpooledTempFile::new(10);
test_overwrite_middle(&mut t);
}
#[test]
fn test_overwrite_and_extend_buffer() {
let mut t = spooled_tempfile(100);
assert_eq!(t.write(b"abcdefghijklmnopqrstuvwxyz").unwrap(), 26);
assert_eq!(t.seek(SeekFrom::End(-5)).unwrap(), 21);
assert_eq!(t.write(b"0123456789").unwrap(), 10);
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
let mut buf = Vec::new();
assert_eq!(t.read_to_end(&mut buf).unwrap(), 31);
assert_eq!(buf.as_slice(), b"abcdefghijklmnopqrstu0123456789");
assert!(!t.is_rolled());
}
#[test]
fn test_overwrite_and_extend_rollover() {
let mut t = SpooledTempFile::new(20);
assert_eq!(t.write(b"abcdefghijklmno").unwrap(), 15);
assert!(!t.is_rolled());
assert_eq!(t.seek(SeekFrom::End(-5)).unwrap(), 10);
assert_eq!(t.stream_position().unwrap(), 10); // tell()
assert!(!t.is_rolled());
assert_eq!(t.write(b"0123456789)!@#$%^&*(").unwrap(), 20);
assert!(t.is_rolled());
assert_eq!(t.stream_position().unwrap(), 30); // tell()
let mut buf = Vec::new();
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
assert_eq!(t.read_to_end(&mut buf).unwrap(), 30);
assert_eq!(buf.as_slice(), b"abcdefghij0123456789)!@#$%^&*(");
}
fn test_sparse(t: &mut SpooledTempFile) {
assert_eq!(t.write(b"abcde").unwrap(), 5);
assert_eq!(t.seek(SeekFrom::Current(5)).unwrap(), 10);
assert_eq!(t.write(b"klmno").unwrap(), 5);
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
let mut buf = Vec::new();
assert_eq!(t.read_to_end(&mut buf).unwrap(), 15);
assert_eq!(buf.as_slice(), b"abcde\0\0\0\0\0klmno");
}
#[test]
fn test_sparse_buffer() {
let mut t = spooled_tempfile(100);
test_sparse(&mut t);
}
#[test]
fn test_sparse_file() {
let mut t = SpooledTempFile::new(1);
test_sparse(&mut t);
}
#[test]
fn test_sparse_write_rollover() {
let mut t = spooled_tempfile(10);
assert_eq!(t.write(b"abcde").unwrap(), 5);
assert!(!t.is_rolled());
assert_eq!(t.seek(SeekFrom::Current(5)).unwrap(), 10);
assert!(!t.is_rolled());
assert_eq!(t.write(b"klmno").unwrap(), 5);
assert!(t.is_rolled());
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
let mut buf = Vec::new();
assert_eq!(t.read_to_end(&mut buf).unwrap(), 15);
assert_eq!(buf.as_slice(), b"abcde\0\0\0\0\0klmno");
}
fn test_set_len(t: &mut SpooledTempFile) {
let mut buf: Vec<u8> = Vec::new();
assert_eq!(t.write(b"abcdefghijklmnopqrstuvwxyz").unwrap(), 26);
// truncate to 10 bytes
assert!(t.set_len(10).is_ok());
// position should not have moved
assert_eq!(t.stream_position().unwrap(), 26); // tell()
assert_eq!(t.read_to_end(&mut buf).unwrap(), 0);
assert_eq!(buf.as_slice(), b"");
assert_eq!(t.stream_position().unwrap(), 26); // tell()
buf.clear();
// read whole thing
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
assert_eq!(t.read_to_end(&mut buf).unwrap(), 10);
assert_eq!(buf.as_slice(), b"abcdefghij");
buf.clear();
// set_len to expand beyond the end
assert!(t.set_len(40).is_ok());
assert_eq!(t.stream_position().unwrap(), 10); // tell()
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
assert_eq!(t.read_to_end(&mut buf).unwrap(), 40);
assert_eq!(
buf.as_slice(),
&b"abcdefghij\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"[..]
);
}
#[test]
fn test_set_len_buffer() {
let mut t = spooled_tempfile(100);
test_set_len(&mut t);
}
#[test]
fn test_set_len_file() {
let mut t = spooled_tempfile(100);
test_set_len(&mut t);
}
#[test]
fn test_set_len_rollover() {
let mut buf: Vec<u8> = Vec::new();
let mut t = spooled_tempfile(10);
assert_eq!(t.write(b"abcde").unwrap(), 5);
assert!(!t.is_rolled());
assert_eq!(t.stream_position().unwrap(), 5); // tell()
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
assert_eq!(t.read_to_end(&mut buf).unwrap(), 5);
assert_eq!(buf.as_slice(), b"abcde");
assert_eq!(t.stream_position().unwrap(), 5); // tell()
buf.clear();
assert!(t.set_len(20).is_ok());
assert!(t.is_rolled());
assert_eq!(t.stream_position().unwrap(), 5); // tell()
assert_eq!(t.seek(SeekFrom::Start(0)).unwrap(), 0);
assert_eq!(t.read_to_end(&mut buf).unwrap(), 20);
assert_eq!(buf.as_slice(), b"abcde\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
}

176
vendor/tempfile/tests/tempdir.rs vendored Normal file
View File

@ -0,0 +1,176 @@
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![deny(rust_2018_idioms)]
use std::env;
use std::fs;
use std::path::Path;
use std::sync::mpsc::channel;
use std::thread;
use tempfile::{Builder, TempDir};
fn test_tempdir() {
let path = {
let p = Builder::new().prefix("foobar").tempdir_in(".").unwrap();
let p = p.path();
assert!(p.to_str().unwrap().contains("foobar"));
p.to_path_buf()
};
assert!(!path.exists());
}
fn test_prefix() {
let tmpfile = TempDir::with_prefix_in("prefix", ".").unwrap();
let name = tmpfile.path().file_name().unwrap().to_str().unwrap();
assert!(name.starts_with("prefix"));
}
fn test_customnamed() {
let tmpfile = Builder::new()
.prefix("prefix")
.suffix("suffix")
.rand_bytes(12)
.tempdir()
.unwrap();
let name = tmpfile.path().file_name().unwrap().to_str().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 = TempDir::new().unwrap();
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 = TempDir::new().unwrap();
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 || TempDir::new().unwrap();
let tmp = thread::spawn(f).join().unwrap();
path = tmp.path().to_path_buf();
assert!(path.exists());
}
assert!(!path.exists());
let path;
{
let tmp = TempDir::new().unwrap();
path = tmp.into_path();
}
assert!(path.exists());
fs::remove_dir_all(&path).unwrap();
assert!(!path.exists());
}
fn test_rm_tempdir_close() {
let (tx, rx) = channel();
let f = move || {
let tmp = TempDir::new().unwrap();
tx.send(tmp.path().to_path_buf()).unwrap();
tmp.close().unwrap();
panic!("panic when unwinding past `tmp`");
};
let _ = thread::spawn(f).join();
let path = rx.recv().unwrap();
assert!(!path.exists());
let tmp = TempDir::new().unwrap();
let path = tmp.path().to_path_buf();
let f = move || {
let tmp = tmp;
tmp.close().unwrap();
panic!("panic when unwinding past `tmp`");
};
let _ = thread::spawn(f).join();
assert!(!path.exists());
let path;
{
let f = move || TempDir::new().unwrap();
let tmp = thread::spawn(f).join().unwrap();
path = tmp.path().to_path_buf();
assert!(path.exists());
tmp.close().unwrap();
}
assert!(!path.exists());
let path;
{
let tmp = TempDir::new().unwrap();
path = tmp.into_path();
}
assert!(path.exists());
fs::remove_dir_all(&path).unwrap();
assert!(!path.exists());
}
fn dont_double_panic() {
let r: Result<(), _> = thread::spawn(move || {
let tmpdir = TempDir::new().unwrap();
// Remove the temporary directory so that TempDir sees
// an error on drop
fs::remove_dir(tmpdir.path()).unwrap();
// Panic. If TempDir panics *again* due to the rmdir
// error then the process will abort.
panic!();
})
.join();
assert!(r.is_err());
}
fn in_tmpdir<F>(f: F)
where
F: FnOnce(),
{
let tmpdir = TempDir::new().unwrap();
assert!(env::set_current_dir(tmpdir.path()).is_ok());
f();
}
fn pass_as_asref_path() {
let tempdir = TempDir::new().unwrap();
takes_asref_path(&tempdir);
fn takes_asref_path<T: AsRef<Path>>(path: T) {
let path = path.as_ref();
assert!(path.exists());
}
}
#[test]
fn main() {
in_tmpdir(test_tempdir);
in_tmpdir(test_prefix);
in_tmpdir(test_customnamed);
in_tmpdir(test_rm_tempdir);
in_tmpdir(test_rm_tempdir_close);
in_tmpdir(dont_double_panic);
in_tmpdir(pass_as_asref_path);
}

68
vendor/tempfile/tests/tempfile.rs vendored Normal file
View File

@ -0,0 +1,68 @@
#![deny(rust_2018_idioms)]
use std::fs;
use std::io::{Read, Seek, SeekFrom, Write};
#[cfg(target_os = "linux")]
use std::{
sync::mpsc::{sync_channel, TryRecvError},
thread,
};
#[test]
fn test_basic() {
let mut tmpfile = 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 = tempfile::tempdir().unwrap();
{
let mut tmpfile = 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 = 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 = 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");
}