From 97896023cf5b8ac9a58baaba7d0571b0cc9ff8f7 Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Sun, 8 Sep 2024 23:59:39 +0200 Subject: add logging --- src/backup.rs | 28 ++++++++++++++-------------- src/config.rs | 7 ++++++- src/main.rs | 47 +++++++++++++++++++++++++++++------------------ src/packages.rs | 2 +- src/packages/pacman.rs | 18 ++++++++++++++---- src/packages/portage.rs | 5 ++++- src/pathinfo.rs | 32 ++++++++++++-------------------- 7 files changed, 80 insertions(+), 59 deletions(-) (limited to 'src') diff --git a/src/backup.rs b/src/backup.rs index 675f020..e463593 100644 --- a/src/backup.rs +++ b/src/backup.rs @@ -6,6 +6,7 @@ use std::{ }; use serde::{Deserialize, Serialize}; +use tracing::info; use uuid::Uuid; use crate::{ @@ -15,7 +16,7 @@ use crate::{ pathinfo::PathInfo, }; -pub type BackupId = String; +pub type Id = String; #[derive(Debug, Serialize, Deserialize)] pub struct Backup { @@ -43,13 +44,12 @@ impl Backup { } pub fn save(&self, config: &Config) -> Result<()> { - println!("Save Backup {:?}", self.get_location(config)); - // println!("{self:#?}"); + info!("Save Backup {:?}", self.get_location(config)); self.get_location(config).append_to_root(config)?; let backup_root = self.get_location(config).get_absolute_dir(config); create_dir_all(&backup_root).unwrap(); - let path = format!("{}/index.json", backup_root); + let path = format!("{backup_root}/index.json"); let mut f = File::create(path).unwrap(); f.write_all(&serde_json::to_vec(self).unwrap()).unwrap(); @@ -62,7 +62,7 @@ impl Backup { pub fn get_last(config: &Config) -> Result> { let backup_index_root = format!("{}/index.json", config.root); - let list: Vec = match Self::get_json_content(&backup_index_root) { + let list: Vec = match Self::get_json_content(&backup_index_root) { Ok(list) => list, Err(err) => { if err.to_string() == "io: No such file or directory (os error 2)" { @@ -78,9 +78,9 @@ impl Backup { )?)) } - pub fn from_index(config: &Config, id: &BackupId) -> Result { + pub fn from_index(config: &Config, id: &Id) -> Result { let backup_index_root = format!("{}/index.json", config.root); - let list: Vec = Self::get_json_content(&backup_index_root)?; + let list: Vec = Self::get_json_content(&backup_index_root)?; let index_loc = list .iter() .find(|bl| &bl.id == id) @@ -94,10 +94,10 @@ impl Backup { Ok(index_file) } - pub fn get_location(&self, config: &Config) -> BackupLocation { + pub fn get_location(&self, config: &Config) -> IndexEntry { let rel_location = format!("{}_{}", config.device, self.timestamp); - BackupLocation { + IndexEntry { id: self.id.to_string(), rel_location, } @@ -106,7 +106,7 @@ impl Backup { pub fn get_absolute_file_location(&self, config: &Config, rel_location: &str) -> String { let loc = self.get_location(config).get_absolute_dir(config); - format!("{}/{}", loc, rel_location) + format!("{loc}/{rel_location}") } fn get_json_content Deserialize<'a>>(path: &str) -> Result { @@ -125,12 +125,12 @@ impl Backup { } #[derive(Debug, Clone, Serialize, Deserialize)] -pub struct BackupLocation { - id: BackupId, +pub struct IndexEntry { + id: Id, rel_location: String, } -impl BackupLocation { +impl IndexEntry { pub fn get_absolute_dir(&self, config: &Config) -> String { format!("{}/{}", config.root, self.rel_location) } @@ -142,7 +142,7 @@ impl BackupLocation { let mut f = File::open(&path)?; let mut content = String::new(); f.read_to_string(&mut content)?; - let mut loc: Vec = serde_json::from_str(&content)?; + let mut loc: Vec = serde_json::from_str(&content)?; let mut f = File::create(path)?; loc.push(self.clone()); diff --git a/src/config.rs b/src/config.rs index 439c17c..13dd0e4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,5 +1,6 @@ use config::{File, Map}; use serde::{Deserialize, Serialize}; +use tracing::{debug, trace}; #[derive(Debug, Serialize, Deserialize)] #[serde(default)] @@ -27,11 +28,15 @@ impl Default for Config { impl Config { pub fn load() -> Result { + debug!("load config"); let config = config::Config::builder() .add_source(File::with_name("config.toml").required(false)) .add_source(config::Environment::with_prefix("FXBAUP").separator("_")) .build()?; - config.try_deserialize() + let cfg = config.try_deserialize(); + trace!(?cfg, "loaded config"); + + cfg } } diff --git a/src/main.rs b/src/main.rs index e67e535..1284e0c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,8 @@ use backup::Backup; use config::Config; use packages::{pacman::Pacman, PackageManager}; +use tracing::{debug, info, level_filters::LevelFilter}; +use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter}; mod backup; mod config; @@ -11,30 +13,39 @@ mod pathinfo; fn main() -> color_eyre::Result<()> { color_eyre::install()?; + let file_appender = tracing_appender::rolling::never("./", "arps.log"); + let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender); + + tracing_subscriber::registry() + .with( + fmt::layer() + .with_writer(non_blocking) + .with_file(false) + .with_ansi(false) + .without_time(), + ) + .with(fmt::layer().with_file(false).without_time()) + .with( + EnvFilter::builder() + .with_default_directive(LevelFilter::INFO.into()) + .from_env_lossy(), + ) + .init(); + debug!("logging initialized"); + let mut cfg = Config::load()?; cfg.user.push("fx".to_string()); cfg.directories.push("~/.config/nvim".to_string()); - // cfg.directories.push("~/.config/hypr".to_string()); cfg.root = "./backup".to_string(); - // cfg.root = "./backup-test".to_string(); - // cfg.directories.push("u:/code/proj/fxbaup/backup-test-dir".to_string()); let pacman = Pacman; let pkgs = pacman.get_installed()?; - - let backup = Backup::create(&cfg, pkgs)?; - // println!("{backup:#?}"); - - backup.save(&cfg)?; - - // PathInfo::compare_to_last_modified(&cfg, &LocationRoot::User("fx".to_string()), "code/proj/fxbaub/backup-test-dir/size.txt")?; - // PathInfo::compare_to_last_modified(&cfg, &LocationRoot::User("fx".to_string()), "code/proj/fxbaub/backup-test-dir/content.txt")?; - - // let index = Backup::get_index(&cfg, None)?; - - // println!("{index:#?}"); - - // let fi = FileInfo::new("~/.config/nvim", &cfg)?; - // println!("{:?}", fi.get_absolute_path()); + let backup = Backup::create(&cfg, pkgs); + // info!(?backup); + // pacman.install(vec![Package { + // id: "lapce".to_string(), + // version: "0.4.2-1".to_string(), + // explicit: true, + // }])?; Ok(()) } diff --git a/src/packages.rs b/src/packages.rs index e7b4c3d..5ee5664 100644 --- a/src/packages.rs +++ b/src/packages.rs @@ -15,5 +15,5 @@ pub struct Package { pub trait PackageManager { fn get_installed(&self) -> Result>; - fn install(&self, pkgs: Vec); + fn install(&self, pkgs: Vec) -> Result<()>; } diff --git a/src/packages/pacman.rs b/src/packages/pacman.rs index b5be4c0..e10c6fb 100644 --- a/src/packages/pacman.rs +++ b/src/packages/pacman.rs @@ -1,4 +1,4 @@ -use std::process::Command; +use std::process::{Command, Stdio}; use super::{Package, PackageManager}; @@ -34,13 +34,23 @@ impl PackageManager for Pacman { id: split[0].to_string(), version: split[1].to_string(), explicit, - }) + }); } Ok(pkgs) } - fn install(&self, _pkgs: Vec) { - todo!(); + fn install(&self, pkgs: Vec) -> Result<()> { + let mut args = vec!["--noconfirm".to_string(), "-S".to_string()]; + + for pkg in pkgs { + args.push(pkg.id); + } + Command::new("pacman") + .stdout(Stdio::inherit()) + .args(args) + .spawn()? + .wait_with_output()?; + Ok(()) } } diff --git a/src/packages/portage.rs b/src/packages/portage.rs index 6b9e508..f9a760b 100644 --- a/src/packages/portage.rs +++ b/src/packages/portage.rs @@ -1,3 +1,5 @@ +use tracing::error; + use super::PackageManager; pub struct Portage; @@ -7,7 +9,8 @@ impl PackageManager for Portage { todo!() } - fn install(&self, pkgs: Vec) { + fn install(&self, pkgs: Vec) -> crate::error::Result<()> { + error!("Install {pkgs:?}"); todo!() } } diff --git a/src/pathinfo.rs b/src/pathinfo.rs index 212dd2a..5b9aa21 100644 --- a/src/pathinfo.rs +++ b/src/pathinfo.rs @@ -6,9 +6,10 @@ use std::{ }; use serde::{Deserialize, Serialize}; +use tracing::info; use crate::{ - backup::{Backup, BackupId}, + backup::{Backup, Id}, config::Config, error::{Error, Result}, }; @@ -18,7 +19,7 @@ pub struct PathInfo { is_file: bool, rel_location: String, location_root: LocationRoot, - last_modified: Option, + last_modified: Option, children: Vec, } @@ -34,7 +35,7 @@ impl PathInfo { rel_location: &str, location_root: &LocationRoot, ) -> Result { - println!("Handling {rel_location}"); + info!("Handling {rel_location}"); let path = Self::get_abs_path(&location_root.to_string(), rel_location); Ok(if path.is_dir() { let mut last_modified = Some(String::new()); @@ -51,7 +52,7 @@ impl PathInfo { }; let handle = Self::handle_dir(config, rl.1, location_root)?; if let Some(lm) = handle.last_modified.clone() { - if last_modified != None { + if last_modified.is_some() { let ts = Backup::from_index(config, &lm)?.timestamp; if ts > last_modified_timestamp { last_modified_timestamp = ts; @@ -82,7 +83,7 @@ impl PathInfo { ) -> Result { let last_modified = Self::compare_to_last_modified(config, location_root, rel_location)?; - println!("From file {rel_location} ({:?})", last_modified); + info!("From file {rel_location} ({last_modified:?})"); Ok(Self { rel_location: rel_location.to_string(), @@ -107,7 +108,6 @@ impl PathInfo { let last_file_opt = Self::find_last_modified(files, rel_location, location_root); let Some(last_file) = last_file_opt else { // File didn't exist last Backup - println!("File didn't exist last Backup"); return Ok(None); }; @@ -120,8 +120,7 @@ impl PathInfo { let old_path = modified_backup.get_absolute_file_location(config, &last_file.rel_location); let new_path = format!("{location_root}/{rel_location}"); - let mut old = File::open(old_path)?; - let mut new = File::open(new_path)?; + let mut old = File::open(old_path)?; let mut new = File::open(new_path)?; let old_len = old.metadata()?.len(); let new_len = new.metadata()?.len(); @@ -147,15 +146,10 @@ impl PathInfo { ) -> Option { for path in files { if path.is_file { - println!("Checking {}", path.rel_location); - println!("File rel: {} ?= {}", path.rel_location, rel_location); - println!("File rot: {} ?= {}", path.location_root, location_root); if path.rel_location == rel_location && path.location_root == *location_root { - println!("Return Some"); return Some(path); }; } else { - println!("Checking all in {path:?}"); let is_modified = PathInfo::find_last_modified(path.children, rel_location, location_root); if is_modified.is_some() { @@ -174,11 +168,9 @@ impl PathInfo { if self.last_modified.is_some() { return Ok(()); } - println!("Save File {:?}", self.rel_location); + info!("Save File {:?}", self.rel_location); if self.is_file { let new_path = format!("{}/{}", backup_root, self.rel_location); - // println!("New Path: {new_path}"); - // println!("Old Path: {:?}", self.get_absolute_path()); let np = Path::new(&new_path); if let Some(parent) = np.parent() { create_dir_all(parent)?; @@ -194,7 +186,7 @@ impl PathInfo { } fn get_abs_path(location_root: &str, rel_location: &str) -> PathBuf { - let path = format!("{}/{}", location_root, rel_location); + let path = format!("{location_root}/{rel_location}"); PathBuf::from(path) } @@ -383,7 +375,7 @@ mod tests { config.root = "./backup-test".to_string(); config .directories - .push("u:fx/code/proj/fxbaup/backup-test-dir".to_string()); + .push("u:fx/code/proj/arps/backup-test-dir".to_string()); create_dir_all("./backup-test-dir")?; let mut f = File::create("./backup-test-dir/size.txt")?; @@ -403,12 +395,12 @@ mod tests { let mut f = File::create("./backup-test-dir/content.txt")?; f.write_all("unmodefied".as_bytes())?; - let pi = PathInfo::from_path(&config, "u:fx/code/proj/fxbaup/backup-test-dir")?; + let pi = PathInfo::from_path(&config, "u:fx/code/proj/arps/backup-test-dir")?; let last_backup = Backup::get_last(&config)?.unwrap(); for file in pi.children { println!("test rel: {}", file.rel_location); - let res = if file.rel_location == "code/proj/fxbaup/backup-test-dir/nothing.txt" { + let res = if file.rel_location == "code/proj/arps/backup-test-dir/nothing.txt" { Some(last_backup.id.clone()) } else { None -- cgit v1.2.3