1use std::fs::{File, OpenOptions};
11use std::io::Write;
12use std::path::{Path, PathBuf};
13
14use rand::TryRng;
15use rand::rngs::SysRng;
16use snafu::Snafu;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum NewFileMode {
22 Default,
24 Exactly(u32),
28 KeepExisting,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum ReplaceStep {
36 Create,
38 SetPermissions,
40 Write,
42 Replace,
44 SyncParent,
46}
47
48impl ReplaceStep {
49 fn verb(self) -> &'static str {
50 match self {
51 Self::Create => "create",
52 Self::SetPermissions => "set the permissions of",
53 Self::Write => "write",
54 Self::Replace => "replace",
55 Self::SyncParent => "sync the directory of",
56 }
57 }
58}
59
60#[derive(Debug, Snafu)]
62#[snafu(display("failed to {} `{}`", step.verb(), path.display()))]
63pub struct ReplaceError {
64 pub step: ReplaceStep,
65 pub path: PathBuf,
70 source: std::io::Error,
71}
72
73impl ReplaceError {
74 pub fn io(&self) -> &std::io::Error {
76 &self.source
77 }
78}
79
80impl From<ReplaceError> for std::io::Error {
81 fn from(error: ReplaceError) -> Self {
83 error.source
84 }
85}
86
87pub fn replace_contents(path: &Path, bytes: &[u8], mode: NewFileMode) -> Result<(), ReplaceError> {
104 let Some(file_name) = path.file_name() else {
105 return Err(ReplaceError {
106 step: ReplaceStep::Create,
107 path: path.to_path_buf(),
108 source: std::io::Error::new(std::io::ErrorKind::InvalidInput, "no file name"),
109 });
110 };
111 let suffix = SysRng.try_next_u64().map_err(|error| ReplaceError {
114 step: ReplaceStep::Create,
115 path: path.to_path_buf(),
116 source: std::io::Error::other(error),
117 })?;
118 let temporary = path.with_file_name(format!(
119 ".{}.tmp-{}-{suffix:016x}",
120 file_name.to_string_lossy(),
121 std::process::id()
122 ));
123 let mut options = OpenOptions::new();
124 options.write(true).create_new(true);
125 create_with_mode(&mut options, mode);
126 let file = options.open(&temporary).map_err(|source| ReplaceError {
127 step: ReplaceStep::Create,
128 path: temporary.clone(),
129 source,
130 })?;
131 let result = write_and_replace(file, &temporary, path, bytes, mode);
132 if result.is_err() {
133 let _ = std::fs::remove_file(&temporary);
136 }
137 result
138}
139
140fn write_and_replace(
141 mut file: File,
142 temporary: &Path,
143 path: &Path,
144 bytes: &[u8],
145 mode: NewFileMode,
146) -> Result<(), ReplaceError> {
147 let failed = |step, at: &Path| {
148 let path = at.to_path_buf();
149 move |source| ReplaceError { step, path, source }
150 };
151 set_mode(&file, path, mode).map_err(failed(ReplaceStep::SetPermissions, temporary))?;
152 file.write_all(bytes)
153 .and_then(|()| file.sync_all())
154 .map_err(failed(ReplaceStep::Write, temporary))?;
155 drop(file);
156 replace_file(temporary, path).map_err(failed(ReplaceStep::Replace, path))?;
157 sync_parent_directory(path).map_err(failed(ReplaceStep::SyncParent, path))
158}
159
160#[cfg(unix)]
161fn create_with_mode(options: &mut OpenOptions, mode: NewFileMode) {
162 use std::os::unix::fs::OpenOptionsExt;
163 if let NewFileMode::Exactly(mode) = mode {
164 options.mode(mode);
165 }
166}
167
168#[cfg(not(unix))]
169fn create_with_mode(_: &mut OpenOptions, _: NewFileMode) {}
170
171#[cfg(unix)]
172fn set_mode(file: &File, target: &Path, mode: NewFileMode) -> std::io::Result<()> {
173 use std::os::unix::fs::PermissionsExt;
174 let permissions = match mode {
175 NewFileMode::Default => return Ok(()),
176 NewFileMode::Exactly(mode) => std::fs::Permissions::from_mode(mode),
177 NewFileMode::KeepExisting => match std::fs::metadata(target) {
178 Ok(metadata) => metadata.permissions(),
179 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
180 Err(error) => return Err(error),
181 },
182 };
183 file.set_permissions(permissions)
184}
185
186#[cfg(not(unix))]
187fn set_mode(_: &File, _: &Path, _: NewFileMode) -> std::io::Result<()> {
188 Ok(())
189}
190
191pub fn replace_file(from: &Path, to: &Path) -> std::io::Result<()> {
204 std::fs::rename(from, to)
205}
206
207pub fn sync_parent_directory(path: &Path) -> std::io::Result<()> {
213 let Some(parent) = path.parent() else {
214 return Ok(());
215 };
216 sync_directory(parent)
217}
218
219fn sync_directory(directory: &Path) -> std::io::Result<()> {
220 open_directory_for_sync(directory).and_then(|directory| directory.sync_all())
221}
222
223fn open_directory_for_sync(path: &Path) -> std::io::Result<File> {
224 #[cfg(windows)]
225 {
226 use std::os::windows::fs::OpenOptionsExt;
227 const GENERIC_READ: u32 = 0x8000_0000;
228 const GENERIC_WRITE: u32 = 0x4000_0000;
229 const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
230 OpenOptions::new()
231 .access_mode(GENERIC_READ | GENERIC_WRITE)
232 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
233 .open(path)
234 }
235 #[cfg(not(windows))]
236 File::open(path)
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242 use crate::test_support::TempPath;
243
244 fn scratch(label: &str) -> TempPath {
246 let directory = TempPath::new(label);
247 std::fs::create_dir(&directory).unwrap();
248 directory
249 }
250
251 fn entries(directory: &Path) -> Vec<std::ffi::OsString> {
253 let mut names = std::fs::read_dir(directory)
254 .unwrap()
255 .map(|entry| entry.unwrap().file_name())
256 .collect::<Vec<_>>();
257 names.sort();
258 names
259 }
260
261 #[test]
262 fn replace_contents_creates_then_replaces_and_leaves_only_the_target() {
263 let scratch = scratch("replace");
264 let path = scratch.join("state.json");
265
266 replace_contents(&path, b"first", NewFileMode::Default).unwrap();
267 assert_eq!(std::fs::read(&path).unwrap(), b"first");
268 replace_contents(&path, b"second", NewFileMode::KeepExisting).unwrap();
269 assert_eq!(std::fs::read(&path).unwrap(), b"second");
270 assert_eq!(entries(&scratch), ["state.json"]);
271 }
272
273 #[test]
276 fn a_failed_replace_reports_its_step_and_removes_the_temporary() {
277 let scratch = scratch("replace-fails");
278 let path = scratch.join("occupied");
279 std::fs::create_dir(&path).unwrap();
280 std::fs::write(path.join("kept"), b"kept").unwrap();
281
282 let error = replace_contents(&path, b"new", NewFileMode::Default).unwrap_err();
283 assert_eq!(error.step, ReplaceStep::Replace);
284 assert_eq!(error.path, path);
285 assert_eq!(entries(&scratch), ["occupied"]);
286 assert_eq!(std::fs::read(path.join("kept")).unwrap(), b"kept");
287 }
288
289 #[test]
292 fn sync_parent_directory_succeeds_for_a_local_file() {
293 let scratch = scratch("dirsync");
294 let path = scratch.join("probe");
295 std::fs::write(&path, b"x").unwrap();
296 sync_parent_directory(&path).unwrap();
297 }
298
299 #[cfg(unix)]
300 #[test]
301 fn replace_contents_sets_the_requested_mode() {
302 use std::os::unix::fs::PermissionsExt;
303 let scratch = scratch("replace-mode");
304 let path = scratch.join("secret");
305 let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777;
306
307 replace_contents(&path, b"key", NewFileMode::Exactly(0o600)).unwrap();
308 assert_eq!(mode(&path), 0o600);
309 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap();
310 replace_contents(&path, b"key", NewFileMode::KeepExisting).unwrap();
311 assert_eq!(mode(&path), 0o640);
312 }
313}