Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Json db losing already saved pasta's on crash/power failure #281

Merged
merged 1 commit into from
Oct 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 13 additions & 25 deletions src/util/db_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,19 @@
}

fn save_to_file(pasta_data: &Vec<Pasta>) {
let mut file = File::create(DATABASE_PATH);
match file {
Ok(_) => {
let writer = BufWriter::new(file.unwrap());
serde_json::to_writer(writer, &pasta_data).expect("Failed to create JSON writer");
}
Err(_) => {
log::info!("Database file {} not found!", DATABASE_PATH);
file = File::create(DATABASE_PATH);
match file {
Ok(_) => {
log::info!("Database file {} created.", DATABASE_PATH);
save_to_file(pasta_data);
}
Err(err) => {
log::error!(
"Failed to create database file {}: {}!",
&DATABASE_PATH,
&err
);
panic!("Failed to create database file {}: {}!", DATABASE_PATH, err)
}
}
}
}
// This uses a two stage write. First we write to a new file, if this fails
// only the new pasta's are lost. Then we replace the current database with
// the new file. This either succeeds or fails. The database is never left
// in an undefined state.
let tmp_file_path = DATABASE_PATH.to_string() + ".tmp";
let tmp_file = File::create(&tmp_file_path).expect(&format!(
"failed to create temporary database file for writing. path: {tmp_file_path}"
));
Comment on lines +23 to +25

Check warning

Code scanning / clippy

use of expect followed by a function call Warning

use of expect followed by a function call

let writer = BufWriter::new(tmp_file);
serde_json::to_writer(writer, &pasta_data)
.expect("Should be able to write out data to database file");
std::fs::rename(tmp_file_path, DATABASE_PATH).expect("Could not update database");
}

fn load_from_file() -> io::Result<Vec<Pasta>> {
Expand Down
Loading