Skip to content

Commit

Permalink
Use atomicwrites to save data file safely
Browse files Browse the repository at this point in the history
  • Loading branch information
iovxw committed Jul 31, 2021
1 parent 36f77b5 commit b7d8d0d
Show file tree
Hide file tree
Showing 3 changed files with 130 additions and 8 deletions.
119 changes: 119 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ quick-xml = { version = "0.22", features = ["encoding"] }
chrono = "0.4"
pinyin = "0.8"
either = "1.6"
atomicwrites = "0.3"

[dependencies.tbot]
version = "0.6"
Expand Down
18 changes: 10 additions & 8 deletions src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::hash::{BuildHasherDefault, Hash, Hasher};
use std::path::PathBuf;
use std::time::{Duration, SystemTime};

use atomicwrites::{AtomicFile, OverwriteBehavior};
use serde::{Deserialize, Serialize};
use serde_json;
use thiserror::Error;
Expand Down Expand Up @@ -273,14 +274,15 @@ impl Database {

pub fn save(&self) -> Result<(), DataError> {
let feeds_list: Vec<&Feed> = self.feeds.iter().map(|(_id, feed)| feed).collect();
let mut file = File::create(&self.path)?;
if let Err(e) = serde_json::to_writer(&mut file, &feeds_list) {
if e.is_io() {
return Err(DataError::Io(e.into()));
} else {
unreachable!(e);
};
}
let file = AtomicFile::new(&self.path, OverwriteBehavior::AllowOverwrite);
file.write(|file| serde_json::to_writer(file, &feeds_list))
.map_err(|e| match e {
atomicwrites::Error::Internal(e) => DataError::Io(e),
atomicwrites::Error::User(e) => {
assert!(!e.is_io(), "unreachable code");
DataError::Io(e.into())
}
})?;
Ok(())
}
}
Expand Down

0 comments on commit b7d8d0d

Please sign in to comment.