refactor: general small refactors to simplify code

- Remove `expect` in favor of `unwrap` when the `Result`'s error variant
  contains the info in the `expect` anyway (eg. when locking things).
  The line number/context are given by the backtrace.
- Remove over-specification of types (`&T` instead of
  `&RWReadLockGuard`)
- Put reused values into constants
- `FromStr` instead of manual function
- Change `if let Some(()) = ...` to `if T.is_some()`
This commit is contained in:
Thomas Frans
2024-02-01 22:05:43 +01:00
committed by Henrik Friedrichsen
parent c5d666f35c
commit 3c8e546445
12 changed files with 97 additions and 96 deletions

View File

@@ -1,12 +1,12 @@
use std::collections::HashMap;
use std::error::Error;
use std::path::PathBuf;
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::sync::{RwLock, RwLockReadGuard};
use std::{fs, process};
use cursive::theme::Theme;
use log::{debug, error};
use ncspot::CONFIGURATION_FILE_NAME;
use ncspot::{CONFIGURATION_FILE_NAME, USER_STATE_FILE_NAME};
use platform_dirs::AppDirs;
use crate::command::{SortDirection, SortKey};
@@ -209,7 +209,7 @@ impl Config {
});
let mut userstate = {
let path = config_path("userstate.cbor");
let path = config_path(USER_STATE_FILE_NAME);
CBOR.load_or_generate_default(path, || Ok(UserState::default()), true)
.expect("could not load user state")
};
@@ -235,36 +235,36 @@ impl Config {
/// Get the user configuration values.
pub fn values(&self) -> RwLockReadGuard<ConfigValues> {
self.values.read().expect("can't readlock config values")
self.values.read().unwrap()
}
/// Get the runtime user state values.
pub fn state(&self) -> RwLockReadGuard<UserState> {
self.state.read().expect("can't readlock user state")
self.state.read().unwrap()
}
/// Modify the internal user state through a shared reference using a closure.
pub fn with_state_mut<F>(&self, cb: F)
where
F: Fn(RwLockWriteGuard<UserState>),
F: Fn(&mut UserState),
{
let state_guard = self.state.write().expect("can't writelock user state");
cb(state_guard);
let mut state_guard = self.state.write().unwrap();
cb(&mut state_guard);
}
/// Update the version number of the runtime user state. This should be done before saving it to
/// disk.
fn update_state_cache_version(&self) {
self.with_state_mut(|mut state| state.cache_version = CACHE_VERSION);
self.with_state_mut(|state| state.cache_version = CACHE_VERSION);
}
/// Save runtime state to the user configuration directory.
pub fn save_state(&self) {
self.update_state_cache_version();
let path = config_path("userstate.cbor");
let path = config_path(USER_STATE_FILE_NAME);
debug!("saving user state to {}", path.display());
if let Err(e) = CBOR.write(path, self.state().clone()) {
if let Err(e) = CBOR.write(path, &*self.state()) {
error!("Could not save user state: {}", e);
}
}