write_atomic 0.7.1

Write to files atomically.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*!
# Write Atomic

[![docs.rs](https://img.shields.io/docsrs/write_atomic.svg?style=flat-square&label=docs.rs)](https://docs.rs/write_atomic/)
[![changelog](https://img.shields.io/crates/v/write_atomic.svg?style=flat-square&label=changelog&color=9b59b6)](https://github.com/Blobfolio/write_atomic/blob/master/CHANGELOG.md)<br>
[![crates.io](https://img.shields.io/crates/v/write_atomic.svg?style=flat-square&label=crates.io)](https://crates.io/crates/write_atomic)
[![ci](https://img.shields.io/github/actions/workflow/status/Blobfolio/write_atomic/ci.yaml?style=flat-square&label=ci)](https://github.com/Blobfolio/write_atomic/actions)
[![deps.rs](https://deps.rs/crate/write_atomic/latest/status.svg?style=flat-square&label=deps.rs)](https://deps.rs/crate/write_atomic/)<br>
[![license](https://img.shields.io/badge/license-wtfpl-ff1493?style=flat-square)](https://en.wikipedia.org/wiki/WTFPL)
[![contributions welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square&label=contributions)](https://github.com/Blobfolio/write_atomic/issues)

Write Atomic was originally a stripped-down remake of [`tempfile-fast`](https://crates.io/crates/tempfile-fast), but with the `3.4.0` release of [`tempfile`](https://crates.io/crates/tempfile), it has largely been mooted.

(`tempfile` now supports Linux optimizations like `O_TMPFILE` natively.)

That said, one might still enjoy the ergonomic single-shot nature of Write Atomic's [`write_file`] and [`copy_file`] methods, as well as their permission/ownership-syncing behaviors, and so it lives on!

## Examples

```no_run
// One line is all it takes:
write_atomic::write_file("/path/to/my-file.txt", b"Some data!").unwrap();
```
*/

#![forbid(unsafe_code)]

#![deny(
	clippy::allow_attributes_without_reason,
	clippy::correctness,
	unreachable_pub,
)]

#![warn(
	clippy::complexity,
	clippy::nursery,
	clippy::pedantic,
	clippy::perf,
	clippy::style,

	clippy::allow_attributes,
	clippy::clone_on_ref_ptr,
	clippy::create_dir,
	clippy::filetype_is_file,
	clippy::format_push_string,
	clippy::get_unwrap,
	clippy::impl_trait_in_params,
	clippy::implicit_clone,
	clippy::lossy_float_literal,
	clippy::missing_assert_message,
	clippy::missing_docs_in_private_items,
	clippy::needless_raw_strings,
	clippy::panic_in_result_fn,
	clippy::pub_without_shorthand,
	clippy::rest_pat_in_fully_bound_structs,
	clippy::semicolon_inside_block,
	clippy::str_to_string,
	clippy::todo,
	clippy::undocumented_unsafe_blocks,
	clippy::unneeded_field_pattern,
	clippy::unseparated_literal_suffix,
	clippy::unwrap_in_result,

	macro_use_extern_crate,
	missing_copy_implementations,
	missing_docs,
	non_ascii_idents,
	trivial_casts,
	trivial_numeric_casts,
	unused_crate_dependencies,
	unused_extern_crates,
	unused_import_braces,
)]



use filetime::FileTime;
use std::{
	fs::{
		File,
		Metadata,
	},
	io::{
		Error,
		ErrorKind,
		Result,
		Write,
	},
	path::{
		Path,
		PathBuf,
	},
};
use tempfile::NamedTempFile;

#[cfg(unix)]
use std::os::unix::fs::MetadataExt;

// Re-export both dependencies.
pub use filetime;
pub use tempfile;



/// # Atomic File Copy!
///
/// Copy the contents — and permissions, ownership, and access/modification
/// times — of one file to another, atomically.
///
/// Similar to [`write_file`], this method first copies everything over to a
/// temporary file before moving it into place.
///
/// ## Examples
///
/// ```no_run
/// // It's just one line:
/// match write_atomic::copy_file("/some/source.jpg", "/some/copy.jpg") {
///     // The file was copied!
///     Ok(()) => {},
///
///     // There was an std::io::Error.
///     Err(e) => panic!("{e}"),
/// };
/// ```
///
/// ## Errors
///
/// This will bubble up any filesystem-related errors encountered along the
/// way.
pub fn copy_file<P>(src: P, dst: P) -> Result<()>
where P: AsRef<Path> {
	let src = src.as_ref();
	let (dst, parent) = check_path(dst)?;

	let file = tempfile::Builder::new().tempfile_in(parent)?;
	std::fs::copy(src, &file)?;
	let meta = std::fs::metadata(src)?;
	copy_metadata(&meta, file.as_file(), true)?;
	write_finish(file, &dst)
}

/// # Atomic File Write!
///
/// Write content to a file, atomically.
///
/// Under the hood, this method creates a temporary file to hold all the
/// changes, then moves that file into place once everything is good to go.
///
/// If a file already exists at the destination path, this method will (try
/// to) preserve its permissions and ownership.
///
/// If not, it will simply create it.
///
/// Unlike [`File::create`](std::fs::File::create), this method will also
/// attempt to create any missing parent directories.
///
/// ## Examples
///
/// ```no_run
/// // It's just one line:
/// match write_atomic::write_file("/path/to/my/file.txt", b"Some data!") {
///     // The file was saved!
///     Ok(()) => {},
///
///     // There was an std::io::Error.
///     Err(e) => panic!("{e}"),
/// };
/// ```
///
/// ## Errors
///
/// This will bubble up any filesystem-related errors encountered along the
/// way.
pub fn write_file<P>(dst: P, data: &[u8]) -> Result<()>
where P: AsRef<Path> {
	let (dst, parent) = check_path(dst)?;

	let mut file = tempfile::Builder::new().tempfile_in(parent)?;
	file.write_all(data)?;
	file.flush()?;

	try_copy_metadata(&dst, file.as_file())?;
	write_finish(file, &dst)
}



/// # Handle Path.
///
/// This checks the path and returns it and its parent, assuming it is valid,
/// or an error if not.
fn check_path<P>(src: P) -> Result<(PathBuf, PathBuf)>
where P: AsRef<Path> {
	// Normalize the formatting.
	let src = std::path::absolute(src)?;

	// The path cannot be a directory.
	if src.is_dir() {
		return Err(Error::new(ErrorKind::InvalidInput, "Path cannot be a directory."));
	}

	// The path must have a parent.
	let parent = src.parent()
		.ok_or_else(|| Error::new(ErrorKind::NotFound, "Path must have a parent directory."))?;

	// Create the parent if it doesn't already exist.
	std::fs::create_dir_all(parent)?;

	// It has to be owned for return purposes.
	let parent = parent.to_path_buf();

	// We're good to go!
	Ok((src, parent))
}

/// # Copy Metadata.
///
/// Make sure we don't lose details like permissions, ownership, etc., when
/// replacing an existing file.
fn copy_metadata(src: &Metadata, dst: &File, times: bool) -> Result<()> {
	// Copy permissions.
	dst.set_permissions(src.permissions())?;

	#[cfg(unix)]
	// Copy ownership.
	std::os::unix::fs::fchown(dst, Some(src.uid()), Some(src.gid()))?;

	// Copy file times too?
	if times {
		let atime = FileTime::from_last_access_time(src);
		let mtime = FileTime::from_last_modification_time(src);
		let _res = filetime::set_file_handle_times(dst, Some(atime), Some(mtime));
	}

	Ok(())
}

/// # Try Copy Metadata.
///
/// For `write_file` operations, there isn't necessarily an existing file to
/// copy permissions from.
///
/// This method will (temporarily) create one if missing so that the default
/// file permissions can at least be synced.
fn try_copy_metadata(src: &Path, dst: &File) -> Result<()> {
	match std::fs::metadata(src) {
		// We have a source! Copy the metadata as normal!
		Ok(meta) => copy_metadata(&meta, dst, false),

		// The file doesn't exist; let's (briefly) create it and sync the
		// permissions.
		Err(ref e) if ErrorKind::NotFound == e.kind() => {
			let mut res = Ok(());

			// Try to create it.
			if File::create(src).is_ok() {
				// Grab the permissions.
				if let Ok(perms) = std::fs::metadata(src).map(|m| m.permissions()) {
					res = dst.set_permissions(perms);
				}

				// Clean up.
				let _res = std::fs::remove_file(src);
			}

			res
		},

		// All other errors bubble.
		Err(e) => Err(e),
	}
}

/// # Finish Write.
///
/// Persist the temporary file.
fn write_finish(file: NamedTempFile, dst: &Path) -> Result<()> {
	file.persist(dst).map(|_| ()).map_err(|e| e.error)
}



#[cfg(test)]
mod tests {
	use super::*;

	#[cfg(unix)]
	/// # Get User/Group IDs.
	fn user_group(meta: &Metadata) -> (u32, u32) {
		use std::os::unix::fs::MetadataExt;
		(meta.uid(), meta.gid())
	}

	#[test]
	fn test_file_times() {
		let mut dst = std::env::temp_dir();
		if ! dst.is_dir() { return; }
		dst.push("LICENSE-copy.txt");

		// Pull the source's details.
		let src = std::fs::canonicalize("./LICENSE")
			.expect("Missing LICENSE file?");
		let meta1 = std::fs::metadata(&src)
			.expect("Unable to read LICENSE metadata.");

		// Copy it and pull the destination's details.
		assert!(copy_file(&src, &dst).is_ok());
		let meta2 = std::fs::metadata(&dst)
			.expect("Unable to read LICENSE-copy.txt metadata.");

		// Check sameness!
		assert_eq!(
			meta1.permissions(),
			meta2.permissions(),
			"Copied permissions not equal.",
		);

		#[cfg(unix)]
		assert_eq!(
			user_group(&meta1),
			user_group(&meta2),
			"Copied ownership not equal.",
		);

		assert_eq!(
			FileTime::from_last_modification_time(&meta1),
			FileTime::from_last_modification_time(&meta2),
			"Copied mtimes not equal.",
		);

		// Let's rewrite to the same destination and re-verify the
		// details. (`write_file` only syncs permissions if overwriting.)
		write_file(&dst, b"Testing a rewrite!").expect("Write failed.");
		let meta2 = std::fs::metadata(&dst)
			.expect("Unable to read LICENSE-copy.txt metadata.");

		// Make sure we're reading something new. Haha.
		assert_eq!(meta2.len(), 18, "Unexpected file length.");

		// Check sameness!
		assert_eq!(
			meta1.permissions(),
			meta2.permissions(),
			"Copied permissions not equal.",
		);

		#[cfg(unix)]
		assert_eq!(
			user_group(&meta1),
			user_group(&meta2),
			"Copied ownership not equal.",
		);

		// This time around the times should be different!
		assert_ne!(
			FileTime::from_last_modification_time(&meta1),
			FileTime::from_last_modification_time(&meta2),
			"Mtimes shouldn't match anymore!",
		);

		// Remove the copy.
		let _res = std::fs::remove_file(dst);
	}

	#[test]
	fn test_write() {
		// Hopefully sandboxes running this test can write to their own
		// temporary directory!
		let mut path = std::env::temp_dir();
		if ! path.is_dir() { return; }
		path.push("write-atomic-test.txt");

		// Now that we have a path, let's try to write to it!
		assert!(write_file(&path, b"This is the first write!").is_ok());

		// Make sure the content is written correctly.
		assert_eq!(
			std::fs::read(&path).expect("Unable to open file."),
			b"This is the first write!",
		);

		// One more time with different content.
		assert!(write_file(&path, b"This is the second write!").is_ok());

		// Make sure the content is written correctly.
		assert_eq!(
			std::fs::read(&path).expect("Unable to open file."),
			b"This is the second write!",
		);

		// Test copy!
		let path2 = path.parent()
			.expect("Missing parent?!")
			.join("copy-atomic-test.txt");
		assert!(copy_file(&path, &path2).is_ok());
		assert_eq!(
			std::fs::read(&path2).expect("Unable to open file."),
			b"This is the second write!",
		);

		// Let's clean up after ourselves.
		let _res = std::fs::remove_file(path);
		let _res = std::fs::remove_file(path2);
	}
}