1 use std::error;
2 use std::ffi::OsStr;
3 use std::fmt;
4 use std::fs::{self, File, OpenOptions};
5 use std::io::{self, Read, Seek, SeekFrom, Write};
6 use std::mem;
7 use std::ops::Deref;
8 #[cfg(unix)]
9 use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
10 #[cfg(target_os = "wasi")]
11 use std::os::wasi::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
12 #[cfg(windows)]
13 use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, RawHandle};
14 use std::path::{Path, PathBuf};
15
16 use crate::env;
17 use crate::error::IoResultExt;
18 use crate::Builder;
19
20 mod imp;
21
22 /// Create a new temporary file.
23 ///
24 /// The file will be created in the location returned by [`env::temp_dir()`].
25 ///
26 /// # Security
27 ///
28 /// This variant is secure/reliable in the presence of a pathological temporary file cleaner.
29 ///
30 /// # Resource Leaking
31 ///
32 /// The temporary file will be automatically removed by the OS when the last handle to it is closed.
33 /// This doesn't rely on Rust destructors being run, so will (almost) never fail to clean up the temporary file.
34 ///
35 /// # Errors
36 ///
37 /// If the file can not be created, `Err` is returned.
38 ///
39 /// # Examples
40 ///
41 /// ```
42 /// use tempfile::tempfile;
43 /// use std::io::Write;
44 ///
45 /// // Create a file inside of `env::temp_dir()`.
46 /// let mut file = tempfile()?;
47 ///
48 /// writeln!(file, "Brian was here. Briefly.")?;
49 /// # Ok::<(), std::io::Error>(())
50 /// ```
tempfile() -> io::Result<File>51 pub fn tempfile() -> io::Result<File> {
52 tempfile_in(env::temp_dir())
53 }
54
55 /// Create a new temporary file in the specified directory.
56 ///
57 /// # Security
58 ///
59 /// This variant is secure/reliable in the presence of a pathological temporary file cleaner.
60 /// If the temporary file isn't created in [`env::temp_dir()`] then temporary file cleaners aren't an issue.
61 ///
62 /// # Resource Leaking
63 ///
64 /// The temporary file will be automatically removed by the OS when the last handle to it is closed.
65 /// This doesn't rely on Rust destructors being run, so will (almost) never fail to clean up the temporary file.
66 ///
67 /// # Errors
68 ///
69 /// If the file can not be created, `Err` is returned.
70 ///
71 /// # Examples
72 ///
73 /// ```
74 /// use tempfile::tempfile_in;
75 /// use std::io::Write;
76 ///
77 /// // Create a file inside of the current working directory
78 /// let mut file = tempfile_in("./")?;
79 ///
80 /// writeln!(file, "Brian was here. Briefly.")?;
81 /// # Ok::<(), std::io::Error>(())
82 /// ```
tempfile_in<P: AsRef<Path>>(dir: P) -> io::Result<File>83 pub fn tempfile_in<P: AsRef<Path>>(dir: P) -> io::Result<File> {
84 imp::create(dir.as_ref())
85 }
86
87 /// Error returned when persisting a temporary file path fails.
88 #[derive(Debug)]
89 pub struct PathPersistError {
90 /// The underlying IO error.
91 pub error: io::Error,
92 /// The temporary file path that couldn't be persisted.
93 pub path: TempPath,
94 }
95
96 impl From<PathPersistError> for io::Error {
97 #[inline]
from(error: PathPersistError) -> io::Error98 fn from(error: PathPersistError) -> io::Error {
99 error.error
100 }
101 }
102
103 impl From<PathPersistError> for TempPath {
104 #[inline]
from(error: PathPersistError) -> TempPath105 fn from(error: PathPersistError) -> TempPath {
106 error.path
107 }
108 }
109
110 impl fmt::Display for PathPersistError {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 write!(f, "failed to persist temporary file path: {}", self.error)
113 }
114 }
115
116 impl error::Error for PathPersistError {
source(&self) -> Option<&(dyn error::Error + 'static)>117 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
118 Some(&self.error)
119 }
120 }
121
122 /// A path to a named temporary file without an open file handle.
123 ///
124 /// This is useful when the temporary file needs to be used by a child process,
125 /// for example.
126 ///
127 /// When dropped, the temporary file is deleted unless `keep(true)` was called
128 /// on the builder that constructed this value.
129 pub struct TempPath {
130 path: Box<Path>,
131 keep: bool,
132 }
133
134 impl TempPath {
135 /// Close and remove the temporary file.
136 ///
137 /// Use this if you want to detect errors in deleting the file.
138 ///
139 /// # Errors
140 ///
141 /// If the file cannot be deleted, `Err` is returned.
142 ///
143 /// # Examples
144 ///
145 /// ```no_run
146 /// use tempfile::NamedTempFile;
147 ///
148 /// let file = NamedTempFile::new()?;
149 ///
150 /// // Close the file, but keep the path to it around.
151 /// let path = file.into_temp_path();
152 ///
153 /// // By closing the `TempPath` explicitly, we can check that it has
154 /// // been deleted successfully. If we don't close it explicitly, the
155 /// // file will still be deleted when `file` goes out of scope, but we
156 /// // won't know whether deleting the file succeeded.
157 /// path.close()?;
158 /// # Ok::<(), std::io::Error>(())
159 /// ```
close(mut self) -> io::Result<()>160 pub fn close(mut self) -> io::Result<()> {
161 let result = fs::remove_file(&self.path).with_err_path(|| &*self.path);
162 self.path = PathBuf::new().into_boxed_path();
163 mem::forget(self);
164 result
165 }
166
167 /// Persist the temporary file at the target path.
168 ///
169 /// If a file exists at the target path, persist will atomically replace it.
170 /// If this method fails, it will return `self` in the resulting
171 /// [`PathPersistError`].
172 ///
173 /// Note: Temporary files cannot be persisted across filesystems. Also
174 /// neither the file contents nor the containing directory are
175 /// synchronized, so the update may not yet have reached the disk when
176 /// `persist` returns.
177 ///
178 /// # Security
179 ///
180 /// Only use this method if you're positive that a temporary file cleaner
181 /// won't have deleted your file. Otherwise, you might end up persisting an
182 /// attacker controlled file.
183 ///
184 /// # Errors
185 ///
186 /// If the file cannot be moved to the new location, `Err` is returned.
187 ///
188 /// # Examples
189 ///
190 /// ```no_run
191 /// use std::io::Write;
192 /// use tempfile::NamedTempFile;
193 ///
194 /// let mut file = NamedTempFile::new()?;
195 /// writeln!(file, "Brian was here. Briefly.")?;
196 ///
197 /// let path = file.into_temp_path();
198 /// path.persist("./saved_file.txt")?;
199 /// # Ok::<(), std::io::Error>(())
200 /// ```
201 ///
202 /// [`PathPersistError`]: struct.PathPersistError.html
persist<P: AsRef<Path>>(mut self, new_path: P) -> Result<(), PathPersistError>203 pub fn persist<P: AsRef<Path>>(mut self, new_path: P) -> Result<(), PathPersistError> {
204 match imp::persist(&self.path, new_path.as_ref(), true) {
205 Ok(_) => {
206 // Don't drop `self`. We don't want to try deleting the old
207 // temporary file path. (It'll fail, but the failure is never
208 // seen.)
209 self.path = PathBuf::new().into_boxed_path();
210 mem::forget(self);
211 Ok(())
212 }
213 Err(e) => Err(PathPersistError {
214 error: e,
215 path: self,
216 }),
217 }
218 }
219
220 /// Persist the temporary file at the target path if and only if no file exists there.
221 ///
222 /// If a file exists at the target path, fail. If this method fails, it will
223 /// return `self` in the resulting [`PathPersistError`].
224 ///
225 /// Note: Temporary files cannot be persisted across filesystems. Also Note:
226 /// This method is not atomic. It can leave the original link to the
227 /// temporary file behind.
228 ///
229 /// # Security
230 ///
231 /// Only use this method if you're positive that a temporary file cleaner
232 /// won't have deleted your file. Otherwise, you might end up persisting an
233 /// attacker controlled file.
234 ///
235 /// # Errors
236 ///
237 /// If the file cannot be moved to the new location or a file already exists
238 /// there, `Err` is returned.
239 ///
240 /// # Examples
241 ///
242 /// ```no_run
243 /// use tempfile::NamedTempFile;
244 /// use std::io::Write;
245 ///
246 /// let mut file = NamedTempFile::new()?;
247 /// writeln!(file, "Brian was here. Briefly.")?;
248 ///
249 /// let path = file.into_temp_path();
250 /// path.persist_noclobber("./saved_file.txt")?;
251 /// # Ok::<(), std::io::Error>(())
252 /// ```
253 ///
254 /// [`PathPersistError`]: struct.PathPersistError.html
persist_noclobber<P: AsRef<Path>>( mut self, new_path: P, ) -> Result<(), PathPersistError>255 pub fn persist_noclobber<P: AsRef<Path>>(
256 mut self,
257 new_path: P,
258 ) -> Result<(), PathPersistError> {
259 match imp::persist(&self.path, new_path.as_ref(), false) {
260 Ok(_) => {
261 // Don't drop `self`. We don't want to try deleting the old
262 // temporary file path. (It'll fail, but the failure is never
263 // seen.)
264 self.path = PathBuf::new().into_boxed_path();
265 mem::forget(self);
266 Ok(())
267 }
268 Err(e) => Err(PathPersistError {
269 error: e,
270 path: self,
271 }),
272 }
273 }
274
275 /// Keep the temporary file from being deleted. This function will turn the
276 /// temporary file into a non-temporary file without moving it.
277 ///
278 /// # Errors
279 ///
280 /// On some platforms (e.g., Windows), we need to mark the file as
281 /// non-temporary. This operation could fail.
282 ///
283 /// # Examples
284 ///
285 /// ```no_run
286 /// use std::io::Write;
287 /// use tempfile::NamedTempFile;
288 ///
289 /// let mut file = NamedTempFile::new()?;
290 /// writeln!(file, "Brian was here. Briefly.")?;
291 ///
292 /// let path = file.into_temp_path();
293 /// let path = path.keep()?;
294 /// # Ok::<(), std::io::Error>(())
295 /// ```
296 ///
297 /// [`PathPersistError`]: struct.PathPersistError.html
keep(mut self) -> Result<PathBuf, PathPersistError>298 pub fn keep(mut self) -> Result<PathBuf, PathPersistError> {
299 match imp::keep(&self.path) {
300 Ok(_) => {
301 // Don't drop `self`. We don't want to try deleting the old
302 // temporary file path. (It'll fail, but the failure is never
303 // seen.)
304 let path = mem::replace(&mut self.path, PathBuf::new().into_boxed_path());
305 mem::forget(self);
306 Ok(path.into())
307 }
308 Err(e) => Err(PathPersistError {
309 error: e,
310 path: self,
311 }),
312 }
313 }
314
315 /// Create a new TempPath from an existing path. This can be done even if no
316 /// file exists at the given path.
317 ///
318 /// This is mostly useful for interacting with libraries and external
319 /// components that provide files to be consumed or expect a path with no
320 /// existing file to be given.
from_path(path: impl Into<PathBuf>) -> Self321 pub fn from_path(path: impl Into<PathBuf>) -> Self {
322 Self {
323 path: path.into().into_boxed_path(),
324 keep: false,
325 }
326 }
327
new(path: PathBuf, keep: bool) -> Self328 pub(crate) fn new(path: PathBuf, keep: bool) -> Self {
329 Self {
330 path: path.into_boxed_path(),
331 keep,
332 }
333 }
334 }
335
336 impl fmt::Debug for TempPath {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338 self.path.fmt(f)
339 }
340 }
341
342 impl Drop for TempPath {
drop(&mut self)343 fn drop(&mut self) {
344 if !self.keep {
345 let _ = fs::remove_file(&self.path);
346 }
347 }
348 }
349
350 impl Deref for TempPath {
351 type Target = Path;
352
deref(&self) -> &Path353 fn deref(&self) -> &Path {
354 &self.path
355 }
356 }
357
358 impl AsRef<Path> for TempPath {
as_ref(&self) -> &Path359 fn as_ref(&self) -> &Path {
360 &self.path
361 }
362 }
363
364 impl AsRef<OsStr> for TempPath {
as_ref(&self) -> &OsStr365 fn as_ref(&self) -> &OsStr {
366 self.path.as_os_str()
367 }
368 }
369
370 /// A named temporary file.
371 ///
372 /// The default constructor, [`NamedTempFile::new()`], creates files in
373 /// the location returned by [`env::temp_dir()`], but `NamedTempFile`
374 /// can be configured to manage a temporary file in any location
375 /// by constructing with [`NamedTempFile::new_in()`].
376 ///
377 /// # Security
378 ///
379 /// Most operating systems employ temporary file cleaners to delete old
380 /// temporary files. Unfortunately these temporary file cleaners don't always
381 /// reliably _detect_ whether the temporary file is still being used.
382 ///
383 /// Specifically, the following sequence of events can happen:
384 ///
385 /// 1. A user creates a temporary file with `NamedTempFile::new()`.
386 /// 2. Time passes.
387 /// 3. The temporary file cleaner deletes (unlinks) the temporary file from the
388 /// filesystem.
389 /// 4. Some other program creates a new file to replace this deleted temporary
390 /// file.
391 /// 5. The user tries to re-open the temporary file (in the same program or in a
392 /// different program) by path. Unfortunately, they'll end up opening the
393 /// file created by the other program, not the original file.
394 ///
395 /// ## Operating System Specific Concerns
396 ///
397 /// The behavior of temporary files and temporary file cleaners differ by
398 /// operating system.
399 ///
400 /// ### Windows
401 ///
402 /// On Windows, open files _can't_ be deleted. This removes most of the concerns
403 /// around temporary file cleaners.
404 ///
405 /// Furthermore, temporary files are, by default, created in per-user temporary
406 /// file directories so only an application running as the same user would be
407 /// able to interfere (which they could do anyways). However, an application
408 /// running as the same user can still _accidentally_ re-create deleted
409 /// temporary files if the number of random bytes in the temporary file name is
410 /// too small.
411 ///
412 /// So, the only real concern on Windows is:
413 ///
414 /// 1. Opening a named temporary file in a world-writable directory.
415 /// 2. Using the `into_temp_path()` and/or `into_parts()` APIs to close the file
416 /// handle without deleting the underlying file.
417 /// 3. Continuing to use the file by path.
418 ///
419 /// ### UNIX
420 ///
421 /// Unlike on Windows, UNIX (and UNIX like) systems allow open files to be
422 /// "unlinked" (deleted).
423 ///
424 /// #### MacOS
425 ///
426 /// Like on Windows, temporary files are created in per-user temporary file
427 /// directories by default so calling `NamedTempFile::new()` should be
428 /// relatively safe.
429 ///
430 /// #### Linux
431 ///
432 /// Unfortunately, most _Linux_ distributions don't create per-user temporary
433 /// file directories. Worse, systemd's tmpfiles daemon (a common temporary file
434 /// cleaner) will happily remove open temporary files if they haven't been
435 /// modified within the last 10 days.
436 ///
437 /// # Resource Leaking
438 ///
439 /// If the program exits before the `NamedTempFile` destructor is
440 /// run, the temporary file will not be deleted. This can happen
441 /// if the process exits using [`std::process::exit()`], a segfault occurs,
442 /// receiving an interrupt signal like `SIGINT` that is not handled, or by using
443 /// a statically declared `NamedTempFile` instance (like with [`lazy_static`]).
444 ///
445 /// Use the [`tempfile()`] function unless you need a named file path.
446 ///
447 /// [`tempfile()`]: fn.tempfile.html
448 /// [`NamedTempFile::new()`]: #method.new
449 /// [`NamedTempFile::new_in()`]: #method.new_in
450 /// [`std::process::exit()`]: http://doc.rust-lang.org/std/process/fn.exit.html
451 /// [`lazy_static`]: https://github.com/rust-lang-nursery/lazy-static.rs/issues/62
452 pub struct NamedTempFile<F = File> {
453 path: TempPath,
454 file: F,
455 }
456
457 impl<F> fmt::Debug for NamedTempFile<F> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result458 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
459 write!(f, "NamedTempFile({:?})", self.path)
460 }
461 }
462
463 impl<F> AsRef<Path> for NamedTempFile<F> {
464 #[inline]
as_ref(&self) -> &Path465 fn as_ref(&self) -> &Path {
466 self.path()
467 }
468 }
469
470 /// Error returned when persisting a temporary file fails.
471 pub struct PersistError<F = File> {
472 /// The underlying IO error.
473 pub error: io::Error,
474 /// The temporary file that couldn't be persisted.
475 pub file: NamedTempFile<F>,
476 }
477
478 impl<F> fmt::Debug for PersistError<F> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480 write!(f, "PersistError({:?})", self.error)
481 }
482 }
483
484 impl<F> From<PersistError<F>> for io::Error {
485 #[inline]
from(error: PersistError<F>) -> io::Error486 fn from(error: PersistError<F>) -> io::Error {
487 error.error
488 }
489 }
490
491 impl<F> From<PersistError<F>> for NamedTempFile<F> {
492 #[inline]
from(error: PersistError<F>) -> NamedTempFile<F>493 fn from(error: PersistError<F>) -> NamedTempFile<F> {
494 error.file
495 }
496 }
497
498 impl<F> fmt::Display for PersistError<F> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result499 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500 write!(f, "failed to persist temporary file: {}", self.error)
501 }
502 }
503
504 impl<F> error::Error for PersistError<F> {
source(&self) -> Option<&(dyn error::Error + 'static)>505 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
506 Some(&self.error)
507 }
508 }
509
510 impl NamedTempFile<File> {
511 /// Create a new named temporary file.
512 ///
513 /// See [`Builder`] for more configuration.
514 ///
515 /// # Security
516 ///
517 /// This will create a temporary file in the default temporary file
518 /// directory (platform dependent). This has security implications on many
519 /// platforms so please read the security section of this type's
520 /// documentation.
521 ///
522 /// Reasons to use this method:
523 ///
524 /// 1. The file has a short lifetime and your temporary file cleaner is
525 /// sane (doesn't delete recently accessed files).
526 ///
527 /// 2. You trust every user on your system (i.e. you are the only user).
528 ///
529 /// 3. You have disabled your system's temporary file cleaner or verified
530 /// that your system doesn't have a temporary file cleaner.
531 ///
532 /// Reasons not to use this method:
533 ///
534 /// 1. You'll fix it later. No you won't.
535 ///
536 /// 2. You don't care about the security of the temporary file. If none of
537 /// the "reasons to use this method" apply, referring to a temporary
538 /// file by name may allow an attacker to create/overwrite your
539 /// non-temporary files. There are exceptions but if you don't already
540 /// know them, don't use this method.
541 ///
542 /// # Errors
543 ///
544 /// If the file can not be created, `Err` is returned.
545 ///
546 /// # Examples
547 ///
548 /// Create a named temporary file and write some data to it:
549 ///
550 /// ```no_run
551 /// use std::io::Write;
552 /// use tempfile::NamedTempFile;
553 ///
554 /// let mut file = NamedTempFile::new()?;
555 ///
556 /// writeln!(file, "Brian was here. Briefly.")?;
557 /// # Ok::<(), std::io::Error>(())
558 /// ```
559 ///
560 /// [`Builder`]: struct.Builder.html
new() -> io::Result<NamedTempFile>561 pub fn new() -> io::Result<NamedTempFile> {
562 Builder::new().tempfile()
563 }
564
565 /// Create a new named temporary file in the specified directory.
566 ///
567 /// This is equivalent to:
568 ///
569 /// ```ignore
570 /// Builder::new().tempfile_in(dir)
571 /// ```
572 ///
573 /// See [`NamedTempFile::new()`] for details.
574 ///
575 /// [`NamedTempFile::new()`]: #method.new
new_in<P: AsRef<Path>>(dir: P) -> io::Result<NamedTempFile>576 pub fn new_in<P: AsRef<Path>>(dir: P) -> io::Result<NamedTempFile> {
577 Builder::new().tempfile_in(dir)
578 }
579
580 /// Create a new named temporary file with the specified filename prefix.
581 ///
582 /// See [`NamedTempFile::new()`] for details.
583 ///
584 /// [`NamedTempFile::new()`]: #method.new
with_prefix<S: AsRef<OsStr>>(prefix: S) -> io::Result<NamedTempFile>585 pub fn with_prefix<S: AsRef<OsStr>>(prefix: S) -> io::Result<NamedTempFile> {
586 Builder::new().prefix(&prefix).tempfile()
587 }
588 /// Create a new named temporary file with the specified filename prefix,
589 /// in the specified directory.
590 ///
591 /// This is equivalent to:
592 ///
593 /// ```ignore
594 /// Builder::new().prefix(&prefix).tempfile_in(directory)
595 /// ```
596 ///
597 /// See [`NamedTempFile::new()`] for details.
598 ///
599 /// [`NamedTempFile::new()`]: #method.new
with_prefix_in<S: AsRef<OsStr>, P: AsRef<Path>>( prefix: S, dir: P, ) -> io::Result<NamedTempFile>600 pub fn with_prefix_in<S: AsRef<OsStr>, P: AsRef<Path>>(
601 prefix: S,
602 dir: P,
603 ) -> io::Result<NamedTempFile> {
604 Builder::new().prefix(&prefix).tempfile_in(dir)
605 }
606 }
607
608 impl<F> NamedTempFile<F> {
609 /// Get the temporary file's path.
610 ///
611 /// # Security
612 ///
613 /// Referring to a temporary file's path may not be secure in all cases.
614 /// Please read the security section on the top level documentation of this
615 /// type for details.
616 ///
617 /// # Examples
618 ///
619 /// ```no_run
620 /// use tempfile::NamedTempFile;
621 ///
622 /// let file = NamedTempFile::new()?;
623 ///
624 /// println!("{:?}", file.path());
625 /// # Ok::<(), std::io::Error>(())
626 /// ```
627 #[inline]
path(&self) -> &Path628 pub fn path(&self) -> &Path {
629 &self.path
630 }
631
632 /// Close and remove the temporary file.
633 ///
634 /// Use this if you want to detect errors in deleting the file.
635 ///
636 /// # Errors
637 ///
638 /// If the file cannot be deleted, `Err` is returned.
639 ///
640 /// # Examples
641 ///
642 /// ```no_run
643 /// use tempfile::NamedTempFile;
644 ///
645 /// let file = NamedTempFile::new()?;
646 ///
647 /// // By closing the `NamedTempFile` explicitly, we can check that it has
648 /// // been deleted successfully. If we don't close it explicitly,
649 /// // the file will still be deleted when `file` goes out
650 /// // of scope, but we won't know whether deleting the file
651 /// // succeeded.
652 /// file.close()?;
653 /// # Ok::<(), std::io::Error>(())
654 /// ```
close(self) -> io::Result<()>655 pub fn close(self) -> io::Result<()> {
656 let NamedTempFile { path, .. } = self;
657 path.close()
658 }
659
660 /// Persist the temporary file at the target path.
661 ///
662 /// If a file exists at the target path, persist will atomically replace it.
663 /// If this method fails, it will return `self` in the resulting
664 /// [`PersistError`].
665 ///
666 /// Note: Temporary files cannot be persisted across filesystems. Also
667 /// neither the file contents nor the containing directory are
668 /// synchronized, so the update may not yet have reached the disk when
669 /// `persist` returns.
670 ///
671 /// # Security
672 ///
673 /// This method persists the temporary file using its path and may not be
674 /// secure in all cases. Please read the security section on the top
675 /// level documentation of this type for details.
676 ///
677 /// # Errors
678 ///
679 /// If the file cannot be moved to the new location, `Err` is returned.
680 ///
681 /// # Examples
682 ///
683 /// ```no_run
684 /// use std::io::Write;
685 /// use tempfile::NamedTempFile;
686 ///
687 /// let file = NamedTempFile::new()?;
688 ///
689 /// let mut persisted_file = file.persist("./saved_file.txt")?;
690 /// writeln!(persisted_file, "Brian was here. Briefly.")?;
691 /// # Ok::<(), std::io::Error>(())
692 /// ```
693 ///
694 /// [`PersistError`]: struct.PersistError.html
persist<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>>695 pub fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> {
696 let NamedTempFile { path, file } = self;
697 match path.persist(new_path) {
698 Ok(_) => Ok(file),
699 Err(err) => {
700 let PathPersistError { error, path } = err;
701 Err(PersistError {
702 file: NamedTempFile { path, file },
703 error,
704 })
705 }
706 }
707 }
708
709 /// Persist the temporary file at the target path if and only if no file exists there.
710 ///
711 /// If a file exists at the target path, fail. If this method fails, it will
712 /// return `self` in the resulting PersistError.
713 ///
714 /// Note: Temporary files cannot be persisted across filesystems. Also Note:
715 /// This method is not atomic. It can leave the original link to the
716 /// temporary file behind.
717 ///
718 /// # Security
719 ///
720 /// This method persists the temporary file using its path and may not be
721 /// secure in all cases. Please read the security section on the top
722 /// level documentation of this type for details.
723 ///
724 /// # Errors
725 ///
726 /// If the file cannot be moved to the new location or a file already exists there,
727 /// `Err` is returned.
728 ///
729 /// # Examples
730 ///
731 /// ```no_run
732 /// use std::io::Write;
733 /// use tempfile::NamedTempFile;
734 ///
735 /// let file = NamedTempFile::new()?;
736 ///
737 /// let mut persisted_file = file.persist_noclobber("./saved_file.txt")?;
738 /// writeln!(persisted_file, "Brian was here. Briefly.")?;
739 /// # Ok::<(), std::io::Error>(())
740 /// ```
persist_noclobber<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>>741 pub fn persist_noclobber<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> {
742 let NamedTempFile { path, file } = self;
743 match path.persist_noclobber(new_path) {
744 Ok(_) => Ok(file),
745 Err(err) => {
746 let PathPersistError { error, path } = err;
747 Err(PersistError {
748 file: NamedTempFile { path, file },
749 error,
750 })
751 }
752 }
753 }
754
755 /// Keep the temporary file from being deleted. This function will turn the
756 /// temporary file into a non-temporary file without moving it.
757 ///
758 ///
759 /// # Errors
760 ///
761 /// On some platforms (e.g., Windows), we need to mark the file as
762 /// non-temporary. This operation could fail.
763 ///
764 /// # Examples
765 ///
766 /// ```no_run
767 /// use std::io::Write;
768 /// use tempfile::NamedTempFile;
769 ///
770 /// let mut file = NamedTempFile::new()?;
771 /// writeln!(file, "Brian was here. Briefly.")?;
772 ///
773 /// let (file, path) = file.keep()?;
774 /// # Ok::<(), std::io::Error>(())
775 /// ```
776 ///
777 /// [`PathPersistError`]: struct.PathPersistError.html
keep(self) -> Result<(F, PathBuf), PersistError<F>>778 pub fn keep(self) -> Result<(F, PathBuf), PersistError<F>> {
779 let (file, path) = (self.file, self.path);
780 match path.keep() {
781 Ok(path) => Ok((file, path)),
782 Err(PathPersistError { error, path }) => Err(PersistError {
783 file: NamedTempFile { path, file },
784 error,
785 }),
786 }
787 }
788
789 /// Get a reference to the underlying file.
as_file(&self) -> &F790 pub fn as_file(&self) -> &F {
791 &self.file
792 }
793
794 /// Get a mutable reference to the underlying file.
as_file_mut(&mut self) -> &mut F795 pub fn as_file_mut(&mut self) -> &mut F {
796 &mut self.file
797 }
798
799 /// Convert the temporary file into a `std::fs::File`.
800 ///
801 /// The inner file will be deleted.
into_file(self) -> F802 pub fn into_file(self) -> F {
803 self.file
804 }
805
806 /// Closes the file, leaving only the temporary file path.
807 ///
808 /// This is useful when another process must be able to open the temporary
809 /// file.
into_temp_path(self) -> TempPath810 pub fn into_temp_path(self) -> TempPath {
811 self.path
812 }
813
814 /// Converts the named temporary file into its constituent parts.
815 ///
816 /// Note: When the path is dropped, the file is deleted but the file handle
817 /// is still usable.
into_parts(self) -> (F, TempPath)818 pub fn into_parts(self) -> (F, TempPath) {
819 (self.file, self.path)
820 }
821
822 /// Creates a `NamedTempFile` from its constituent parts.
823 ///
824 /// This can be used with [`NamedTempFile::into_parts`] to reconstruct the
825 /// `NamedTempFile`.
from_parts(file: F, path: TempPath) -> Self826 pub fn from_parts(file: F, path: TempPath) -> Self {
827 Self { file, path }
828 }
829 }
830
831 impl NamedTempFile<File> {
832 /// Securely reopen the temporary file.
833 ///
834 /// This function is useful when you need multiple independent handles to
835 /// the same file. It's perfectly fine to drop the original `NamedTempFile`
836 /// while holding on to `File`s returned by this function; the `File`s will
837 /// remain usable. However, they may not be nameable.
838 ///
839 /// # Errors
840 ///
841 /// If the file cannot be reopened, `Err` is returned.
842 ///
843 /// # Security
844 ///
845 /// Unlike `File::open(my_temp_file.path())`, `NamedTempFile::reopen()`
846 /// guarantees that the re-opened file is the _same_ file, even in the
847 /// presence of pathological temporary file cleaners.
848 ///
849 /// # Examples
850 ///
851 /// ```no_run
852 /// use tempfile::NamedTempFile;
853 ///
854 /// let file = NamedTempFile::new()?;
855 ///
856 /// let another_handle = file.reopen()?;
857 /// # Ok::<(), std::io::Error>(())
858 /// ```
reopen(&self) -> io::Result<File>859 pub fn reopen(&self) -> io::Result<File> {
860 imp::reopen(self.as_file(), NamedTempFile::path(self))
861 .with_err_path(|| NamedTempFile::path(self))
862 }
863 }
864
865 impl<F: Read> Read for NamedTempFile<F> {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>866 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
867 self.as_file_mut().read(buf).with_err_path(|| self.path())
868 }
869
read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize>870 fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
871 self.as_file_mut()
872 .read_vectored(bufs)
873 .with_err_path(|| self.path())
874 }
875
read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize>876 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
877 self.as_file_mut()
878 .read_to_end(buf)
879 .with_err_path(|| self.path())
880 }
881
read_to_string(&mut self, buf: &mut String) -> io::Result<usize>882 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
883 self.as_file_mut()
884 .read_to_string(buf)
885 .with_err_path(|| self.path())
886 }
887
read_exact(&mut self, buf: &mut [u8]) -> io::Result<()>888 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
889 self.as_file_mut()
890 .read_exact(buf)
891 .with_err_path(|| self.path())
892 }
893 }
894
895 impl Read for &NamedTempFile<File> {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>896 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
897 self.as_file().read(buf).with_err_path(|| self.path())
898 }
899
read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize>900 fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
901 self.as_file()
902 .read_vectored(bufs)
903 .with_err_path(|| self.path())
904 }
905
read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize>906 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
907 self.as_file()
908 .read_to_end(buf)
909 .with_err_path(|| self.path())
910 }
911
read_to_string(&mut self, buf: &mut String) -> io::Result<usize>912 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
913 self.as_file()
914 .read_to_string(buf)
915 .with_err_path(|| self.path())
916 }
917
read_exact(&mut self, buf: &mut [u8]) -> io::Result<()>918 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
919 self.as_file().read_exact(buf).with_err_path(|| self.path())
920 }
921 }
922
923 impl<F: Write> Write for NamedTempFile<F> {
write(&mut self, buf: &[u8]) -> io::Result<usize>924 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
925 self.as_file_mut().write(buf).with_err_path(|| self.path())
926 }
927 #[inline]
flush(&mut self) -> io::Result<()>928 fn flush(&mut self) -> io::Result<()> {
929 self.as_file_mut().flush().with_err_path(|| self.path())
930 }
931
write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize>932 fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
933 self.as_file_mut()
934 .write_vectored(bufs)
935 .with_err_path(|| self.path())
936 }
937
write_all(&mut self, buf: &[u8]) -> io::Result<()>938 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
939 self.as_file_mut()
940 .write_all(buf)
941 .with_err_path(|| self.path())
942 }
943
write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()>944 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
945 self.as_file_mut()
946 .write_fmt(fmt)
947 .with_err_path(|| self.path())
948 }
949 }
950
951 impl Write for &NamedTempFile<File> {
write(&mut self, buf: &[u8]) -> io::Result<usize>952 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
953 self.as_file().write(buf).with_err_path(|| self.path())
954 }
955 #[inline]
flush(&mut self) -> io::Result<()>956 fn flush(&mut self) -> io::Result<()> {
957 self.as_file().flush().with_err_path(|| self.path())
958 }
959
write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize>960 fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
961 self.as_file()
962 .write_vectored(bufs)
963 .with_err_path(|| self.path())
964 }
965
write_all(&mut self, buf: &[u8]) -> io::Result<()>966 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
967 self.as_file().write_all(buf).with_err_path(|| self.path())
968 }
969
write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()>970 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
971 self.as_file().write_fmt(fmt).with_err_path(|| self.path())
972 }
973 }
974
975 impl<F: Seek> Seek for NamedTempFile<F> {
seek(&mut self, pos: SeekFrom) -> io::Result<u64>976 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
977 self.as_file_mut().seek(pos).with_err_path(|| self.path())
978 }
979 }
980
981 impl Seek for &NamedTempFile<File> {
seek(&mut self, pos: SeekFrom) -> io::Result<u64>982 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
983 self.as_file().seek(pos).with_err_path(|| self.path())
984 }
985 }
986
987 #[cfg(any(unix, target_os = "wasi"))]
988 impl<F: AsFd> AsFd for NamedTempFile<F> {
as_fd(&self) -> BorrowedFd<'_>989 fn as_fd(&self) -> BorrowedFd<'_> {
990 self.as_file().as_fd()
991 }
992 }
993
994 #[cfg(any(unix, target_os = "wasi"))]
995 impl<F: AsRawFd> AsRawFd for NamedTempFile<F> {
996 #[inline]
as_raw_fd(&self) -> RawFd997 fn as_raw_fd(&self) -> RawFd {
998 self.as_file().as_raw_fd()
999 }
1000 }
1001
1002 #[cfg(windows)]
1003 impl<F: AsHandle> AsHandle for NamedTempFile<F> {
1004 #[inline]
as_handle(&self) -> BorrowedHandle<'_>1005 fn as_handle(&self) -> BorrowedHandle<'_> {
1006 self.as_file().as_handle()
1007 }
1008 }
1009
1010 #[cfg(windows)]
1011 impl<F: AsRawHandle> AsRawHandle for NamedTempFile<F> {
1012 #[inline]
as_raw_handle(&self) -> RawHandle1013 fn as_raw_handle(&self) -> RawHandle {
1014 self.as_file().as_raw_handle()
1015 }
1016 }
1017
create_named( mut path: PathBuf, open_options: &mut OpenOptions, permissions: Option<&std::fs::Permissions>, keep: bool, ) -> io::Result<NamedTempFile>1018 pub(crate) fn create_named(
1019 mut path: PathBuf,
1020 open_options: &mut OpenOptions,
1021 permissions: Option<&std::fs::Permissions>,
1022 keep: bool,
1023 ) -> io::Result<NamedTempFile> {
1024 // Make the path absolute. Otherwise, changing directories could cause us to
1025 // delete the wrong file.
1026 if !path.is_absolute() {
1027 path = std::env::current_dir()?.join(path)
1028 }
1029 imp::create_named(&path, open_options, permissions)
1030 .with_err_path(|| path.clone())
1031 .map(|file| NamedTempFile {
1032 path: TempPath {
1033 path: path.into_boxed_path(),
1034 keep,
1035 },
1036 file,
1037 })
1038 }
1039