From 2266da9106a8abc322b3b23d362a90ef65408954 Mon Sep 17 00:00:00 2001 From: 2Shirt <2xShirt@gmail.com> Date: Sun, 17 Nov 2024 16:12:04 -0800 Subject: [PATCH] Apply Clippy pedantic recommendations --- src/app.rs | 63 ++++++++++++++++++---------------------- src/components/footer.rs | 56 +++++++++++++++-------------------- src/components/left.rs | 23 +++++++-------- src/components/popup.rs | 11 +++---- src/components/right.rs | 24 +++++++-------- src/components/title.rs | 11 +++---- src/config.rs | 37 ++++++++++++----------- src/system/disk.rs | 8 ++--- src/system/diskpart.rs | 4 +-- src/tasks.rs | 13 ++++----- 10 files changed, 110 insertions(+), 140 deletions(-) diff --git a/src/app.rs b/src/app.rs index 4322a1a..a5ba031 100644 --- a/src/app.rs +++ b/src/app.rs @@ -141,14 +141,15 @@ impl App { (_, Mode::PreClone) => Mode::Clone, (_, Mode::Clone) => Mode::SelectParts, (Mode::SelectParts, Mode::Confirm) => Mode::PostClone, - (_, Mode::PostClone) => Mode::Done, - (_, Mode::Done) => Mode::Done, + (_, Mode::PostClone | Mode::Done) => Mode::Done, (_, Mode::Failed) => Mode::Failed, // Invalid states (_, Mode::Confirm) => panic!("This shouldn't happen."), }; - if new_mode != self.cur_mode { + if new_mode == self.cur_mode { + None + } else { match self.cur_mode { // Update prev_mode if appropriate Mode::Confirm => {} @@ -159,8 +160,6 @@ impl App { _ => self.prev_mode = self.cur_mode, } Some(new_mode) - } else { - None } } @@ -171,13 +170,13 @@ impl App { .frame_rate(self.frame_rate); tui.enter()?; - for component in self.components.iter_mut() { + for component in &mut self.components { component.register_action_handler(self.action_tx.clone())?; } - for component in self.components.iter_mut() { + for component in &mut self.components { component.register_config_handler(self.config.clone())?; } - for component in self.components.iter_mut() { + for component in &mut self.components { component.init(tui.size()?)?; } @@ -213,7 +212,7 @@ impl App { Event::Key(key) => self.handle_key_event(key)?, _ => {} } - for component in self.components.iter_mut() { + for component in &mut self.components { if let Some(action) = component.handle_events(Some(event.clone()))? { action_tx.send(action)?; } @@ -226,22 +225,19 @@ impl App { let Some(keymap) = self.config.keybindings.get(&self.cur_mode) else { return Ok(()); }; - match keymap.get(&vec![key]) { - Some(action) => { + if let Some(action) = keymap.get(&vec![key]) { + info!("Got action: {action:?}"); + action_tx.send(action.clone())?; + } else { + // If the key was not handled as a single key action, + // then consider it for multi-key combinations. + self.last_tick_key_events.push(key); + + // Check for multi-key combinations + if let Some(action) = keymap.get(&self.last_tick_key_events) { info!("Got action: {action:?}"); action_tx.send(action.clone())?; } - _ => { - // If the key was not handled as a single key action, - // then consider it for multi-key combinations. - self.last_tick_key_events.push(key); - - // Check for multi-key combinations - if let Some(action) = keymap.get(&self.last_tick_key_events) { - info!("Got action: {action:?}"); - action_tx.send(action.clone())?; - } - } } Ok(()) } @@ -272,7 +268,7 @@ impl App { self.action_tx.send(Action::SetMode(Mode::Failed))?; } Action::InstallDriver => { - self.action_tx.send(Action::SetMode(Mode::InstallDrivers))? + self.action_tx.send(Action::SetMode(Mode::InstallDrivers))?; } Action::SelectDriver(ref driver) => { self.driver = Some(driver.clone()); @@ -358,14 +354,13 @@ impl App { // Get System32 path let system32 = if cfg!(windows) { - match env::var("SYSTEMROOT") { - Ok(path) => format!("{path}/System32"), - Err(_) => { - self.action_tx.send(Action::Error(String::from( - "ERROR\n\n\nFailed to find SYSTEMROOT", - )))?; - return Ok(()); - } + if let Ok(path) = env::var("SYSTEMROOT") { + format!("{path}/System32") + } else { + self.action_tx.send(Action::Error(String::from( + "ERROR\n\n\nFailed to find SYSTEMROOT", + )))?; + return Ok(()); } } else { String::from(".") @@ -467,9 +462,9 @@ impl App { } _ => {} } - for component in self.components.iter_mut() { + for component in &mut self.components { if let Some(action) = component.update(action.clone())? { - self.action_tx.send(action)? + self.action_tx.send(action)?; }; } } @@ -494,7 +489,7 @@ impl App { if let Err(err) = component.draw(frame, area) { let _ = self .action_tx - .send(Action::Error(format!("Failed to draw: {:?}", err))); + .send(Action::Error(format!("Failed to draw: {err:?}"))); } } }; diff --git a/src/components/footer.rs b/src/components/footer.rs index 8258e21..1530cd7 100644 --- a/src/components/footer.rs +++ b/src/components/footer.rs @@ -14,7 +14,10 @@ // along with Deja-vu. If not, see . // use color_eyre::Result; -use ratatui::{prelude::*, widgets::*}; +use ratatui::{ + prelude::*, + widgets::{Block, Borders, Paragraph}, +}; use tokio::sync::mpsc::UnboundedSender; use super::Component; @@ -24,13 +27,13 @@ use crate::{action::Action, app::Mode, config::Config}; pub struct Footer { command_tx: Option>, config: Config, - footer_text: String, + text: String, } impl Footer { pub fn new() -> Self { Self { - footer_text: String::from("(q) to quit"), + text: String::from("(q) to quit"), ..Default::default() } } @@ -48,36 +51,25 @@ impl Component for Footer { } fn update(&mut self, action: Action) -> Result> { - match action { - Action::Tick => { - // add any logic here that should run on every tick - } - Action::Render => { - // add any logic here that should run on every render - } - Action::SetMode(new_mode) => { - self.footer_text = match new_mode { - Mode::ScanDisks | Mode::PreClone | Mode::Clone | Mode::PostClone => { - String::from("(q) to quit") - } - Mode::SelectParts => { - String::from("(Enter) to select / (s) to start over / (q) to quit") - } - Mode::SelectDisks => String::from( - "(Enter) to select / / (i) to install driver / (r) to rescan / (q) to quit", - ), - Mode::SelectTableType => { - String::from("(Enter) to select / (b) to go back / (q) to quit") - } - Mode::Confirm => { - String::from("(Enter) to confirm / (b) to go back / (q) to quit") - } - Mode::Done | Mode::Failed | Mode::InstallDrivers => { - String::from("(Enter) or (q) to quit") - } + if let Action::SetMode(new_mode) = action { + self.text = match new_mode { + Mode::ScanDisks | Mode::PreClone | Mode::Clone | Mode::PostClone => { + String::from("(q) to quit") + } + Mode::SelectParts => { + String::from("(Enter) to select / (s) to start over / (q) to quit") + } + Mode::SelectDisks => String::from( + "(Enter) to select / / (i) to install driver / (r) to rescan / (q) to quit", + ), + Mode::SelectTableType => { + String::from("(Enter) to select / (b) to go back / (q) to quit") + } + Mode::Confirm => String::from("(Enter) to confirm / (b) to go back / (q) to quit"), + Mode::Done | Mode::Failed | Mode::InstallDrivers => { + String::from("(Enter) or (q) to quit") } } - _ => {} } Ok(None) } @@ -85,7 +77,7 @@ impl Component for Footer { fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> { let footer = Paragraph::new( Line::from(Span::styled( - &self.footer_text, + &self.text, Style::default().fg(Color::DarkGray), )) .centered(), diff --git a/src/components/left.rs b/src/components/left.rs index 3d46716..8ccfa12 100644 --- a/src/components/left.rs +++ b/src/components/left.rs @@ -15,7 +15,10 @@ // use color_eyre::Result; use crossterm::event::KeyEvent; -use ratatui::{prelude::*, widgets::*}; +use ratatui::{ + prelude::*, + widgets::{Block, Borders, HighlightSpacing, List, ListItem, Padding, Paragraph}, +}; use tokio::sync::mpsc::UnboundedSender; use tracing::info; @@ -73,12 +76,6 @@ impl Component for Left { fn update(&mut self, action: Action) -> Result> { match action { - Action::Tick => { - // add any logic here that should run on every tick - } - Action::Render => { - // add any logic here that should run on every render - } Action::KeyUp => match self.mode { Mode::InstallDrivers => self.list_drivers.previous(), Mode::SelectDisks => self.list_disks.previous(), @@ -180,7 +177,7 @@ impl Component for Left { match (prev_mode, new_mode) { (_, Mode::ScanDisks) => { self.list_disks.clear_items(); - self.title_text = String::from(""); + self.title_text = String::new(); } (_, Mode::InstallDrivers) => { self.list_drivers.set_items(drivers::scan()); @@ -215,10 +212,10 @@ impl Component for Left { self.title_text = String::from("Select Boot and OS Partitions"); } (Mode::SelectDisks | Mode::SelectParts, Mode::Confirm) => { - self.title_text = String::from("Confirm Selections") + self.title_text = String::from("Confirm Selections"); } (Mode::SelectTableType, Mode::Confirm) => { - self.title_text = String::from("Confirm Selections (Again)") + self.title_text = String::from("Confirm Selections (Again)"); } (_, Mode::Done | Mode::Failed) => self.title_text = String::from("Done"), // Invalid states @@ -368,10 +365,10 @@ impl Component for Left { .repeat_highlight_symbol(false); match self.mode { Mode::InstallDrivers => { - frame.render_stateful_widget(list, body_area, &mut self.list_drivers.state) + frame.render_stateful_widget(list, body_area, &mut self.list_drivers.state); } Mode::SelectDisks => { - frame.render_stateful_widget(list, body_area, &mut self.list_disks.state) + frame.render_stateful_widget(list, body_area, &mut self.list_disks.state); } Mode::SelectTableType => frame.render_stateful_widget( list, @@ -379,7 +376,7 @@ impl Component for Left { &mut self.list_table_types.state, ), Mode::SelectParts => { - frame.render_stateful_widget(list, body_area, &mut self.list_parts.state) + frame.render_stateful_widget(list, body_area, &mut self.list_parts.state); } _ => panic!("This shouldn't happen."), } diff --git a/src/components/popup.rs b/src/components/popup.rs index 54318a1..933dbde 100644 --- a/src/components/popup.rs +++ b/src/components/popup.rs @@ -14,7 +14,10 @@ // along with Deja-vu. If not, see . // use color_eyre::Result; -use ratatui::{prelude::*, widgets::*}; +use ratatui::{ + prelude::*, + widgets::{Block, Borders, Clear, Paragraph, Wrap}, +}; use serde::{Deserialize, Serialize}; use strum::Display; use tokio::sync::mpsc::UnboundedSender; @@ -61,12 +64,6 @@ impl Component for Popup { fn update(&mut self, action: Action) -> Result> { match action { - Action::Tick => { - // add any logic here that should run on every tick - } - Action::Render => { - // add any logic here that should run on every render - } Action::DismissPopup => self.popup_text.clear(), Action::DisplayPopup(new_type, new_text) => { self.popup_type = new_type; diff --git a/src/components/right.rs b/src/components/right.rs index 5eea48d..d053b25 100644 --- a/src/components/right.rs +++ b/src/components/right.rs @@ -15,7 +15,10 @@ // use color_eyre::Result; use crossterm::event::KeyEvent; -use ratatui::{prelude::*, widgets::*}; +use ratatui::{ + prelude::*, + widgets::{Block, Borders, Padding, Paragraph, Wrap}, +}; use tokio::sync::mpsc::UnboundedSender; use tracing::info; @@ -71,12 +74,6 @@ impl Component for Right { fn update(&mut self, action: Action) -> Result> { match action { - Action::Tick => { - // add any logic here that should run on every tick - } - Action::Render => { - // add any logic here that should run on every render - } Action::KeyUp => match self.cur_mode { Mode::SelectDisks => self.list_disks.previous(), Mode::SelectParts => self.list_parts.previous(), @@ -175,9 +172,8 @@ impl Component for Right { (_, Mode::InstallDrivers) => { body_text.push(Line::from(Span::raw(format!("CPU: {}", get_cpu_name())))); } - (_, Mode::SelectDisks) - | (Mode::SelectDisks | Mode::SelectTableType, Mode::Confirm) - | (_, Mode::SelectTableType) => { + (_, Mode::SelectDisks | Mode::SelectTableType) + | (Mode::SelectDisks | Mode::SelectTableType, Mode::Confirm) => { // Source Disk body_text.push(Line::from(Span::styled( "Source:", @@ -230,10 +226,10 @@ impl Component for Right { (Some(one), None) => { // First selected if let Some(two) = self.selections[1] { - if one != two { - self.selections[1] - } else { + if one == two { None + } else { + self.selections[1] } } else { self.list_disks.selected() @@ -263,7 +259,7 @@ impl Component for Right { ])); if let Some(table_type) = &self.table_type { body_text.push(Line::from(Span::styled( - format!(" (Will be formatted {})", table_type), + format!(" (Will be formatted {table_type})"), Style::default().yellow().bold(), ))); } diff --git a/src/components/title.rs b/src/components/title.rs index 8855808..1394186 100644 --- a/src/components/title.rs +++ b/src/components/title.rs @@ -14,7 +14,10 @@ // along with Deja-vu. If not, see . // use color_eyre::Result; -use ratatui::{prelude::*, widgets::*}; +use ratatui::{ + prelude::*, + widgets::{Block, Borders, Paragraph}, +}; use tokio::sync::mpsc::UnboundedSender; use super::Component; @@ -45,12 +48,6 @@ impl Component for Title { fn update(&mut self, action: Action) -> Result> { match action { - Action::Tick => { - // add any logic here that should run on every tick - } - Action::Render => { - // add any logic here that should run on every render - } _ => {} } Ok(None) diff --git a/src/config.rs b/src/config.rs index 4fb882c..d402e55 100644 --- a/src/config.rs +++ b/src/config.rs @@ -89,7 +89,7 @@ impl Config { .required(false); builder = builder.add_source(source); if config_dir.join(file).exists() { - found_config = true + found_config = true; } } if !found_config { @@ -100,7 +100,7 @@ impl Config { for (mode, default_bindings) in default_config.keybindings.iter() { let user_bindings = cfg.keybindings.entry(*mode).or_default(); - for (key, cmd) in default_bindings.iter() { + for (key, cmd) in default_bindings { user_bindings .entry(key.clone()) .or_insert_with(|| cmd.clone()); @@ -108,7 +108,7 @@ impl Config { } for (mode, default_styles) in default_config.styles.iter() { let user_styles = cfg.styles.entry(*mode).or_default(); - for (style_key, style) in default_styles.iter() { + for (style_key, style) in default_styles { user_styles.entry(style_key.clone()).or_insert(*style); } } @@ -234,8 +234,7 @@ fn parse_key_code_with_modifiers( "f11" => KeyCode::F(11), "f12" => KeyCode::F(12), "space" => KeyCode::Char(' '), - "hyphen" => KeyCode::Char('-'), - "minus" => KeyCode::Char('-'), + "hyphen" | "minus" => KeyCode::Char('-'), "tab" => KeyCode::Tab, c if c.len() == 1 => { let mut c = c.chars().next().unwrap(); @@ -276,16 +275,16 @@ pub fn key_event_to_string(key_event: &KeyEvent) -> String { &char } KeyCode::Esc => "esc", - KeyCode::Null => "", - KeyCode::CapsLock => "", - KeyCode::Menu => "", - KeyCode::ScrollLock => "", - KeyCode::Media(_) => "", - KeyCode::NumLock => "", - KeyCode::PrintScreen => "", - KeyCode::Pause => "", - KeyCode::KeypadBegin => "", - KeyCode::Modifier(_) => "", + KeyCode::Null + | KeyCode::CapsLock + | KeyCode::Menu + | KeyCode::ScrollLock + | KeyCode::Media(_) + | KeyCode::NumLock + | KeyCode::PrintScreen + | KeyCode::Pause + | KeyCode::KeypadBegin + | KeyCode::Modifier(_) => "", }; let mut modifiers = Vec::with_capacity(3); @@ -314,13 +313,13 @@ pub fn key_event_to_string(key_event: &KeyEvent) -> String { pub fn parse_key_sequence(raw: &str) -> Result, String> { if raw.chars().filter(|c| *c == '>').count() != raw.chars().filter(|c| *c == '<').count() { - return Err(format!("Unable to parse `{}`", raw)); + return Err(format!("Unable to parse `{raw}`")); } - let raw = if !raw.contains("><") { - let raw = raw.strip_prefix('<').unwrap_or(raw); - let raw = raw.strip_prefix('>').unwrap_or(raw); + let raw = if raw.contains("><") { raw } else { + let raw = raw.strip_prefix('<').unwrap_or(raw); + let raw = raw.strip_prefix('>').unwrap_or(raw); raw }; let sequences = raw diff --git a/src/system/disk.rs b/src/system/disk.rs index 46e010b..96a8ae0 100644 --- a/src/system/disk.rs +++ b/src/system/disk.rs @@ -91,7 +91,7 @@ impl fmt::Display for Disk { f, "Disk {:<3} {:>11} {:<4} {:<4} {} ({})", self.id, - bytes_to_string(&self.size), + bytes_to_string(self.size), self.conn_type, match self.part_type { PartitionTableType::Guid => "GPT", @@ -114,7 +114,7 @@ impl fmt::Display for Partition { s = format!( "{:<8} {:>11} {:<7}", self.id, - bytes_to_string(&self.size), + bytes_to_string(self.size), fs ); if !self.label.is_empty() { @@ -359,10 +359,10 @@ fn refresh_fake_disk_info() -> Vec { /// Clippy exception is fine because this supports sizes up to 2 EiB #[allow(clippy::cast_precision_loss)] #[must_use] -pub fn bytes_to_string(size: &u64) -> String { +pub fn bytes_to_string(size: u64) -> String { let units = "KMGTPEZY".chars(); let scale = 1024.0; - let mut size = *size as f64; + let mut size = size as f64; let mut suffix: Option = None; for u in units { if size < scale { diff --git a/src/system/diskpart.rs b/src/system/diskpart.rs index 554f607..9521982 100644 --- a/src/system/diskpart.rs +++ b/src/system/diskpart.rs @@ -49,7 +49,7 @@ pub fn get_disk_details(disk_id: usize, disk_size: u64, disk_details: Option<&st if let Some(details_str) = disk_details { details = String::from(details_str); } else { - let script = format!("select disk {}\r\ndetail disk", disk_id); + let script = format!("select disk {disk_id}\r\ndetail disk"); details = run_script(&script); }; @@ -85,7 +85,7 @@ pub fn get_partition_details( if let Some(details) = disk_details { contents = String::from(details); } else { - let script = format!("select disk {}\r\nlist partition", disk_id); + let script = format!("select disk {disk_id}\r\nlist partition"); contents = run_script(&script); }; for (_, [number, size]) in RE_LIS.captures_iter(&contents).map(|c| c.extract()) { diff --git a/src/tasks.rs b/src/tasks.rs index 1b10d97..50bca0d 100644 --- a/src/tasks.rs +++ b/src/tasks.rs @@ -82,9 +82,7 @@ impl Tasks { // Forward any actions to main app if let Ok(action) = self.task_rx.try_recv() { let result = self.action_tx.send(action.clone()); - if result.is_err() { - panic!("Failed to send Action: {action:?}"); - } + assert!(result.is_ok(), "Failed to send Action: {action:?}"); } // Check status of current task (if one is running). @@ -140,13 +138,12 @@ impl Tasks { } } Err(err) => { - Some(Action::Error(format!("Failed to run command: {:?}", err))) + Some(Action::Error(format!("Failed to run command: {err:?}"))) } } { let msg = format!("{:?}", &action); - if task_tx.send(action).is_err() { - panic!("Failed to send Action: {msg}"); - } + let result = task_tx.send(action); + assert!(result.is_ok(), "Failed to send Action: {msg}"); } })); } else { @@ -183,7 +180,7 @@ impl Tasks { self.handle = Some(thread::spawn(move || { let mut disks = disk_list_arc.lock().unwrap(); *disks = disk::get_disks(); - })) + })); } Task::Sleep => { self.handle = Some(thread::spawn(|| sleep(Duration::from_millis(250))));