Add collaborative authored-file safety
This commit is contained in:
1 parent
b4aa61e394
commit
5a82a9ee29
23 files changed
+2857
-89
No files matched your search
@@ -13,17 +13,20 @@ pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||
atomic_write_with_pre_rename(path, bytes, || Ok(()))
|
||||
}
|
||||
|
||||
fn atomic_write_with_pre_rename(
|
||||
pub(crate) fn atomic_write_with_pre_rename<E>(
|
||||
path: &Path,
|
||||
bytes: &[u8],
|
||||
before_rename: impl FnOnce() -> Result<(), String>,
|
||||
) -> Result<(), String> {
|
||||
before_rename: impl FnOnce() -> Result<(), E>,
|
||||
) -> Result<(), E>
|
||||
where
|
||||
E: From<String>,
|
||||
{
|
||||
let parent = path
|
||||
.parent()
|
||||
.filter(|parent| !parent.as_os_str().is_empty())
|
||||
.unwrap_or_else(|| Path::new("."));
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
|
||||
.map_err(|error| E::from(format!("could not create {}: {error}", parent.display())))?;
|
||||
|
||||
let file_name = path
|
||||
.file_name()
|
||||
@@ -40,18 +43,21 @@ fn atomic_write_with_pre_rename(
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(&temporary)
|
||||
.map_err(|error| format!("could not create {}: {error}", temporary.display()))?;
|
||||
file.write_all(bytes)
|
||||
.map_err(|error| format!("could not write {}: {error}", temporary.display()))?;
|
||||
.map_err(|error| {
|
||||
E::from(format!("could not create {}: {error}", temporary.display()))
|
||||
})?;
|
||||
file.write_all(bytes).map_err(|error| {
|
||||
E::from(format!("could not write {}: {error}", temporary.display()))
|
||||
})?;
|
||||
file.sync_all()
|
||||
.map_err(|error| format!("could not sync {}: {error}", temporary.display()))?;
|
||||
.map_err(|error| E::from(format!("could not sync {}: {error}", temporary.display())))?;
|
||||
before_rename()?;
|
||||
fs::rename(&temporary, path).map_err(|error| {
|
||||
format!(
|
||||
E::from(format!(
|
||||
"could not replace {} with {}: {error}",
|
||||
path.display(),
|
||||
temporary.display()
|
||||
)
|
||||
))
|
||||
})?;
|
||||
sync_parent_directory(parent);
|
||||
Ok(())
|
||||
|
||||
Reference in new issue
Block a user