Skip to content

Commit

Permalink
Added in Logging, and cleaned up the unwraps
Browse files Browse the repository at this point in the history
Cleaned up all of the unwraps, and added in some basic simple logging. It just logs to a file in the same directory as the executable, and only logs errors that happen in place of the previous unwraps.

I also updated the RFD crate to v 0.12
  • Loading branch information
Vadoola committed Oct 2, 2023
1 parent d41605c commit b8241b4
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 22 deletions.
6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pv-unlocker"
version = "0.6.0"
version = "0.7.0"
authors = ["Carl <carl@vadoola.com>"]
edition = "2021"
build = "build.rs"
Expand All @@ -13,7 +13,9 @@ ab_versions = {git = "https://github.com/Vadoola/ab_versions_rs.git"}
clap = { version = "4.3", features = ["derive"] }
rayon = "1.5"
wild = "2.1"
rfd = { version = "0.11.4", default-features = false, features = ["xdg-portal"]}
rfd = { version = "0.12", default-features = false, features = ["xdg-portal"]}
log = "0.4.20"
simplelog = "0.12.1"

[build-dependencies]
slint-build = "1.1"
Expand Down
99 changes: 79 additions & 20 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@

use ab_versions::{get_version, is_protected, strip_protection};
use clap::Parser;
use log::error;
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
use rfd::FileDialog;
use simplelog::{CombinedLogger, Config, LevelFilter, SimpleLogger, WriteLogger};
use slint::{Model, ModelRc, VecModel};
use std::{borrow::BorrowMut, cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc};
use std::{
borrow::BorrowMut, cell::RefCell, collections::HashMap, fs::File, path::PathBuf, rc::Rc,
};

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
Expand All @@ -21,6 +25,24 @@ struct Args {
slint::include_modules!();

fn main() -> Result<(), slint::PlatformError> {
CombinedLogger::init(vec![
#[cfg(feature = "termcolor")]
TermLogger::new(
LevelFilter::Warn,
Config::default(),
TerminalMode::Mixed,
ColorChoice::Auto,
),
#[cfg(not(feature = "termcolor"))]
SimpleLogger::new(LevelFilter::Warn, Config::default()),
WriteLogger::new(
LevelFilter::Info,
Config::default(),
File::create("my_rust_binary.log").expect("Failed to create log file"),
),
])
.expect("Failed to create logging infrastructure");

let args = Args::parse_from(wild::args());
let files = Rc::new(RefCell::new(process_paths(args.files)));

Expand All @@ -29,23 +51,38 @@ fn main() -> Result<(), slint::PlatformError> {

//if files were passed on the command line process them and add them to the UI model
let info = get_file_info(&files.borrow());
file_model.borrow_mut().extend(info.into_iter());
file_model.borrow_mut().extend(info);

ui.set_files(ModelRc::from(file_model.clone()));

let unlock_file_model = file_model.clone();
let unlock_files = files.clone();
ui.on_unlock(move |file, idx| {
if let Some(path) = unlock_files.borrow().get(&file.to_string()) {
strip_protection(path).unwrap();

//After attempting to unlock it update the model with the new protected status
//by verifying it in the file on disk
let unlock_file_model = unlock_file_model.as_ref();
if let Some(mut row_data) = unlock_file_model.row_data(idx as usize) {
row_data.locked = is_protected(&path).unwrap();
unlock_file_model.set_row_data(idx as usize, row_data);
} //else...hmm error updating the model?...what to do?
match strip_protection(path) {
Ok(_) => {
//After attempting to unlock it update the model with the new protected status
//by verifying it in the file on disk
let unlock_file_model = unlock_file_model.as_ref();
if let Some(mut row_data) = unlock_file_model.row_data(idx as usize) {
match is_protected(&path) {
Ok(lck) => {
row_data.locked = lck;
unlock_file_model.set_row_data(idx as usize, row_data);
}
Err(e) => {
error!(
"Unable to confirm file {} was unlocked. Reason: {e}",
path.display()
)
}
}
}
}
Err(e) => {
error!("Failed to unlock file {}. Reason: {e}", path.display())
}
}
} //else display some sort of toast message with the error?
});

Expand All @@ -69,11 +106,15 @@ fn process_paths(files: Vec<PathBuf>) -> HashMap<String, PathBuf> {
files
.into_iter()
.map(|pb| {
let name = pb
.file_name()
.map(std::ffi::OsStr::to_string_lossy)
.unwrap()
.to_string();
let name = {
let tmp_name = pb.file_name().map(std::ffi::OsStr::to_string_lossy);

if let Some(tmp_name) = tmp_name {
tmp_name.to_string()
} else {
pb.display().to_string()
}
};
(name, pb)
})
.collect()
Expand All @@ -82,10 +123,28 @@ fn process_paths(files: Vec<PathBuf>) -> HashMap<String, PathBuf> {
fn get_file_info(files: &HashMap<String, PathBuf>) -> Vec<file_info> {
files
.par_iter()
.map(|(name, file)| file_info {
locked: is_protected(&file).unwrap(),
file_name: name.into(),
file_ver: get_version(&file).unwrap().to_string().into(),
.filter_map(|(name, file)| match is_protected(&file) {
Ok(lckd) => match get_version(&file) {
Ok(ver) => Some(file_info {
locked: lckd,
file_name: name.into(),
file_ver: ver.to_string().into(),
}),
Err(e) => {
error!(
"Unable to get file information from {}. Reason: {e}",
file.display()
);
None
}
},
Err(e) => {
error!(
"Unable to get file information from {}. Reason: {e}",
file.display()
);
None
}
})
.collect()
}

0 comments on commit b8241b4

Please sign in to comment.