From 695556c3441f5ffd40c35387a5b45e4459684c2c Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Fri, 6 Sep 2024 17:12:52 +0200 Subject: add get specific or last backup --- src/backup.rs | 38 ++++++++++++++++++++++++++++---------- src/error.rs | 3 +++ src/main.rs | 8 +++++--- 3 files changed, 36 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/backup.rs b/src/backup.rs index 69bc2ea..8cc94f1 100644 --- a/src/backup.rs +++ b/src/backup.rs @@ -1,6 +1,6 @@ use std::{ - fs::{create_dir_all, File, OpenOptions}, - io::{ErrorKind, Read, Write}, + fs::{create_dir_all, File}, + io::{Read, Write}, path::PathBuf, time::{SystemTime, UNIX_EPOCH}, }; @@ -43,7 +43,7 @@ impl Backup { pub fn save(&self, config: &Config) -> Result<()> { let rel_location = format!( - "bu_{}_{}", + "{}_{}", gethostname() .into_string() .map_err(|_| Error::InvalidOsString)?, @@ -66,17 +66,35 @@ impl Backup { Ok(()) } - pub fn get(config: &Config, _id: Option) -> Result<()> { + pub fn get_index(config: &Config, id: Option) -> Result { let backup_index_root = format!("{}/index.json", config.root); - let mut file = File::open(backup_index_root)?; - let mut content = String::new(); - file.read_to_string(&mut content)?; - let list: Vec = serde_json::from_str(&content)?; + let list: Vec = Self::get_json_content(&backup_index_root)?; println!("{list:#?}"); - todo!(); + let index_loc = if let Some(id) = id { + list.iter() + .find(|bl| bl.id == id) + .ok_or(Error::BackupNotFound)? + .rel_location + .clone() + } else { + list.last() + .ok_or(Error::BackupNotFound)? + .rel_location + .clone() + }; - Ok(()) + let path = format!("{}/{index_loc}/index.json", config.root); + let index_file: Self = Self::get_json_content(&path)?; + + Ok(index_file) + } + + fn get_json_content Deserialize<'a>>(path: &str) -> Result { + let mut file = File::open(path)?; + let mut content = String::new(); + file.read_to_string(&mut content)?; + Ok(serde_json::from_str(&content)?) } fn append_to_root_index(config: &Config, new_backup: BackupLocation) -> Result<()> { diff --git a/src/error.rs b/src/error.rs index dc132f4..6afa3d0 100644 --- a/src/error.rs +++ b/src/error.rs @@ -20,6 +20,9 @@ pub enum Error { #[error("OsString couldn't be converted to string")] InvalidOsString, + #[error("Requested backup not found")] + BackupNotFound, + #[error("json: {source}")] SerdeJson { #[from] diff --git a/src/main.rs b/src/main.rs index e0b3758..d5ccb75 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,11 +21,13 @@ fn main() -> color_eyre::Result<()> { let pkgs = pacman.get_installed(); let backup = Backup::create(&cfg, pkgs)?; - // println!("{backup:#?}"); + println!("{backup:#?}"); - backup.save(&cfg)?; + // backup.save(&cfg)?; - Backup::get(&cfg, None)?; + let index = Backup::get_index(&cfg, None)?; + + println!("{index:#?}"); // let fi = FileInfo::new("~/.config/nvim", &cfg)?; // println!("{:?}", fi.get_absolute_path()); -- cgit v1.2.3