Remove more unwrap

This commit is contained in:
micialware committed 2026-08-24 23:27:24 +03:00
1 parent b5b1eb768c
commit d836b57d2a
5 files changed
+48 -36

No files matched your search

+12 -9
View File
@@ -1,12 +1,15 @@
use crate::app::AppState; use crate::app::AppState;
use crate::core::srs::{OrderMode, OrderModule, RandomSRSModule, SRSModule, SemiRandomSRSModule, WordOpenMode, WorstWordsSRSModule}; use crate::core::srs::{
OrderMode, OrderModule, RandomSRSModule, SRSModule, SemiRandomSRSModule, WordOpenMode,
WorstWordsSRSModule,
};
use crate::data::entities::*; use crate::data::entities::*;
use crate::data_provider::card_stats::{load_stats_of_deck, update_stat_score}; use crate::data_provider::card_stats::{load_stats_of_deck, update_stat_score};
use crate::data_provider::history::push_note; use crate::data_provider::history::push_note;
use crate::notification::NotificationData;
use chrono::Utc; use chrono::Utc;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::sync::Arc; use std::sync::Arc;
use crate::notification::NotificationData;
#[derive(Clone)] #[derive(Clone)]
pub struct DeckData { pub struct DeckData {
@@ -18,7 +21,10 @@ pub struct DeckData {
settings: DeckSettings, settings: DeckSettings,
} }
impl DeckData { impl DeckData {
pub fn new(settings: &DeckSettings, state: Arc<Mutex<AppState>>) -> Result<Self, NotificationData> { pub fn new(
settings: &DeckSettings,
state: Arc<Mutex<AppState>>,
) -> Result<Self, NotificationData> {
let state_for = state.clone(); let state_for = state.clone();
let state_locked = state.lock(); let state_locked = state.lock();
@@ -83,11 +89,7 @@ impl DeckData {
(self.words[index].clone(), self.set[index].clone()) (self.words[index].clone(), self.set[index].clone())
} }
pub fn open(&mut self, status: WordOpenMode) -> Result<(), NotificationData> { pub fn open(&mut self, status: WordOpenMode) -> Result<(), NotificationData> {
if self.current_word_index.is_none() { if let Some(index) = self.current_word_index {
return Ok(());
}
let index = self.current_word_index.unwrap();
let word: &mut CardStatistics = &mut self.set[index]; let word: &mut CardStatistics = &mut self.set[index];
let old_score = word.score; let old_score = word.score;
word.update(status); word.update(status);
@@ -115,10 +117,11 @@ impl DeckData {
after: new_score, after: new_score,
}, },
); );
}
Ok(()) Ok(())
} }
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.set.len() self.set.len()
} }
} }
+1 -1
View File
@@ -111,7 +111,7 @@ impl SRSModule for SemiRandomSRSModule {
.iter() .iter()
.map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0) .map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0)
.collect::<Vec<f32>>(); .collect::<Vec<f32>>();
self.last_weights = WeightedIndex::new(weights).unwrap(); self.last_weights = WeightedIndex::new(weights).expect("Incorrect weights update");
} }
} }
impl SemiRandomSRSModule { impl SemiRandomSRSModule {
+5 -2
View File
@@ -105,12 +105,15 @@ impl DeckSettings {
.iter() .iter()
.find(|g| g.id == word.group_id) .find(|g| g.id == word.group_id)
.cloned() .cloned()
.unwrap() .expect("No group id")
.name, .name,
); );
let result = engine.eval_ast_with_scope::<bool>(&mut scope, &ast); let result = engine.eval_ast_with_scope::<bool>(&mut scope, &ast);
result.is_ok() && result.unwrap() if let Ok(result) = result {
return result
}
false
}) })
.map(|(index, _)| index) .map(|(index, _)| index)
.collect(); .collect();
+2 -2
View File
@@ -4,10 +4,10 @@ use crate::notification::NotificationData;
use crate::notification::NotificationData::PermissionDenied; use crate::notification::NotificationData::PermissionDenied;
pub fn app_data_dir() -> PathBuf { pub fn app_data_dir() -> PathBuf {
let mut dir = dirs::data_dir().unwrap(); let mut dir = dirs::data_dir().expect("Unsupported OS");
dir.push("jap_learn"); dir.push("jap_learn");
if !dir.exists() { if !dir.exists() {
fs::create_dir_all(dir.clone()).unwrap(); fs::create_dir_all(dir.clone()).expect("Unable to create directory");
} }
dir dir
+28 -22
View File
@@ -1,11 +1,12 @@
use crate::app::{fill_state, AppState}; use crate::app::{fill_state, AppState};
use crate::data::Id;
use crate::data_provider::history::get_history_of_set; use crate::data_provider::history::get_history_of_set;
use crate::data_provider::sqlite::{create_db, default_connection}; use crate::data_provider::sqlite::{create_db, default_connection};
use crate::data_provider::web_api::{ use crate::data_provider::web_api::{
get_local_version, get_web_version, load_data, set_local_version, get_local_version, get_web_version, load_data, set_local_version,
}; };
use crate::fs::*; use crate::fs::*;
use crate::message_navigation; use crate::{message_navigation, push_error, push_error_task};
use crate::navigation::Page::*; use crate::navigation::Page::*;
use crate::navigation::RootMessage::{ use crate::navigation::RootMessage::{
DataLoaded, Keyboard, Notification, PushNotification, UpdateData, DataLoaded, Keyboard, Notification, PushNotification, UpdateData,
@@ -40,7 +41,7 @@ use parking_lot::Mutex;
use rusqlite::Connection; use rusqlite::Connection;
use std::sync::Arc; use std::sync::Arc;
use std::time::Instant; use std::time::Instant;
use crate::data::Id; use crate::notification::NotificationData::PermissionDenied;
impl Default for ScreenState { impl Default for ScreenState {
fn default() -> Self { fn default() -> Self {
@@ -110,12 +111,13 @@ impl ScreenState {
let state = ScreenState::default(); let state = ScreenState::default();
let reading_additional_task = Task::perform(Self::load_additional_data(), |data| data); let reading_additional_task = Task::perform(Self::load_additional_data(), |data| data);
let final_task; let mut final_task = reading_additional_task;
let state_guard = state.app_state.lock(); let state_guard = state.app_state.lock();
if state_guard.sync_data.auto_web_fetch { if state_guard.sync_data.auto_web_fetch
let key = state_guard.sync_data.key.clone().unwrap(); && let Some(key) = state_guard.sync_data.key.clone()
{
final_task = Task::batch([ final_task = Task::batch([
reading_additional_task, final_task,
Task::perform(Self::load_web_backup(key), |result| match result { Task::perform(Self::load_web_backup(key), |result| match result {
Ok(update) => { Ok(update) => {
if update { if update {
@@ -127,8 +129,6 @@ impl ScreenState {
Err(err) => PushNotification(NotificationRequest::Warning(err)), Err(err) => PushNotification(NotificationRequest::Warning(err)),
}), }),
]); ]);
} else {
final_task = reading_additional_task;
} }
drop(state_guard); drop(state_guard);
@@ -138,21 +138,23 @@ impl ScreenState {
async fn load_additional_data() -> RootMessage { async fn load_additional_data() -> RootMessage {
let directory = history_dir(); let directory = history_dir();
if let Ok(directory) = directory { if let Ok(directory) = directory {
let mut map = HashMap::new(); let mut map = HashMap::new();
for file in directory.read_dir().unwrap().flatten() { for file in directory
.read_dir()
.expect("Cant read history directory")
.flatten()
{
let mut vec = vec![]; let mut vec = vec![];
let history_file_name = match file.file_name().into_string() { let history_file_name = match file.file_name().into_string() {
Err(_) => continue, Err(_) => continue,
Ok(v) => v, Ok(v) => v,
}; };
let id = history_file_name[4..history_file_name.len() - 12] if let Ok(id) = history_file_name[4..history_file_name.len() - 12].parse::<Id>()
.parse::<Id>() && let Ok(history) = get_history_of_set(id)
.unwrap(); {
let history = get_history_of_set(id);
if let Ok(history) = history {
let by_date = history.chunk_by(|x, x1| { let by_date = history.chunk_by(|x, x1| {
x.timestamp.naive_local().date() == x1.timestamp.naive_local().date() x.timestamp.naive_local().date() == x1.timestamp.naive_local().date()
}); });
@@ -161,7 +163,7 @@ impl ScreenState {
} }
map.insert(id, vec); map.insert(id, vec);
} else { } else {
return PushNotification(NotificationRequest::Warning(history.err().unwrap())); return PushNotification(NotificationRequest::Warning(PermissionDenied));
} }
} }
return DataLoaded(map); return DataLoaded(map);
@@ -203,7 +205,9 @@ impl ScreenState {
} }
let db_file = db_path(); let db_file = db_path();
let temp_db_file = temp_db_path(); let temp_db_file = temp_db_path();
std::fs::rename(temp_db_file, &db_file).unwrap(); if std::fs::rename(temp_db_file, &db_file).is_err(){
return push_error_task!(PermissionDenied)
}
state.connection = default_connection(); state.connection = default_connection();
fill_state(&mut state); fill_state(&mut state);
@@ -290,12 +294,14 @@ impl ScreenState {
} }
fn handle_keyboard(&mut self, message: Event) -> Task<RootMessage> { fn handle_keyboard(&mut self, message: Event) -> Task<RootMessage> {
let page = self.stack.last_mut().unwrap(); if let Some(page) = self.stack.last_mut(){
match page { return match page {
Repetition(page) => page.press(&message), Repetition(page) => page.press(&message),
_ => Task::none(), _ => Task::none(),
} }
} }
Task::none()
}
} }
pub struct AppSettings { pub struct AppSettings {
@@ -306,7 +312,7 @@ pub struct AppSettings {
#[macro_export] #[macro_export]
macro_rules! view_navigation { macro_rules! view_navigation {
($stack:expr, $($e:ident), *) => { ($stack:expr, $($e:ident), *) => {
match &$stack.last().unwrap() { match &$stack.last().expect("Unexpected stack state") {
$( $(
$e(s) => s.view().map(RootMessage::$e), $e(s) => s.view().map(RootMessage::$e),
)* )*
@@ -320,7 +326,7 @@ macro_rules! state_update {
match $message { match $message {
$( $(
RootMessage::$e(msg) => { RootMessage::$e(msg) => {
if let $e(s) = $stack.last_mut().unwrap() { if let $e(s) = $stack.last_mut().expect("Unexpected stack state") {
message_navigation!(msg, $stack, s) message_navigation!(msg, $stack, s)
} }
else { else {
@@ -355,7 +361,7 @@ macro_rules! message_navigation {
#[macro_export] #[macro_export]
macro_rules! state_navigate_handle { macro_rules! state_navigate_handle {
($stack:expr, $($e:ident), *) => { ($stack:expr, $($e:ident), *) => {
match $stack.last_mut().unwrap() { match $stack.last_mut().expect("Unexpected stack state") {
$( $(
Page::$e(page) => { Page::$e(page) => {
page.navigated(); page.navigated();