/rust/registry/src/index.crates.io-1949cf8c6b5b557f/tempfile-3.17.1/src/file/mod.rs
Line | Count | Source |
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 | | /// ``` |
51 | 0 | pub fn tempfile() -> io::Result<File> { |
52 | 0 | tempfile_in(env::temp_dir()) |
53 | 0 | } |
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 | | /// ``` |
83 | 0 | pub fn tempfile_in<P: AsRef<Path>>(dir: P) -> io::Result<File> { |
84 | 0 | imp::create(dir.as_ref()) |
85 | 0 | } |
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] |
98 | 0 | fn from(error: PathPersistError) -> io::Error { |
99 | 0 | error.error |
100 | 0 | } |
101 | | } |
102 | | |
103 | | impl From<PathPersistError> for TempPath { |
104 | | #[inline] |
105 | 0 | fn from(error: PathPersistError) -> TempPath { |
106 | 0 | error.path |
107 | 0 | } |
108 | | } |
109 | | |
110 | | impl fmt::Display for PathPersistError { |
111 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
112 | 0 | write!(f, "failed to persist temporary file path: {}", self.error) |
113 | 0 | } |
114 | | } |
115 | | |
116 | | impl error::Error for PathPersistError { |
117 | 0 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { |
118 | 0 | Some(&self.error) |
119 | 0 | } |
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 | | /// ``` |
160 | 0 | pub fn close(mut self) -> io::Result<()> { |
161 | 0 | let result = fs::remove_file(&self.path).with_err_path(|| &*self.path); |
162 | 0 | self.path = PathBuf::new().into_boxed_path(); |
163 | 0 | mem::forget(self); |
164 | 0 | result |
165 | 0 | } |
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 |
203 | 0 | pub fn persist<P: AsRef<Path>>(mut self, new_path: P) -> Result<(), PathPersistError> { |
204 | 0 | 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 | 0 | self.path = PathBuf::new().into_boxed_path(); |
210 | 0 | mem::forget(self); |
211 | 0 | Ok(()) |
212 | | } |
213 | 0 | Err(e) => Err(PathPersistError { |
214 | 0 | error: e, |
215 | 0 | path: self, |
216 | 0 | }), |
217 | | } |
218 | 0 | } |
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 |
255 | 0 | pub fn persist_noclobber<P: AsRef<Path>>( |
256 | 0 | mut self, |
257 | 0 | new_path: P, |
258 | 0 | ) -> Result<(), PathPersistError> { |
259 | 0 | 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 | 0 | self.path = PathBuf::new().into_boxed_path(); |
265 | 0 | mem::forget(self); |
266 | 0 | Ok(()) |
267 | | } |
268 | 0 | Err(e) => Err(PathPersistError { |
269 | 0 | error: e, |
270 | 0 | path: self, |
271 | 0 | }), |
272 | | } |
273 | 0 | } |
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 |
298 | 0 | pub fn keep(mut self) -> Result<PathBuf, PathPersistError> { |
299 | 0 | 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 | 0 | let path = mem::replace(&mut self.path, PathBuf::new().into_boxed_path()); |
305 | 0 | mem::forget(self); |
306 | 0 | Ok(path.into()) |
307 | | } |
308 | 0 | Err(e) => Err(PathPersistError { |
309 | 0 | error: e, |
310 | 0 | path: self, |
311 | 0 | }), |
312 | | } |
313 | 0 | } |
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. |
321 | 0 | pub fn from_path(path: impl Into<PathBuf>) -> Self { |
322 | 0 | Self { |
323 | 0 | path: path.into().into_boxed_path(), |
324 | 0 | keep: false, |
325 | 0 | } |
326 | 0 | } |
327 | | |
328 | 0 | pub(crate) fn new(path: PathBuf, keep: bool) -> Self { |
329 | 0 | Self { |
330 | 0 | path: path.into_boxed_path(), |
331 | 0 | keep, |
332 | 0 | } |
333 | 0 | } |
334 | | } |
335 | | |
336 | | impl fmt::Debug for TempPath { |
337 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
338 | 0 | self.path.fmt(f) |
339 | 0 | } |
340 | | } |
341 | | |
342 | | impl Drop for TempPath { |
343 | 0 | fn drop(&mut self) { |
344 | 0 | if !self.keep { |
345 | 0 | let _ = fs::remove_file(&self.path); |
346 | 0 | } |
347 | 0 | } |
348 | | } |
349 | | |
350 | | impl Deref for TempPath { |
351 | | type Target = Path; |
352 | | |
353 | 0 | fn deref(&self) -> &Path { |
354 | 0 | &self.path |
355 | 0 | } |
356 | | } |
357 | | |
358 | | impl AsRef<Path> for TempPath { |
359 | 0 | fn as_ref(&self) -> &Path { |
360 | 0 | &self.path |
361 | 0 | } |
362 | | } |
363 | | |
364 | | impl AsRef<OsStr> for TempPath { |
365 | 0 | fn as_ref(&self) -> &OsStr { |
366 | 0 | self.path.as_os_str() |
367 | 0 | } |
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, temporary files are, by default, created in per-user temporary |
403 | | /// file directories so only an application running as the same user would be |
404 | | /// able to interfere (which they could do anyways). However, an application |
405 | | /// running as the same user can still _accidentally_ re-create deleted |
406 | | /// temporary files if the number of random bytes in the temporary file name is |
407 | | /// too small. |
408 | | /// |
409 | | /// ### MacOS |
410 | | /// |
411 | | /// Like on Windows, temporary files are created in per-user temporary file |
412 | | /// directories by default so calling `NamedTempFile::new()` should be |
413 | | /// relatively safe. |
414 | | /// |
415 | | /// ### Linux |
416 | | /// |
417 | | /// Unfortunately, most _Linux_ distributions don't create per-user temporary |
418 | | /// file directories. Worse, systemd's tmpfiles daemon (a common temporary file |
419 | | /// cleaner) will happily remove open temporary files if they haven't been |
420 | | /// modified within the last 10 days. |
421 | | /// |
422 | | /// # Resource Leaking |
423 | | /// |
424 | | /// If the program exits before the `NamedTempFile` destructor is |
425 | | /// run, the temporary file will not be deleted. This can happen |
426 | | /// if the process exits using [`std::process::exit()`], a segfault occurs, |
427 | | /// receiving an interrupt signal like `SIGINT` that is not handled, or by using |
428 | | /// a statically declared `NamedTempFile` instance (like with [`lazy_static`]). |
429 | | /// |
430 | | /// Use the [`tempfile()`] function unless you need a named file path. |
431 | | /// |
432 | | /// [`tempfile()`]: fn.tempfile.html |
433 | | /// [`NamedTempFile::new()`]: #method.new |
434 | | /// [`NamedTempFile::new_in()`]: #method.new_in |
435 | | /// [`std::process::exit()`]: http://doc.rust-lang.org/std/process/fn.exit.html |
436 | | /// [`lazy_static`]: https://github.com/rust-lang-nursery/lazy-static.rs/issues/62 |
437 | | pub struct NamedTempFile<F = File> { |
438 | | path: TempPath, |
439 | | file: F, |
440 | | } |
441 | | |
442 | | impl<F> fmt::Debug for NamedTempFile<F> { |
443 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
444 | 0 | write!(f, "NamedTempFile({:?})", self.path) |
445 | 0 | } |
446 | | } |
447 | | |
448 | | impl<F> AsRef<Path> for NamedTempFile<F> { |
449 | | #[inline] |
450 | 0 | fn as_ref(&self) -> &Path { |
451 | 0 | self.path() |
452 | 0 | } |
453 | | } |
454 | | |
455 | | /// Error returned when persisting a temporary file fails. |
456 | | pub struct PersistError<F = File> { |
457 | | /// The underlying IO error. |
458 | | pub error: io::Error, |
459 | | /// The temporary file that couldn't be persisted. |
460 | | pub file: NamedTempFile<F>, |
461 | | } |
462 | | |
463 | | impl<F> fmt::Debug for PersistError<F> { |
464 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
465 | 0 | write!(f, "PersistError({:?})", self.error) |
466 | 0 | } |
467 | | } |
468 | | |
469 | | impl<F> From<PersistError<F>> for io::Error { |
470 | | #[inline] |
471 | 0 | fn from(error: PersistError<F>) -> io::Error { |
472 | 0 | error.error |
473 | 0 | } |
474 | | } |
475 | | |
476 | | impl<F> From<PersistError<F>> for NamedTempFile<F> { |
477 | | #[inline] |
478 | 0 | fn from(error: PersistError<F>) -> NamedTempFile<F> { |
479 | 0 | error.file |
480 | 0 | } |
481 | | } |
482 | | |
483 | | impl<F> fmt::Display for PersistError<F> { |
484 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
485 | 0 | write!(f, "failed to persist temporary file: {}", self.error) |
486 | 0 | } |
487 | | } |
488 | | |
489 | | impl<F> error::Error for PersistError<F> { |
490 | 0 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { |
491 | 0 | Some(&self.error) |
492 | 0 | } |
493 | | } |
494 | | |
495 | | impl NamedTempFile<File> { |
496 | | /// Create a new named temporary file. |
497 | | /// |
498 | | /// See [`Builder`] for more configuration. |
499 | | /// |
500 | | /// # Security |
501 | | /// |
502 | | /// This will create a temporary file in the default temporary file |
503 | | /// directory (platform dependent). This has security implications on many |
504 | | /// platforms so please read the security section of this type's |
505 | | /// documentation. |
506 | | /// |
507 | | /// Reasons to use this method: |
508 | | /// |
509 | | /// 1. The file has a short lifetime and your temporary file cleaner is |
510 | | /// sane (doesn't delete recently accessed files). |
511 | | /// |
512 | | /// 2. You trust every user on your system (i.e. you are the only user). |
513 | | /// |
514 | | /// 3. You have disabled your system's temporary file cleaner or verified |
515 | | /// that your system doesn't have a temporary file cleaner. |
516 | | /// |
517 | | /// Reasons not to use this method: |
518 | | /// |
519 | | /// 1. You'll fix it later. No you won't. |
520 | | /// |
521 | | /// 2. You don't care about the security of the temporary file. If none of |
522 | | /// the "reasons to use this method" apply, referring to a temporary |
523 | | /// file by name may allow an attacker to create/overwrite your |
524 | | /// non-temporary files. There are exceptions but if you don't already |
525 | | /// know them, don't use this method. |
526 | | /// |
527 | | /// # Errors |
528 | | /// |
529 | | /// If the file can not be created, `Err` is returned. |
530 | | /// |
531 | | /// # Examples |
532 | | /// |
533 | | /// Create a named temporary file and write some data to it: |
534 | | /// |
535 | | /// ```no_run |
536 | | /// use std::io::Write; |
537 | | /// use tempfile::NamedTempFile; |
538 | | /// |
539 | | /// let mut file = NamedTempFile::new()?; |
540 | | /// |
541 | | /// writeln!(file, "Brian was here. Briefly.")?; |
542 | | /// # Ok::<(), std::io::Error>(()) |
543 | | /// ``` |
544 | | /// |
545 | | /// [`Builder`]: struct.Builder.html |
546 | 0 | pub fn new() -> io::Result<NamedTempFile> { |
547 | 0 | Builder::new().tempfile() |
548 | 0 | } |
549 | | |
550 | | /// Create a new named temporary file in the specified directory. |
551 | | /// |
552 | | /// This is equivalent to: |
553 | | /// |
554 | | /// ```ignore |
555 | | /// Builder::new().tempfile_in(dir) |
556 | | /// ``` |
557 | | /// |
558 | | /// See [`NamedTempFile::new()`] for details. |
559 | | /// |
560 | | /// [`NamedTempFile::new()`]: #method.new |
561 | 0 | pub fn new_in<P: AsRef<Path>>(dir: P) -> io::Result<NamedTempFile> { |
562 | 0 | Builder::new().tempfile_in(dir) |
563 | 0 | } |
564 | | |
565 | | /// Create a new named temporary file with the specified filename suffix. |
566 | | /// |
567 | | /// See [`NamedTempFile::new()`] for details. |
568 | | /// |
569 | | /// [`NamedTempFile::new()`]: #method.new |
570 | 0 | pub fn with_suffix<S: AsRef<OsStr>>(suffix: S) -> io::Result<NamedTempFile> { |
571 | 0 | Builder::new().suffix(&suffix).tempfile() |
572 | 0 | } |
573 | | /// Create a new named temporary file with the specified filename suffix, |
574 | | /// in the specified directory. |
575 | | /// |
576 | | /// This is equivalent to: |
577 | | /// |
578 | | /// ```ignore |
579 | | /// Builder::new().suffix(&suffix).tempfile_in(directory) |
580 | | /// ``` |
581 | | /// |
582 | | /// See [`NamedTempFile::new()`] for details. |
583 | | /// |
584 | | /// [`NamedTempFile::new()`]: #method.new |
585 | 0 | pub fn with_suffix_in<S: AsRef<OsStr>, P: AsRef<Path>>( |
586 | 0 | suffix: S, |
587 | 0 | dir: P, |
588 | 0 | ) -> io::Result<NamedTempFile> { |
589 | 0 | Builder::new().suffix(&suffix).tempfile_in(dir) |
590 | 0 | } |
591 | | |
592 | | /// Create a new named temporary file with the specified filename prefix. |
593 | | /// |
594 | | /// See [`NamedTempFile::new()`] for details. |
595 | | /// |
596 | | /// [`NamedTempFile::new()`]: #method.new |
597 | 0 | pub fn with_prefix<S: AsRef<OsStr>>(prefix: S) -> io::Result<NamedTempFile> { |
598 | 0 | Builder::new().prefix(&prefix).tempfile() |
599 | 0 | } |
600 | | /// Create a new named temporary file with the specified filename prefix, |
601 | | /// in the specified directory. |
602 | | /// |
603 | | /// This is equivalent to: |
604 | | /// |
605 | | /// ```ignore |
606 | | /// Builder::new().prefix(&prefix).tempfile_in(directory) |
607 | | /// ``` |
608 | | /// |
609 | | /// See [`NamedTempFile::new()`] for details. |
610 | | /// |
611 | | /// [`NamedTempFile::new()`]: #method.new |
612 | 0 | pub fn with_prefix_in<S: AsRef<OsStr>, P: AsRef<Path>>( |
613 | 0 | prefix: S, |
614 | 0 | dir: P, |
615 | 0 | ) -> io::Result<NamedTempFile> { |
616 | 0 | Builder::new().prefix(&prefix).tempfile_in(dir) |
617 | 0 | } |
618 | | } |
619 | | |
620 | | impl<F> NamedTempFile<F> { |
621 | | /// Get the temporary file's path. |
622 | | /// |
623 | | /// # Security |
624 | | /// |
625 | | /// Referring to a temporary file's path may not be secure in all cases. |
626 | | /// Please read the security section on the top level documentation of this |
627 | | /// type for details. |
628 | | /// |
629 | | /// # Examples |
630 | | /// |
631 | | /// ```no_run |
632 | | /// use tempfile::NamedTempFile; |
633 | | /// |
634 | | /// let file = NamedTempFile::new()?; |
635 | | /// |
636 | | /// println!("{:?}", file.path()); |
637 | | /// # Ok::<(), std::io::Error>(()) |
638 | | /// ``` |
639 | | #[inline] |
640 | 0 | pub fn path(&self) -> &Path { |
641 | 0 | &self.path |
642 | 0 | } |
643 | | |
644 | | /// Close and remove the temporary file. |
645 | | /// |
646 | | /// Use this if you want to detect errors in deleting the file. |
647 | | /// |
648 | | /// # Errors |
649 | | /// |
650 | | /// If the file cannot be deleted, `Err` is returned. |
651 | | /// |
652 | | /// # Examples |
653 | | /// |
654 | | /// ```no_run |
655 | | /// use tempfile::NamedTempFile; |
656 | | /// |
657 | | /// let file = NamedTempFile::new()?; |
658 | | /// |
659 | | /// // By closing the `NamedTempFile` explicitly, we can check that it has |
660 | | /// // been deleted successfully. If we don't close it explicitly, |
661 | | /// // the file will still be deleted when `file` goes out |
662 | | /// // of scope, but we won't know whether deleting the file |
663 | | /// // succeeded. |
664 | | /// file.close()?; |
665 | | /// # Ok::<(), std::io::Error>(()) |
666 | | /// ``` |
667 | 0 | pub fn close(self) -> io::Result<()> { |
668 | 0 | let NamedTempFile { path, .. } = self; |
669 | 0 | path.close() |
670 | 0 | } |
671 | | |
672 | | /// Persist the temporary file at the target path. |
673 | | /// |
674 | | /// If a file exists at the target path, persist will atomically replace it. |
675 | | /// If this method fails, it will return `self` in the resulting |
676 | | /// [`PersistError`]. |
677 | | /// |
678 | | /// Note: Temporary files cannot be persisted across filesystems. Also |
679 | | /// neither the file contents nor the containing directory are |
680 | | /// synchronized, so the update may not yet have reached the disk when |
681 | | /// `persist` returns. |
682 | | /// |
683 | | /// # Security |
684 | | /// |
685 | | /// This method persists the temporary file using its path and may not be |
686 | | /// secure in all cases. Please read the security section on the top |
687 | | /// level documentation of this type for details. |
688 | | /// |
689 | | /// # Errors |
690 | | /// |
691 | | /// If the file cannot be moved to the new location, `Err` is returned. |
692 | | /// |
693 | | /// # Examples |
694 | | /// |
695 | | /// ```no_run |
696 | | /// use std::io::Write; |
697 | | /// use tempfile::NamedTempFile; |
698 | | /// |
699 | | /// let file = NamedTempFile::new()?; |
700 | | /// |
701 | | /// let mut persisted_file = file.persist("./saved_file.txt")?; |
702 | | /// writeln!(persisted_file, "Brian was here. Briefly.")?; |
703 | | /// # Ok::<(), std::io::Error>(()) |
704 | | /// ``` |
705 | | /// |
706 | | /// [`PersistError`]: struct.PersistError.html |
707 | 0 | pub fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> { |
708 | 0 | let NamedTempFile { path, file } = self; |
709 | 0 | match path.persist(new_path) { |
710 | 0 | Ok(_) => Ok(file), |
711 | 0 | Err(err) => { |
712 | 0 | let PathPersistError { error, path } = err; |
713 | 0 | Err(PersistError { |
714 | 0 | file: NamedTempFile { path, file }, |
715 | 0 | error, |
716 | 0 | }) |
717 | | } |
718 | | } |
719 | 0 | } |
720 | | |
721 | | /// Persist the temporary file at the target path if and only if no file exists there. |
722 | | /// |
723 | | /// If a file exists at the target path, fail. If this method fails, it will |
724 | | /// return `self` in the resulting PersistError. |
725 | | /// |
726 | | /// Note: Temporary files cannot be persisted across filesystems. Also Note: |
727 | | /// This method is not atomic. It can leave the original link to the |
728 | | /// temporary file behind. |
729 | | /// |
730 | | /// # Security |
731 | | /// |
732 | | /// This method persists the temporary file using its path and may not be |
733 | | /// secure in all cases. Please read the security section on the top |
734 | | /// level documentation of this type for details. |
735 | | /// |
736 | | /// # Errors |
737 | | /// |
738 | | /// If the file cannot be moved to the new location or a file already exists there, |
739 | | /// `Err` is returned. |
740 | | /// |
741 | | /// # Examples |
742 | | /// |
743 | | /// ```no_run |
744 | | /// use std::io::Write; |
745 | | /// use tempfile::NamedTempFile; |
746 | | /// |
747 | | /// let file = NamedTempFile::new()?; |
748 | | /// |
749 | | /// let mut persisted_file = file.persist_noclobber("./saved_file.txt")?; |
750 | | /// writeln!(persisted_file, "Brian was here. Briefly.")?; |
751 | | /// # Ok::<(), std::io::Error>(()) |
752 | | /// ``` |
753 | 0 | pub fn persist_noclobber<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> { |
754 | 0 | let NamedTempFile { path, file } = self; |
755 | 0 | match path.persist_noclobber(new_path) { |
756 | 0 | Ok(_) => Ok(file), |
757 | 0 | Err(err) => { |
758 | 0 | let PathPersistError { error, path } = err; |
759 | 0 | Err(PersistError { |
760 | 0 | file: NamedTempFile { path, file }, |
761 | 0 | error, |
762 | 0 | }) |
763 | | } |
764 | | } |
765 | 0 | } |
766 | | |
767 | | /// Keep the temporary file from being deleted. This function will turn the |
768 | | /// temporary file into a non-temporary file without moving it. |
769 | | /// |
770 | | /// |
771 | | /// # Errors |
772 | | /// |
773 | | /// On some platforms (e.g., Windows), we need to mark the file as |
774 | | /// non-temporary. This operation could fail. |
775 | | /// |
776 | | /// # Examples |
777 | | /// |
778 | | /// ```no_run |
779 | | /// use std::io::Write; |
780 | | /// use tempfile::NamedTempFile; |
781 | | /// |
782 | | /// let mut file = NamedTempFile::new()?; |
783 | | /// writeln!(file, "Brian was here. Briefly.")?; |
784 | | /// |
785 | | /// let (file, path) = file.keep()?; |
786 | | /// # Ok::<(), std::io::Error>(()) |
787 | | /// ``` |
788 | | /// |
789 | | /// [`PathPersistError`]: struct.PathPersistError.html |
790 | 0 | pub fn keep(self) -> Result<(F, PathBuf), PersistError<F>> { |
791 | 0 | let (file, path) = (self.file, self.path); |
792 | 0 | match path.keep() { |
793 | 0 | Ok(path) => Ok((file, path)), |
794 | 0 | Err(PathPersistError { error, path }) => Err(PersistError { |
795 | 0 | file: NamedTempFile { path, file }, |
796 | 0 | error, |
797 | 0 | }), |
798 | | } |
799 | 0 | } |
800 | | |
801 | | /// Get a reference to the underlying file. |
802 | 0 | pub fn as_file(&self) -> &F { |
803 | 0 | &self.file |
804 | 0 | } |
805 | | |
806 | | /// Get a mutable reference to the underlying file. |
807 | 0 | pub fn as_file_mut(&mut self) -> &mut F { |
808 | 0 | &mut self.file |
809 | 0 | } Unexecuted instantiation: <tempfile::file::NamedTempFile>::as_file_mut Unexecuted instantiation: <tempfile::file::NamedTempFile<_>>::as_file_mut |
810 | | |
811 | | /// Turn this named temporary file into an "unnamed" temporary file as if you |
812 | | /// had constructed it with [`tempfile()`]. |
813 | | /// |
814 | | /// The underlying file will be removed from the filesystem but the returned [`File`] |
815 | | /// can still be read/written. |
816 | 0 | pub fn into_file(self) -> F { |
817 | 0 | self.file |
818 | 0 | } |
819 | | |
820 | | /// Closes the file, leaving only the temporary file path. |
821 | | /// |
822 | | /// This is useful when another process must be able to open the temporary |
823 | | /// file. |
824 | 0 | pub fn into_temp_path(self) -> TempPath { |
825 | 0 | self.path |
826 | 0 | } |
827 | | |
828 | | /// Converts the named temporary file into its constituent parts. |
829 | | /// |
830 | | /// Note: When the path is dropped, the underlying file will be removed from the filesystem but |
831 | | /// the returned [`File`] can still be read/written. |
832 | 0 | pub fn into_parts(self) -> (F, TempPath) { |
833 | 0 | (self.file, self.path) |
834 | 0 | } |
835 | | |
836 | | /// Creates a `NamedTempFile` from its constituent parts. |
837 | | /// |
838 | | /// This can be used with [`NamedTempFile::into_parts`] to reconstruct the |
839 | | /// `NamedTempFile`. |
840 | 0 | pub fn from_parts(file: F, path: TempPath) -> Self { |
841 | 0 | Self { file, path } |
842 | 0 | } |
843 | | } |
844 | | |
845 | | impl NamedTempFile<File> { |
846 | | /// Securely reopen the temporary file. |
847 | | /// |
848 | | /// This function is useful when you need multiple independent handles to |
849 | | /// the same file. It's perfectly fine to drop the original `NamedTempFile` |
850 | | /// while holding on to `File`s returned by this function; the `File`s will |
851 | | /// remain usable. However, they may not be nameable. |
852 | | /// |
853 | | /// # Errors |
854 | | /// |
855 | | /// If the file cannot be reopened, `Err` is returned. |
856 | | /// |
857 | | /// # Security |
858 | | /// |
859 | | /// Unlike `File::open(my_temp_file.path())`, `NamedTempFile::reopen()` |
860 | | /// guarantees that the re-opened file is the _same_ file, even in the |
861 | | /// presence of pathological temporary file cleaners. |
862 | | /// |
863 | | /// # Examples |
864 | | /// |
865 | | /// ```no_run |
866 | | /// use tempfile::NamedTempFile; |
867 | | /// |
868 | | /// let file = NamedTempFile::new()?; |
869 | | /// |
870 | | /// let another_handle = file.reopen()?; |
871 | | /// # Ok::<(), std::io::Error>(()) |
872 | | /// ``` |
873 | 0 | pub fn reopen(&self) -> io::Result<File> { |
874 | 0 | imp::reopen(self.as_file(), NamedTempFile::path(self)) |
875 | 0 | .with_err_path(|| NamedTempFile::path(self)) |
876 | 0 | } |
877 | | } |
878 | | |
879 | | impl<F: Read> Read for NamedTempFile<F> { |
880 | 0 | fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
881 | 0 | self.as_file_mut().read(buf).with_err_path(|| self.path()) |
882 | 0 | } |
883 | | |
884 | 0 | fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> { |
885 | 0 | self.as_file_mut() |
886 | 0 | .read_vectored(bufs) |
887 | 0 | .with_err_path(|| self.path()) |
888 | 0 | } |
889 | | |
890 | 0 | fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { |
891 | 0 | self.as_file_mut() |
892 | 0 | .read_to_end(buf) |
893 | 0 | .with_err_path(|| self.path()) |
894 | 0 | } |
895 | | |
896 | 0 | fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { |
897 | 0 | self.as_file_mut() |
898 | 0 | .read_to_string(buf) |
899 | 0 | .with_err_path(|| self.path()) |
900 | 0 | } |
901 | | |
902 | 0 | fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { |
903 | 0 | self.as_file_mut() |
904 | 0 | .read_exact(buf) |
905 | 0 | .with_err_path(|| self.path()) |
906 | 0 | } |
907 | | } |
908 | | |
909 | | impl Read for &NamedTempFile<File> { |
910 | 0 | fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
911 | 0 | self.as_file().read(buf).with_err_path(|| self.path()) |
912 | 0 | } |
913 | | |
914 | 0 | fn read_vectored(&mut self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> { |
915 | 0 | self.as_file() |
916 | 0 | .read_vectored(bufs) |
917 | 0 | .with_err_path(|| self.path()) |
918 | 0 | } |
919 | | |
920 | 0 | fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { |
921 | 0 | self.as_file() |
922 | 0 | .read_to_end(buf) |
923 | 0 | .with_err_path(|| self.path()) |
924 | 0 | } |
925 | | |
926 | 0 | fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { |
927 | 0 | self.as_file() |
928 | 0 | .read_to_string(buf) |
929 | 0 | .with_err_path(|| self.path()) |
930 | 0 | } |
931 | | |
932 | 0 | fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { |
933 | 0 | self.as_file().read_exact(buf).with_err_path(|| self.path()) |
934 | 0 | } |
935 | | } |
936 | | |
937 | | impl<F: Write> Write for NamedTempFile<F> { |
938 | 0 | fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
939 | 0 | self.as_file_mut().write(buf).with_err_path(|| self.path()) |
940 | 0 | } |
941 | | #[inline] |
942 | 0 | fn flush(&mut self) -> io::Result<()> { |
943 | 0 | self.as_file_mut().flush().with_err_path(|| self.path()) |
944 | 0 | } |
945 | | |
946 | 0 | fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> { |
947 | 0 | self.as_file_mut() |
948 | 0 | .write_vectored(bufs) |
949 | 0 | .with_err_path(|| self.path()) |
950 | 0 | } |
951 | | |
952 | 0 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { |
953 | 0 | self.as_file_mut() |
954 | 0 | .write_all(buf) |
955 | 0 | .with_err_path(|| self.path()) Unexecuted instantiation: <tempfile::file::NamedTempFile as std::io::Write>::write_all::{closure#0}Unexecuted instantiation: <tempfile::file::NamedTempFile<_> as std::io::Write>::write_all::{closure#0} |
956 | 0 | } Unexecuted instantiation: <tempfile::file::NamedTempFile as std::io::Write>::write_all Unexecuted instantiation: <tempfile::file::NamedTempFile<_> as std::io::Write>::write_all |
957 | | |
958 | 0 | fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { |
959 | 0 | self.as_file_mut() |
960 | 0 | .write_fmt(fmt) |
961 | 0 | .with_err_path(|| self.path()) |
962 | 0 | } |
963 | | } |
964 | | |
965 | | impl Write for &NamedTempFile<File> { |
966 | 0 | fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
967 | 0 | self.as_file().write(buf).with_err_path(|| self.path()) |
968 | 0 | } |
969 | | #[inline] |
970 | 0 | fn flush(&mut self) -> io::Result<()> { |
971 | 0 | self.as_file().flush().with_err_path(|| self.path()) |
972 | 0 | } |
973 | | |
974 | 0 | fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> { |
975 | 0 | self.as_file() |
976 | 0 | .write_vectored(bufs) |
977 | 0 | .with_err_path(|| self.path()) |
978 | 0 | } |
979 | | |
980 | 0 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { |
981 | 0 | self.as_file().write_all(buf).with_err_path(|| self.path()) |
982 | 0 | } |
983 | | |
984 | 0 | fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { |
985 | 0 | self.as_file().write_fmt(fmt).with_err_path(|| self.path()) |
986 | 0 | } |
987 | | } |
988 | | |
989 | | impl<F: Seek> Seek for NamedTempFile<F> { |
990 | 0 | fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { |
991 | 0 | self.as_file_mut().seek(pos).with_err_path(|| self.path()) |
992 | 0 | } |
993 | | } |
994 | | |
995 | | impl Seek for &NamedTempFile<File> { |
996 | 0 | fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { |
997 | 0 | self.as_file().seek(pos).with_err_path(|| self.path()) |
998 | 0 | } |
999 | | } |
1000 | | |
1001 | | #[cfg(any(unix, target_os = "wasi"))] |
1002 | | impl<F: AsFd> AsFd for NamedTempFile<F> { |
1003 | 0 | fn as_fd(&self) -> BorrowedFd<'_> { |
1004 | 0 | self.as_file().as_fd() |
1005 | 0 | } |
1006 | | } |
1007 | | |
1008 | | #[cfg(any(unix, target_os = "wasi"))] |
1009 | | impl<F: AsRawFd> AsRawFd for NamedTempFile<F> { |
1010 | | #[inline] |
1011 | 0 | fn as_raw_fd(&self) -> RawFd { |
1012 | 0 | self.as_file().as_raw_fd() |
1013 | 0 | } |
1014 | | } |
1015 | | |
1016 | | #[cfg(windows)] |
1017 | | impl<F: AsHandle> AsHandle for NamedTempFile<F> { |
1018 | | #[inline] |
1019 | | fn as_handle(&self) -> BorrowedHandle<'_> { |
1020 | | self.as_file().as_handle() |
1021 | | } |
1022 | | } |
1023 | | |
1024 | | #[cfg(windows)] |
1025 | | impl<F: AsRawHandle> AsRawHandle for NamedTempFile<F> { |
1026 | | #[inline] |
1027 | | fn as_raw_handle(&self) -> RawHandle { |
1028 | | self.as_file().as_raw_handle() |
1029 | | } |
1030 | | } |
1031 | | |
1032 | 0 | pub(crate) fn create_named( |
1033 | 0 | path: PathBuf, |
1034 | 0 | open_options: &mut OpenOptions, |
1035 | 0 | permissions: Option<&std::fs::Permissions>, |
1036 | 0 | keep: bool, |
1037 | 0 | ) -> io::Result<NamedTempFile> { |
1038 | 0 | imp::create_named(&path, open_options, permissions) |
1039 | 0 | .with_err_path(|| path.clone()) |
1040 | 0 | .map(|file| NamedTempFile { |
1041 | 0 | path: TempPath { |
1042 | 0 | path: path.into_boxed_path(), |
1043 | 0 | keep, |
1044 | 0 | }, |
1045 | 0 | file, |
1046 | 0 | }) |
1047 | 0 | } |