0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-03-03 09:31:22 -05:00

fix: atomically write files to $DENO_DIR (#8822)

This commit is contained in:
Luca Casonato 2020-12-18 19:30:49 +01:00 committed by GitHub
parent 37fd0836d0
commit b9165e9482
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 19 additions and 3 deletions

View file

@ -139,7 +139,7 @@ impl DiskCache {
Some(ref parent) => self.ensure_dir_exists(parent),
None => Ok(()),
}?;
fs_util::write_file(&path, data, crate::http_cache::CACHE_PERM)
fs_util::atomic_write_file(&path, data, crate::http_cache::CACHE_PERM)
.map_err(|e| with_io_context(&e, format!("{:#?}", &path)))
}
}

View file

@ -2,12 +2,28 @@
use deno_core::error::AnyError;
pub use deno_core::normalize_path;
use deno_runtime::deno_crypto::rand;
use std::env::current_dir;
use std::fs::OpenOptions;
use std::io::{Error, Write};
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
pub fn atomic_write_file<T: AsRef<[u8]>>(
filename: &Path,
data: T,
mode: u32,
) -> std::io::Result<()> {
let rand: String = (0..4)
.map(|_| format!("{:02x}", rand::random::<u8>()))
.collect();
let extension = format!("{}.tmp", rand);
let tmp_file = filename.with_extension(extension);
write_file(&tmp_file, data, mode)?;
std::fs::rename(tmp_file, filename)?;
Ok(())
}
pub fn write_file<T: AsRef<[u8]>>(
filename: &Path,
data: T,

View file

@ -87,7 +87,7 @@ impl Metadata {
pub fn write(&self, cache_filename: &Path) -> Result<(), AnyError> {
let metadata_filename = Self::filename(cache_filename);
let json = serde_json::to_string_pretty(self)?;
fs_util::write_file(&metadata_filename, json, CACHE_PERM)?;
fs_util::atomic_write_file(&metadata_filename, json, CACHE_PERM)?;
Ok(())
}
@ -161,7 +161,7 @@ impl HttpCache {
.expect("Cache filename should have a parent dir");
self.ensure_dir_exists(parent_filename)?;
// Cache content
fs_util::write_file(&cache_filename, content, CACHE_PERM)?;
fs_util::atomic_write_file(&cache_filename, content, CACHE_PERM)?;
let metadata = Metadata {
url: url.to_string(),