async_tempfile/builder.rs
1use crate::tempdir::DIR_PREFIX;
2use crate::tempfile::FILE_PREFIX;
3use crate::{Error, TempDir, TempFile};
4use std::path::PathBuf;
5
6/// A builder for configuring and creating a [`TempFile`].
7///
8/// Obtain one via [`TempFile::builder`]. The file name is composed as
9/// `{prefix}{random}{suffix}`, where the random core is unpredictable and
10/// collision-resistant, and the file is created with an exclusive
11/// (`O_EXCL`) create so it never clobbers an existing file.
12///
13/// ## Example
14///
15/// ```
16/// # use async_tempfile::{TempFile, Error};
17/// # let _ = tokio_test::block_on(async {
18/// let file = TempFile::builder()
19/// .prefix("session_")
20/// .suffix(".tmp")
21/// .dir(std::env::temp_dir())
22/// .create()
23/// .await?;
24///
25/// let name = file.file_path().file_name().unwrap().to_string_lossy().into_owned();
26/// assert!(name.starts_with("session_"));
27/// assert!(name.ends_with(".tmp"));
28/// # Ok::<(), Error>(())
29/// # });
30/// ```
31#[derive(Debug, Clone)]
32pub struct TempFileBuilder {
33 dir: Option<PathBuf>,
34 prefix: String,
35 suffix: String,
36}
37
38impl TempFileBuilder {
39 pub(crate) fn new() -> Self {
40 Self {
41 dir: None,
42 prefix: FILE_PREFIX.to_string(),
43 suffix: String::new(),
44 }
45 }
46
47 /// Sets the file name prefix. Defaults to `atmp_`.
48 pub fn prefix<S: Into<String>>(mut self, prefix: S) -> Self {
49 self.prefix = prefix.into();
50 self
51 }
52
53 /// Sets the file name suffix (for example a file extension). Defaults to empty.
54 pub fn suffix<S: Into<String>>(mut self, suffix: S) -> Self {
55 self.suffix = suffix.into();
56 self
57 }
58
59 /// Sets the directory to create the file in. Defaults to the system
60 /// temporary directory ([`std::env::temp_dir`]).
61 pub fn dir<P: Into<PathBuf>>(mut self, dir: P) -> Self {
62 self.dir = Some(dir.into());
63 self
64 }
65
66 /// Creates the temporary file with the configured options.
67 pub async fn create(self) -> Result<TempFile, Error> {
68 let dir = self.dir.unwrap_or_else(std::env::temp_dir);
69 TempFile::create_with_affixes(&dir, &self.prefix, &self.suffix).await
70 }
71}
72
73/// A builder for configuring and creating a [`TempDir`].
74///
75/// Obtain one via [`TempDir::builder`]. The directory name is composed as
76/// `{prefix}{random}{suffix}` with an unpredictable, collision-resistant random
77/// core, created with an exclusive create.
78///
79/// ## Example
80///
81/// ```
82/// # use async_tempfile::{TempDir, Error};
83/// # let _ = tokio_test::block_on(async {
84/// let dir = TempDir::builder()
85/// .prefix("workspace_")
86/// .create()
87/// .await?;
88///
89/// let name = dir.dir_path().file_name().unwrap().to_string_lossy().into_owned();
90/// assert!(name.starts_with("workspace_"));
91/// # Ok::<(), Error>(())
92/// # });
93/// ```
94#[derive(Debug, Clone)]
95pub struct TempDirBuilder {
96 root: Option<PathBuf>,
97 prefix: String,
98 suffix: String,
99}
100
101impl TempDirBuilder {
102 pub(crate) fn new() -> Self {
103 Self {
104 root: None,
105 prefix: DIR_PREFIX.to_string(),
106 suffix: String::new(),
107 }
108 }
109
110 /// Sets the directory name prefix. Defaults to `atmpd_`.
111 pub fn prefix<S: Into<String>>(mut self, prefix: S) -> Self {
112 self.prefix = prefix.into();
113 self
114 }
115
116 /// Sets the directory name suffix. Defaults to empty.
117 pub fn suffix<S: Into<String>>(mut self, suffix: S) -> Self {
118 self.suffix = suffix.into();
119 self
120 }
121
122 /// Sets the root directory to create the directory in. Defaults to the
123 /// system temporary directory ([`std::env::temp_dir`]).
124 pub fn dir<P: Into<PathBuf>>(mut self, root: P) -> Self {
125 self.root = Some(root.into());
126 self
127 }
128
129 /// Creates the temporary directory with the configured options.
130 pub async fn create(self) -> Result<TempDir, Error> {
131 let root = self.root.unwrap_or_else(std::env::temp_dir);
132 TempDir::create_with_affixes(&root, &self.prefix, &self.suffix).await
133 }
134}