diff --git a/src/main.rs b/src/main.rs index 1898e90..0aef676 100644 --- a/src/main.rs +++ b/src/main.rs @@ -66,6 +66,7 @@ fn commands_backup(cli: &Cli, _args: &BackupArgs) -> io::Result<()> { cli.chain_len, cli.chains, ); + manager.load()?; manager.create_backup()?; manager.remove_old_backups() diff --git a/src/server/backups.rs b/src/server/backups.rs index c8f235a..5097746 100644 --- a/src/server/backups.rs +++ b/src/server/backups.rs @@ -250,19 +250,7 @@ impl BackupManager { } } - pub fn open( - backup_dir: PathBuf, - config_dir: PathBuf, - world_dir: PathBuf, - chain_len: u64, - chains_to_keep: u64, - ) -> std::io::Result { - let mut manager = Self::new(backup_dir, config_dir, world_dir, chain_len, chains_to_keep); - manager.load_json()?; - - Ok(manager) - } - + /// Create a new backup with the expected type. pub fn create_backup(&mut self) -> io::Result<()> { let dirs = vec![ (PathBuf::from("config"), self.config_dir.clone()), @@ -296,12 +284,12 @@ impl BackupManager { // The above statement always creates this element, so this unwrap is safe self.chains.last_mut().unwrap().push(backup); - self.write_json()?; + self.save()?; Ok(()) } - /// Remove the oldest backups + /// Delete all backups associated with outdated chains, and forget those chains. pub fn remove_old_backups(&mut self) -> std::io::Result<()> { let chains_to_store: usize = self.chains_to_keep.try_into().unwrap(); @@ -322,24 +310,28 @@ impl BackupManager { } } - self.write_json()?; + self.save()?; Ok(()) } - pub fn write_json(&self) -> std::io::Result<()> { + /// Write the in-memory state to disk. + pub fn save(&self) -> std::io::Result<()> { let json_file = File::create(self.backup_dir.join(Self::METADATA_FILE))?; serde_json::to_writer(json_file, &self.chains)?; Ok(()) } - pub fn load_json(&mut self) -> std::io::Result<()> { + /// Overwrite the in-memory state with the on-disk state. + pub fn load(&mut self) -> std::io::Result<()> { let json_file = match File::open(self.backup_dir.join(Self::METADATA_FILE)) { Ok(f) => f, Err(e) => { // Don't error out if the file isn't there, it will be created when necessary if e.kind() == io::ErrorKind::NotFound { + self.chains = Vec::new(); + return Ok(()); } else { return Err(e); diff --git a/src/server/command.rs b/src/server/command.rs index fa92804..bd1f0e6 100644 --- a/src/server/command.rs +++ b/src/server/command.rs @@ -186,13 +186,15 @@ impl ServerCommand { } pub fn spawn(&mut self) -> std::io::Result { - let manager = BackupManager::open( + let mut manager = BackupManager::new( self.backup_dir.clone(), self.config_dir.clone(), self.world_dir.clone(), self.chain_len, self.chains_to_keep, - )?; + ); + manager.load()?; + let mut cmd = self.create_cmd(); self.accept_eula()?; let child = cmd.spawn()?;