diff --git a/README.md b/README.md index 978d3bb..9639c40 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,9 @@ This is still in very early development, so expect old maps to no longer work. ### Core - [x] Mapping - - [x] Record the state of disc regions + - [x] Record the state of disc regions. - [x] Recover from saved map. + - [x] Backup old map before truncating for new. - [ ] Recovery - [x] Initial Technically there is an outstanding issue with sleepy firmware here, diff --git a/src/io.rs b/src/io.rs index 5713256..2a17623 100644 --- a/src/io.rs +++ b/src/io.rs @@ -1,7 +1,7 @@ use std::fs::{File, OpenOptions}; use std::io::{self, Seek, SeekFrom}; -use std::ops::{Index, Range, RangeFrom}; -use std::slice::SliceIndex; +use std::ops::Index; +use std::path::Path; use crate::cli::CONFIG; @@ -66,10 +66,21 @@ pub fn load_map_read() -> std::io::Result { } pub fn load_map_write() -> anyhow::Result { + // Attempt to check if a map exists on the disk. + // If so, make a backup of it. + // + // This should be recoverable by just skipping over this error and logging a warning, + // but for now it will be an error condition. + if std::fs::exists(crate::path::MAP_PATH.clone()) + .context("Could not check if map exists in fs to make a backup.")? + { + backup(crate::path::MAP_PATH.clone())?; + } + OpenOptions::new() .write(true) .create(true) - .truncate(true) // Wipe old map. Should really make a backup first. + .truncate(true) // Wipe old map, in case we skip over backing up the old one. .open(crate::path::MAP_PATH.clone()) .with_context(|| { format!( @@ -79,6 +90,13 @@ pub fn load_map_write() -> anyhow::Result { }) } +fn backup>(path: P) -> std::io::Result<()> { + std::fs::rename( + &path, + format!("{}.bak", path.as_ref().to_path_buf().display()), + ) +} + #[repr(C, align(512))] pub struct DirectIOBuffer(pub [u8; crate::MAX_BUFFER_SIZE]);