From a05bf561cc6d96237f683ab0b3c782d6841974d9 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Wed, 28 Sep 2022 23:30:08 +0000 Subject: [PATCH 01/22] docs: readme.md updated --- README.md | 2 +- containerised/DOCKERHUB_README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index acae78e..ca3486f 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Published on Docker Hub, with images built for `linux/amd64`, `linux/arm64`, and `linux/arm/v6` -`docker run --rm -it --volume /var/run/docker.sock:/var/run/docker.sock:ro --pull=always mrjackwills/oxker` +`docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock:ro --pull=always mrjackwills/oxker` ## Download & install diff --git a/containerised/DOCKERHUB_README.md b/containerised/DOCKERHUB_README.md index 4339e01..bdc6af3 100644 --- a/containerised/DOCKERHUB_README.md +++ b/containerised/DOCKERHUB_README.md @@ -17,7 +17,7 @@ Images built for `linux/amd64`, `linux/arm64`, and `linux/arm/v6` -`docker run --rm -it --volume /var/run/docker.sock:/var/run/docker.sock:ro --pull=always mrjackwills/oxker` +`docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock:ro --pull=always mrjackwills/oxker` ## Help From 17dc604befac75cb9dc0311a0e43f9927fe0ca30 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Wed, 28 Sep 2022 23:32:15 +0000 Subject: [PATCH 02/22] refactor: async fn to just fn --- src/docker_data/mod.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/docker_data/mod.rs b/src/docker_data/mod.rs index feb6314..32e168c 100644 --- a/src/docker_data/mod.rs +++ b/src/docker_data/mod.rs @@ -150,7 +150,7 @@ impl DockerData { } /// Update all stats, spawn each container into own tokio::spawn thread - async fn update_all_container_stats(&mut self, all_ids: &[(bool, String)]) { + fn update_all_container_stats(&mut self, all_ids: &[(bool, String)]) { for (is_running, id) in all_ids.iter() { let docker = Arc::clone(&self.docker); let app_data = Arc::clone(&self.app_data); @@ -256,7 +256,7 @@ impl DockerData { } /// Update all logs, spawn each container into own tokio::spawn thread - async fn init_all_logs(&mut self, all_ids: &[(bool, String)]) { + fn init_all_logs(&mut self, all_ids: &[(bool, String)]) { for (_, id) in all_ids.iter() { let docker = Arc::clone(&self.docker); let timestamps = self.timestamps; @@ -293,7 +293,7 @@ impl DockerData { )) }); }; - self.update_all_container_stats(&all_ids).await; + self.update_all_container_stats(&all_ids); } /// Animate the loading icon @@ -319,10 +319,10 @@ impl DockerData { let loading_spin = self.loading_spin(loading_uuid).await; let all_ids = self.update_all_containers().await; - self.update_all_container_stats(&all_ids).await; + self.update_all_container_stats(&all_ids); // Maybe only do a single one at first? - self.init_all_logs(&all_ids).await; + self.init_all_logs(&all_ids); if all_ids.is_empty() { self.initialised = true; From 15597dbe6942ec053541398ce0e9dedc10a4d3ea Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Sat, 1 Oct 2022 17:43:20 +0000 Subject: [PATCH 03/22] chore: Update clap to v4 --- Cargo.toml | 4 ++-- src/parse_args/mod.rs | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 12c456f..79d4580 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ name = "oxker" version = "0.1.4" edition = "2021" authors = ["Jack Wills "] -description = "a simple tui to view & control docker containers" +description = "A simple tui to view & control docker containers" repository = "https://github.com/mrjackwills/oxker" homepage = "https://github.com/mrjackwills/oxker" license = "MIT" @@ -15,7 +15,7 @@ categories = ["command-line-utilities"] anyhow = "1.0" bollard = "0.13" cansi = "2.2" -clap={version="3.2", features = ["derive", "unicode"] } +clap={version="4.0", features = ["derive", "unicode", "color"] } crossterm = "0.25" futures-util = "0.3" parking_lot = {version= "0.12"} diff --git a/src/parse_args/mod.rs b/src/parse_args/mod.rs index a115aed..b7ece6b 100644 --- a/src/parse_args/mod.rs +++ b/src/parse_args/mod.rs @@ -3,29 +3,29 @@ use std::process; use clap::Parser; use tracing::error; -#[derive(Parser, Debug, Clone)] -#[clap(about, version, author)] - +#[derive(Parser, Debug, Clone, Copy)] +// #[command(help_template = FULL_TEMPLATE)] +#[command(version, about)] pub struct CliArgs { /// Docker update interval in ms, minimum 1, reccomended 500+ #[clap(short = 'd', value_name = "ms", default_value_t = 1000)] pub docker_interval: u32, - /// Don't draw gui - for debugging - mostly pointless - #[clap(short = 'g')] - pub gui: bool, - /// Remove timestamps from Docker logs #[clap(short = 't')] pub timestamp: bool, + /// Attempt to colorize the logs + #[clap(short = 'c', conflicts_with = "raw")] + pub color: bool, + /// Show raw logs, default is to remove ansi formatting #[clap(short = 'r', conflicts_with = "color")] pub raw: bool, - /// Attempt to colorize the logs - #[clap(short = 'c', conflicts_with = "raw")] - pub color: bool, + /// Don't draw gui - for debugging - mostly pointless + #[clap(short = 'g')] + pub gui: bool, } impl CliArgs { From e76878f424d72b943713ef84e95e25fada77d79e Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Sat, 1 Oct 2022 19:57:27 +0000 Subject: [PATCH 04/22] refactor: Impl Copy where able to --- .../workflows/create_release_and_build.yml | 6 +- CHANGELOG.md | 2 +- containerised/DOCKERHUB_README.md | 2 +- src/app_data/container_state.rs | 65 +++++++-------- src/app_data/mod.rs | 82 +++++++++++-------- src/app_error.rs | 2 +- src/docker_data/mod.rs | 6 +- src/input_handler/message.rs | 2 +- src/input_handler/mod.rs | 12 +-- src/main.rs | 18 ++-- src/ui/color_match.rs | 10 +-- src/ui/draw_blocks.rs | 28 ++++--- src/ui/gui_state.rs | 9 +- src/ui/mod.rs | 12 +-- 14 files changed, 138 insertions(+), 118 deletions(-) diff --git a/.github/workflows/create_release_and_build.yml b/.github/workflows/create_release_and_build.yml index 83df16e..a398b2c 100644 --- a/.github/workflows/create_release_and_build.yml +++ b/.github/workflows/create_release_and_build.yml @@ -46,7 +46,7 @@ jobs: uses: actions-rs/toolchain@v1 with: toolchain: stable - target: arm-unknown-linux-musleabihf + target: arm-unknown-linux-musleabihf override: true - uses: actions-rs/cargo@v1 with: @@ -61,7 +61,7 @@ jobs: uses: actions-rs/toolchain@v1 with: toolchain: stable - target: x86_64-pc-windows-gnu + target: x86_64-pc-windows-gnu override: true - uses: actions-rs/cargo@v1 with: @@ -86,7 +86,7 @@ jobs: run: | docker build --platform linux/arm/v6,linux/arm64,linux/amd64 \ -t ${{ secrets.DOCKERHUB_USERNAME }}/oxker:latest \ - --push \ + --push \ -f containerised/Dockerfile . - name: Release diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dfa2ef..4d7817b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -118,7 +118,7 @@ ### 2022-04-29 ### Features -+ allow toggling of mouse caputre, to select & copy text with mouse, closes #2, [aec184ea](https://github.com/mrjackwills/oxker/commit/aec184ea22b289e91942a4c3e6a415685884bc47), ++ allow toggling of mouse caputre, to select & copy text with mouse, closes #2, [aec184ea](https://github.com/mrjackwills/oxker/commit/aec184ea22b289e91942a4c3e6a415685884bc47), + show id column, [b10f9274](https://github.com/mrjackwills/oxker/commit/b10f927481c9e38a48c1d4b94e744ec48e8b6ba6), + draw_popup, using enum to draw in one of 9 areas, closes #6, [1017850a](https://github.com/mrjackwills/oxker/commit/1017850a6cc91328abc1127bdb117495f5e909d8), + use a message rx/sx for all docker commands, remove update loop, wait for update message from gui instead, [9b70fdfa](https://github.com/mrjackwills/oxker/commit/9b70fdfad7b38361ebee301bdc2545d3f0dfcf9e), diff --git a/containerised/DOCKERHUB_README.md b/containerised/DOCKERHUB_README.md index bdc6af3..d073b02 100644 --- a/containerised/DOCKERHUB_README.md +++ b/containerised/DOCKERHUB_README.md @@ -2,7 +2,7 @@

oxker

-
+
A simple tui to view & control docker containers

diff --git a/src/app_data/container_state.rs b/src/app_data/container_state.rs index 03c0c1c..bc334c2 100644 --- a/src/app_data/container_state.rs +++ b/src/app_data/container_state.rs @@ -7,7 +7,6 @@ use tui::{ use super::Header; - const ONE_KB: f64 = 1000.0; const ONE_MB: f64 = ONE_KB * 1000.0; const ONE_GB: f64 = ONE_MB * 1000.0; @@ -25,6 +24,7 @@ impl StatefulList { items, } } + pub fn end(&mut self) { let len = self.items.len(); if len > 0 { @@ -83,7 +83,7 @@ impl StatefulList { } /// States of the container -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd)] +#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd)] pub enum State { Dead, Exited, @@ -95,7 +95,7 @@ pub enum State { } impl State { - pub const fn get_color(&self) -> Color { + pub const fn get_color(self) -> Color { match self { Self::Running => Color::Green, Self::Removing => Color::LightRed, @@ -105,15 +105,15 @@ impl State { } } // Dirty way to create order for the state, rather than impl Ord - pub const fn order(&self) -> &'static str { + pub const fn order(self) -> u8 { match self { - Self::Running => "a", - Self::Paused => "b", - Self::Restarting => "c", - Self::Removing => "d", - Self::Exited => "e", - Self::Dead => "f", - Self::Unknown => "g", + Self::Running => 0, + Self::Paused => 1, + Self::Restarting => 2, + Self::Removing => 3, + Self::Exited => 4, + Self::Dead => 5, + Self::Unknown => 6, } } } @@ -162,7 +162,7 @@ impl fmt::Display for State { } /// Items for the container control list -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Copy)] pub enum DockerControls { Pause, Unpause, @@ -172,7 +172,7 @@ pub enum DockerControls { } impl DockerControls { - pub const fn get_color(&self) -> Color { + pub const fn get_color(self) -> Color { match self { Self::Start => Color::Green, Self::Stop => Color::Red, @@ -182,7 +182,8 @@ impl DockerControls { } } - pub fn gen_vec(state: &State) -> Vec { + /// Docker commands available depending on the containers state + pub fn gen_vec(state: State) -> Vec { match state { State::Dead | State::Exited => vec![Self::Start, Self::Restart], State::Paused => vec![Self::Unpause, Self::Stop], @@ -213,7 +214,7 @@ pub trait Stats { /// Struct for frequently updated CPU stats /// So can use custom display formatter /// Use trait Stats for use as generic in draw_chart function -#[derive(Clone, Debug)] +#[derive(Debug, Clone, Copy)] pub struct CpuStats { value: f64, } @@ -266,7 +267,7 @@ impl fmt::Display for CpuStats { /// Struct for frequently updated memory usage stats /// So can use custom display formatter /// Use trait Stats for use as generic in draw_chart function -#[derive(Clone, Debug, Eq)] +#[derive(Debug, Clone, Copy, Eq)] pub struct ByteStats { value: u64, } @@ -303,10 +304,9 @@ impl Stats for ByteStats { } } -// convert from bytes to kB, MB, GB etc +/// convert from bytes to kB, MB, GB etc impl fmt::Display for ByteStats { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // TODO these can be consts outside of this definition let as_f64 = self.value as f64; let p = match as_f64 { x if x >= ONE_GB => format!("{y:.2} GB", y = as_f64 / ONE_GB), @@ -318,6 +318,10 @@ impl fmt::Display for ByteStats { } } + +pub type MemTuple = (Vec<(f64, f64)>, ByteStats, State); +pub type CpuTuple = (Vec<(f64, f64)>, CpuStats, State); + /// Info for each container #[derive(Debug, Clone)] pub struct ContainerItem { @@ -336,13 +340,10 @@ pub struct ContainerItem { pub status: String, } -pub type MemTuple = (Vec<(f64, f64)>, ByteStats, State); -pub type CpuTuple = (Vec<(f64, f64)>, CpuStats, State); - impl ContainerItem { /// Create a new container item pub fn new(id: String, status: String, image: String, state: State, name: String) -> Self { - let mut docker_controls = StatefulList::new(DockerControls::gen_vec(&state)); + let mut docker_controls = StatefulList::new(DockerControls::gen_vec(state)); docker_controls.start(); Self { cpu_stats: VecDeque::with_capacity(60), @@ -361,18 +362,18 @@ impl ContainerItem { } } - /// Find the max value in the last 30 items in the cpu stats vec + /// Find the max value in the cpu stats VecDeque fn max_cpu_stats(&self) -> CpuStats { match self.cpu_stats.iter().max() { - Some(value) => value.clone(), + Some(value) => *value, None => CpuStats::new(0.0), } } - /// Find the max value in the last 30 items in the mem stats vec + /// Find the max value in the mem stats VecDeque fn max_mem_stats(&self) -> ByteStats { match self.mem_stats.iter().max() { - Some(value) => value.clone(), + Some(value) => *value, None => ByteStats::new(0), } } @@ -382,11 +383,11 @@ impl ContainerItem { self.cpu_stats .iter() .enumerate() - .map(|i| (i.0 as f64, i.1.value)) + .map(|i| (i.0 as f64, i.1.value as f64)) .collect::>() } - /// Convert mem stats into a vec for the charts function + /// Convert mem stats into a Vec for the charts function fn get_mem_dataset(&self) -> Vec<(f64, f64)> { self.mem_stats .iter() @@ -400,7 +401,7 @@ impl ContainerItem { ( self.get_cpu_dataset(), self.max_cpu_stats(), - self.state.clone(), + self.state, ) } @@ -409,7 +410,7 @@ impl ContainerItem { ( self.get_mem_dataset(), self.max_mem_stats(), - self.state.clone(), + self.state, ) } @@ -421,7 +422,7 @@ impl ContainerItem { } /// Container information panel headings + widths, for nice pretty formatting -#[derive(Debug)] +#[derive(Debug, Clone, Copy)] pub struct Columns { pub state: (Header, usize), pub status: (Header, usize), @@ -450,4 +451,4 @@ impl Columns { net_tx: (Header::Tx, 5), } } -} +} \ No newline at end of file diff --git a/src/app_data/mod.rs b/src/app_data/mod.rs index 6c7924d..a0ba4d9 100644 --- a/src/app_data/mod.rs +++ b/src/app_data/mod.rs @@ -9,7 +9,7 @@ use crate::{app_error::AppError, parse_args::CliArgs, ui::log_sanitizer}; pub use container_state::*; /// Global app_state, stored in an Arc -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct AppData { args: CliArgs, error: Option, @@ -20,13 +20,13 @@ pub struct AppData { sorted_by: Option<(Header, SortedOrder)>, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum SortedOrder { Asc, Desc, } -#[derive(Debug, Clone, PartialEq, Hash, Eq)] +#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)] pub enum Header { State, Status, @@ -58,20 +58,19 @@ impl fmt::Display for Header { } impl AppData { - pub fn get_sorted(&self) -> Option<(Header, SortedOrder)> { - self.sorted_by.clone() + pub const fn get_sorted(&self) -> Option<(Header, SortedOrder)> { + self.sorted_by } /// Change the sorted order, also set the selected container state to match new order pub fn set_sorted(&mut self, x: Option<(Header, SortedOrder)>) { self.sorted_by = x; - let id = self.get_selected_container_id(); self.sort_containers(); self.containers.state.select( self.containers .items .iter() - .position(|i| Some(i.id.clone()) == id), + .position(|i| Some(i.id.clone()) == self.get_selected_container_id()), ); } /// Generate a default app_state @@ -106,8 +105,7 @@ impl AppData { .state .selected() { - output = - Some(self.containers.items[index].docker_controls.items[control_index].clone()); + output = Some(self.containers.items[index].docker_controls.items[control_index]); } } output @@ -116,34 +114,42 @@ impl AppData { /// Change selected choice of docker commands of selected container pub fn docker_command_next(&mut self) { if let Some(index) = self.containers.state.selected() { - self.containers.items[index].docker_controls.next(); + if let Some(i) = self.containers.items.get_mut(index) { + i.docker_controls.next(); + } } } /// Change selected choice of docker commands of selected container pub fn docker_command_previous(&mut self) { if let Some(index) = self.containers.state.selected() { - self.containers.items[index].docker_controls.previous(); + if let Some(i) = self.containers.items.get_mut(index) { + i.docker_controls.previous(); + } } } /// Change selected choice of docker commands of selected container pub fn docker_command_start(&mut self) { if let Some(index) = self.containers.state.selected() { - self.containers.items[index].docker_controls.start(); + if let Some(i) = self.containers.items.get_mut(index) { + i.docker_controls.start(); + } } } /// Change selected choice of docker commands of selected container pub fn docker_command_end(&mut self) { if let Some(index) = self.containers.state.selected() { - self.containers.items[index].docker_controls.end(); + if let Some(i) = self.containers.items.get_mut(index) { + i.docker_controls.end(); + } } } /// return single app_state error - pub fn get_error(&self) -> Option { - self.error.clone() + pub const fn get_error(&self) -> Option { + self.error } /// remove single app_state error @@ -177,19 +183,19 @@ impl AppData { /// Sort the containers vec, based on a heading, either ascending or descending pub fn sort_containers(&mut self) { - if let Some((head, so)) = self.sorted_by.as_ref() { + if let Some((head, ord)) = self.sorted_by.as_ref() { match head { - Header::State => match so { + Header::State => match ord { SortedOrder::Desc => self .containers .items - .sort_by(|a, b| a.state.order().cmp(b.state.order())), + .sort_by(|a, b| a.state.order().cmp(&b.state.order())), SortedOrder::Asc => self .containers .items - .sort_by(|a, b| b.state.order().cmp(a.state.order())), + .sort_by(|a, b| b.state.order().cmp(&a.state.order())), }, - Header::Status => match so { + Header::Status => match ord { SortedOrder::Asc => self .containers .items @@ -199,7 +205,7 @@ impl AppData { .items .sort_by(|a, b| b.status.cmp(&a.status)), }, - Header::Cpu => match so { + Header::Cpu => match ord { SortedOrder::Asc => self .containers .items @@ -209,7 +215,7 @@ impl AppData { .items .sort_by(|a, b| b.cpu_stats.back().cmp(&a.cpu_stats.back())), }, - Header::Memory => match so { + Header::Memory => match ord { SortedOrder::Asc => self .containers .items @@ -219,25 +225,25 @@ impl AppData { .items .sort_by(|a, b| b.mem_stats.back().cmp(&a.mem_stats.back())), }, - Header::Id => match so { + Header::Id => match ord { SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.id.cmp(&b.id)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.id.cmp(&a.id)), }, - Header::Image => match so { + Header::Image => match ord { SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.image.cmp(&b.image)), SortedOrder::Desc => { self.containers.items.sort_by(|a, b| b.image.cmp(&a.image)); } }, - Header::Name => match so { + Header::Name => match ord { SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.name.cmp(&b.name)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.name.cmp(&a.name)), }, - Header::Rx => match so { + Header::Rx => match ord { SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.rx.cmp(&b.rx)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.rx.cmp(&a.rx)), }, - Header::Tx => match so { + Header::Tx => match ord { SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.tx.cmp(&b.tx)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.tx.cmp(&a.tx)), }, @@ -268,28 +274,36 @@ impl AppData { /// select next selected log line pub fn log_next(&mut self) { if let Some(index) = self.get_selected_log_index() { - self.containers.items[index].logs.next(); + if let Some(i) = self.containers.items.get_mut(index) { + i.logs.next(); + } } } /// select previous selected log line pub fn log_previous(&mut self) { if let Some(index) = self.get_selected_log_index() { - self.containers.items[index].logs.previous(); + if let Some(i) = self.containers.items.get_mut(index) { + i.logs.previous(); + } } } /// select last selected log line pub fn log_end(&mut self) { if let Some(index) = self.get_selected_log_index() { - self.containers.items[index].logs.end(); + if let Some(i) = self.containers.items.get_mut(index) { + i.logs.end(); + } } } /// select first selected log line pub fn log_start(&mut self) { if let Some(index) = self.get_selected_log_index() { - self.containers.items[index].logs.start(); + if let Some(i) = self.containers.items.get_mut(index) { + i.logs.start(); + } } } @@ -470,7 +484,7 @@ impl AppData { current_container.status = status; }; if current_container.state != state { - current_container.docker_controls.items = DockerControls::gen_vec(&state); + current_container.docker_controls.items = DockerControls::gen_vec(state); // Update the list state, needs to be None if the gen_vec returns an empty vec match state { @@ -488,7 +502,7 @@ impl AppData { }; } else { // limit image name to 64 chars? - // let mut container = ContainerItem::new(id.clone(), status, image.chars().into_iter().take(64).collect(), state, name); + // let mut container = ContainerItem::new(id.clone(), status, image.chars().into_iter().take(64).collect(), state, name); let mut container = ContainerItem::new(id.clone(), status, image, state, name); container.logs.end(); self.containers.items.push(container); @@ -511,7 +525,7 @@ impl AppData { let lines = if color { log_sanitizer::colorize_logs(i) } else if raw { - log_sanitizer::raw(i.clone()) + log_sanitizer::raw(i) } else { log_sanitizer::remove_ansi(i) }; diff --git a/src/app_error.rs b/src/app_error.rs index b1bcd83..385b227 100644 --- a/src/app_error.rs +++ b/src/app_error.rs @@ -3,7 +3,7 @@ use std::fmt; /// app errors to set in global state #[allow(unused)] -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Copy)] pub enum AppError { DockerConnect, DockerInterval, diff --git a/src/docker_data/mod.rs b/src/docker_data/mod.rs index 32e168c..4547f11 100644 --- a/src/docker_data/mod.rs +++ b/src/docker_data/mod.rs @@ -24,7 +24,7 @@ use crate::{ mod message; pub use message::DockerMessage; -#[derive(Debug, Hash, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Eq, Hash, PartialEq)] enum SpawnId { Stats((String, Binate)), Log(String), @@ -33,7 +33,7 @@ enum SpawnId { /// Cpu & Mem stats take twice as long as the update interval to get a value, so will have two being executed at the same time /// SpawnId::Stats takes container_id and binate value to enable both cycles of the same container_id to be inserted into the hashmap /// Binate value is toggled when all join handles have been spawned off -#[derive(Debug, Hash, Clone, PartialEq, Eq, Copy)] +#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)] enum Binate { One, Two, @@ -61,7 +61,7 @@ pub struct DockerData { } impl DockerData { - /// Use docker stats for work out current cpu usage + /// Use docker stats to caluclate current cpu usage fn calculate_usage(stats: &Stats) -> f64 { let mut cpu_percentage = 0.0; let previous_cpu = stats.precpu_stats.cpu_usage.total_usage; diff --git a/src/input_handler/message.rs b/src/input_handler/message.rs index cbefb49..f87e2e9 100644 --- a/src/input_handler/message.rs +++ b/src/input_handler/message.rs @@ -1,6 +1,6 @@ use crossterm::event::{KeyCode, MouseEvent}; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Copy)] pub enum InputMessages { ButtonPress(KeyCode), MouseEvent(MouseEvent), diff --git a/src/input_handler/mod.rs b/src/input_handler/mod.rs index 731b005..b253beb 100644 --- a/src/input_handler/mod.rs +++ b/src/input_handler/mod.rs @@ -77,8 +77,8 @@ impl InputHandler { } } - /// Mouse button - fn m_button(&mut self) { + /// Toggle the mouse capture (via input of the 'm' key) + fn m_key(&mut self) { if self.mouse_capture { match execute!(std::io::stdout(), DisableMouseCapture) { Ok(_) => self @@ -118,7 +118,7 @@ impl InputHandler { /// Sort containers based on a given header, switch asc to desc if already sorted, else always desc fn sort(&self, header: Header) { - let mut output = Some((header.clone(), SortedOrder::Desc)); + let mut output = Some((header, SortedOrder::Desc)); let mut locked_data = self.app_data.lock(); if let Some((h, order)) = locked_data.get_sorted().as_ref() { if &SortedOrder::Desc == order && h == &header { @@ -128,7 +128,7 @@ impl InputHandler { locked_data.set_sorted(output); } - /// Send a quit message to docker, to abort all spawns, if error, quit here instead + /// Send a quit message to docker, to abort all spawns, if an error is return, set is_running to false here instead async fn quit(&self) { match self.docker_sender.send(DockerMessage::Quit).await { Ok(_) => (), @@ -154,7 +154,7 @@ impl InputHandler { match key_code { KeyCode::Char('q' | 'Q') => self.quit().await, KeyCode::Char('h' | 'H') => self.gui_state.lock().show_help = false, - KeyCode::Char('m' | 'M') => self.m_button(), + KeyCode::Char('m' | 'M') => self.m_key(), _ => (), } } else { @@ -171,7 +171,7 @@ impl InputHandler { KeyCode::Char('9') => self.sort(Header::Tx), KeyCode::Char('q' | 'Q') => self.quit().await, KeyCode::Char('h' | 'H') => self.gui_state.lock().show_help = true, - KeyCode::Char('m' | 'M') => self.m_button(), + KeyCode::Char('m' | 'M') => self.m_key(), KeyCode::Tab => { // Skip control panel if no containers, could be refactored let has_containers = self.app_data.lock().get_container_len() == 0; diff --git a/src/main.rs b/src/main.rs index f4b67b0..b39db48 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,27 +35,24 @@ fn setup_tracing() { async fn main() { setup_tracing(); let args = CliArgs::new(); - let app_data = Arc::new(Mutex::new(AppData::default(args.clone()))); + let app_data = Arc::new(Mutex::new(AppData::default(args))); let gui_state = Arc::new(Mutex::new(GuiState::default())); let is_running = Arc::new(AtomicBool::new(true)); - let docker_args = args.clone(); let docker_app_data = Arc::clone(&app_data); let docker_gui_state = Arc::clone(&gui_state); let (docker_sx, docker_rx) = tokio::sync::mpsc::channel(16); // Create docker daemon handler, and only spawn up the docker data handler if ping returns non-error - match Docker::connect_with_socket_defaults() { Ok(docker) => { - let docker = Arc::new(docker); - match docker.ping().await { - Ok(_) => { - let docker = Arc::clone(&docker); + match docker.ping().await { + Ok(_) => { + let docker = Arc::new(docker); let is_running = Arc::clone(&is_running); tokio::spawn(DockerData::init( - docker_args, + args, docker_app_data, docker, docker_gui_state, @@ -85,7 +82,7 @@ async fn main() { input_is_running, )); - // Debug mode for testing, mostly pointless, doesn't take terminal nor draw gui + if args.gui { let update_duration = std::time::Duration::from_millis(u64::from(args.docker_interval)); create_ui( @@ -99,8 +96,9 @@ async fn main() { .await .unwrap_or(()); } else { + // Debug mode for testing, mostly pointless, doesn't take terminal nor draw gui + // TODO this needs to be improved to display something actually useful loop { - // TODO this needs to be improved to display something useful info!("in debug mode"); tokio::time::sleep(std::time::Duration::from_millis(5000)).await; } diff --git a/src/ui/color_match.rs b/src/ui/color_match.rs index a95dc88..5c423f9 100644 --- a/src/ui/color_match.rs +++ b/src/ui/color_match.rs @@ -7,7 +7,7 @@ pub mod log_sanitizer { }; /// Attempt to colorize the given string to tui-rs standards - pub fn colorize_logs(input: &str) -> Vec> { + pub fn colorize_logs<'a>(input: &str) -> Vec> { vec![Spans::from( categorise_text(input) .into_iter() @@ -40,17 +40,17 @@ pub mod log_sanitizer { } /// Remove all ansi formatting from a given string and create tui-rs spans - pub fn remove_ansi(input: &str) -> Vec> { + pub fn remove_ansi<'a>(input: &str) -> Vec> { let mut output = String::from(""); for i in categorise_text(input) { output.push_str(i.text); } - raw(output) + raw(&output) } /// create tui-rs spans that exactly match the given strings - pub fn raw(input: String) -> Vec> { - vec![Spans::from(Span::raw(input))] + pub fn raw<'a>(input: &str) -> Vec> { + vec![Spans::from(Span::raw(input.to_owned()))] } /// Change from ansi to tui colors diff --git a/src/ui/draw_blocks.rs b/src/ui/draw_blocks.rs index 1573a37..26e56ac 100644 --- a/src/ui/draw_blocks.rs +++ b/src/ui/draw_blocks.rs @@ -39,6 +39,8 @@ const REPO: &str = env!("CARGO_PKG_REPOSITORY"); const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION"); const ORANGE: Color = Color::Rgb(255, 178, 36); const MARGIN: &str = " "; +const ARROW: &str = "▶ "; +const CIRCLE: &str ="⚪ "; /// Generate block, add a border if is the selected panel, /// add custom title based on state of each panel @@ -99,7 +101,7 @@ pub fn commands( let items = List::new(items) .block(block) .highlight_style(Style::default().add_modifier(Modifier::BOLD)) - .highlight_symbol("▶ "); + .highlight_symbol(ARROW); f.render_stateful_widget( items, @@ -201,7 +203,7 @@ pub fn containers( let items = List::new(items) .block(block) .highlight_style(Style::default().add_modifier(Modifier::BOLD)) - .highlight_symbol("⚪ "); + .highlight_symbol(CIRCLE); f.render_stateful_widget(items, area, &mut app_data.lock().containers.state); } @@ -237,7 +239,7 @@ pub fn logs( let items = List::new(items) .block(block) - .highlight_symbol("▶ ") + .highlight_symbol(ARROW) .highlight_style(Style::default().add_modifier(Modifier::BOLD)); f.render_stateful_widget( items, @@ -281,8 +283,8 @@ pub fn chart( .data(&mem.0)]; let cpu_stats = CpuStats::new(cpu.0.last().map_or(0.00, |f| f.1)); let mem_stats = ByteStats::new(mem.0.last().map_or(0, |f| f.1 as u64)); - let cpu_chart = make_chart(&cpu.2, "cpu", cpu_dataset, &cpu_stats, &cpu.1); - let mem_chart = make_chart(&mem.2, "memory", mem_dataset, &mem_stats, &mem.1); + let cpu_chart = make_chart(cpu.2, "cpu", cpu_dataset, &cpu_stats, &cpu.1); + let mem_chart = make_chart(mem.2, "memory", mem_dataset, &mem_stats, &mem.1); f.render_widget(cpu_chart, area[0]); f.render_widget(mem_chart, area[1]); @@ -292,7 +294,7 @@ pub fn chart( /// Create charts fn make_chart<'a, T: Stats + Display>( - state: &State, + state: State, name: &'a str, dataset: Vec>, current: &'a T, @@ -340,14 +342,14 @@ fn make_chart<'a, T: Stats + Display>( ) } -/// Draw heading bar at top of program, always visible +/// Draw heading bar at top of program, always visible pub fn heading_bar( area: Rect, columns: &Columns, f: &mut Frame<'_, B>, has_containers: bool, loading_icon: &str, - sorted_by: &Option<(Header, SortedOrder)>, + sorted_by: Option<(Header, SortedOrder)>, gui_state: &Arc>, ) { let block = || Block::default().style(Style::default().bg(Color::Magenta).fg(Color::Black)); @@ -412,7 +414,7 @@ pub fn heading_bar( (status, count) }; - // Meta data for iterate over to create blocks and correct widths + // Meta data to iterate over to create blocks with correct widths let header_meta = [ (Header::State, columns.state.1), (Header::Status, columns.status.1), @@ -429,7 +431,7 @@ pub fn heading_bar( .iter() .map(|i| { let header_block = gen_header(&i.0, i.1); - (header_block.0, i.0.clone(), Constraint::Max(header_block.1)) + (header_block.0, i.0, Constraint::Max(header_block.1)) }) .collect::>(); @@ -469,11 +471,12 @@ pub fn heading_bar( .block(block()) .alignment(Alignment::Right); + // If no containers, don't display the headers, could maybe do this first? let index = if has_containers { 1 } else { 0 }; f.render_widget(paragraph, split_bar[index]); } -/// From a given &String, return the maximum number of chars on a single line +/// From a given &str, return the maximum number of chars on a single line fn max_line_width(text: &str) -> usize { let mut max_line_width = 0; text.lines().into_iter().for_each(|line| { @@ -486,6 +489,7 @@ fn max_line_width(text: &str) -> usize { } /// Draw the help box in the centre of the screen +/// TODO this is message, should make every line it's own renderable span pub fn help_box(f: &mut Frame<'_, B>) { let title = format!(" {} ", VERSION); @@ -564,7 +568,7 @@ pub fn help_box(f: &mut Frame<'_, B>) { } /// Draw an error popup over whole screen -pub fn error(f: &mut Frame<'_, B>, error: &AppError, seconds: Option) { +pub fn error(f: &mut Frame<'_, B>, error: AppError, seconds: Option) { let block = Block::default() .title(" Error ") .border_type(BorderType::Rounded) diff --git a/src/ui/gui_state.rs b/src/ui/gui_state.rs index 1239e20..b4c586f 100644 --- a/src/ui/gui_state.rs +++ b/src/ui/gui_state.rs @@ -7,7 +7,7 @@ use uuid::Uuid; use crate::app_data::Header; -#[derive(Debug, PartialEq, std::hash::Hash, std::cmp::Eq, Clone, Copy)] +#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)] pub enum SelectablePanel { Containers, Commands, @@ -38,6 +38,7 @@ impl SelectablePanel { } } +#[derive(Debug, Copy, Clone)] pub enum Region { Panel(SelectablePanel), Header(Header), @@ -72,7 +73,7 @@ impl BoxLocation { } } - // Should combine and just return a tuple? + // Should combine with get_vertical_constraints and just return a tuple of (vc, hc)? pub const fn get_horizontal_constraints( self, blank_vertical: u16, @@ -221,7 +222,7 @@ impl GuiState { .filter(|i| i.1.intersects(rect)) .collect::>() .get(0) - .map(|data| data.0.clone()) + .map(|data| *data.0) } /// Insert, or updates header area panel into heading_map @@ -260,7 +261,7 @@ impl GuiState { pub fn get_loading(&mut self) -> String { if self.is_loading.is_empty() { String::from(" ") - } else { + } else { self.loading_icon.to_string() } } diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 3f5fc07..35a8b28 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -93,7 +93,7 @@ async fn run_app( break; } if terminal - .draw(|f| draw_blocks::error(f, &AppError::DockerConnect, Some(seconds))) + .draw(|f| draw_blocks::error(f, AppError::DockerConnect, Some(seconds))) .is_err() { return Err(AppError::Terminal); @@ -104,9 +104,11 @@ async fn run_app( } else { let mut now = Instant::now(); loop { - if terminal.draw(|f| ui(f, &app_data, &gui_state)).is_err() { - return Err(AppError::Terminal); + if terminal.draw(|f| ui(f, &app_data, &gui_state)).is_err() { + return Err(AppError::Terminal); } + // TODO could only draw if in gui mode, that way all inputs & docker commands will run, and can just trace!("{event"}) all over the place + // refactor this into own function, so can be called without drawing to the terminal if crossterm::event::poll(input_poll_rate).unwrap_or(false) { if let Ok(event) = event::read() { if let Event::Key(key) = event { @@ -213,7 +215,7 @@ fn ui( f, has_containers, &loading_icon, - &sorted_by, + sorted_by, gui_state, ); @@ -233,6 +235,6 @@ fn ui( if let Some(error) = has_error { app_data.lock().show_error = true; - draw_blocks::error(f, &error, None); + draw_blocks::error(f, error, None); } } From 1dbb91438777df62394dc1e1b2d7e0946ca85b50 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Sat, 1 Oct 2022 20:05:34 +0000 Subject: [PATCH 05/22] docs: changelog --- CHANGELOG.md | 13 +++++++++++++ src/docker_data/message.rs | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d7817b..38933d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,16 @@ + +### Chores ++ Update clap to v4, [15597dbe6942ec053541398ce0e9dedc10a4d3ea] + +### Docs ++ readme.md updated, [a05bf561cc6d96237f683ab0b3c782d6841974d9] + +### Refactors ++ Impl Copy where able to, [e76878f424d72b943713ef84e95e25fada77d79e] ++ async fn to just fn, [17dc604befac75cb9dc0311a0e43f9927fe0ca30] + + + # v0.1.4 ### 2022-09-07 diff --git a/src/docker_data/message.rs b/src/docker_data/message.rs index a730830..a2c51cc 100644 --- a/src/docker_data/message.rs +++ b/src/docker_data/message.rs @@ -7,4 +7,4 @@ pub enum DockerMessage { Unpause(String), Stop(String), Quit, -} +} \ No newline at end of file From 6731002ee42c9460042c2c38aff5101b1bcebbe6 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Sat, 1 Oct 2022 21:02:38 +0000 Subject: [PATCH 06/22] refactor: remove pointless clone()'s & variable declarations --- src/app_data/container_state.rs | 17 +++------ src/docker_data/message.rs | 2 +- src/docker_data/mod.rs | 61 +++++++++++++++++---------------- src/main.rs | 35 +++++++++---------- src/parse_args/mod.rs | 2 +- src/ui/draw_blocks.rs | 4 +-- src/ui/mod.rs | 8 ++--- 7 files changed, 59 insertions(+), 70 deletions(-) diff --git a/src/app_data/container_state.rs b/src/app_data/container_state.rs index bc334c2..3734b34 100644 --- a/src/app_data/container_state.rs +++ b/src/app_data/container_state.rs @@ -182,7 +182,7 @@ impl DockerControls { } } - /// Docker commands available depending on the containers state + /// Docker commands available depending on the containers state pub fn gen_vec(state: State) -> Vec { match state { State::Dead | State::Exited => vec![Self::Start, Self::Restart], @@ -318,7 +318,6 @@ impl fmt::Display for ByteStats { } } - pub type MemTuple = (Vec<(f64, f64)>, ByteStats, State); pub type CpuTuple = (Vec<(f64, f64)>, CpuStats, State); @@ -398,20 +397,12 @@ impl ContainerItem { /// Get all cpu chart data fn get_cpu_chart_data(&self) -> CpuTuple { - ( - self.get_cpu_dataset(), - self.max_cpu_stats(), - self.state, - ) + (self.get_cpu_dataset(), self.max_cpu_stats(), self.state) } /// Get all mem chart data fn get_mem_chart_data(&self) -> MemTuple { - ( - self.get_mem_dataset(), - self.max_mem_stats(), - self.state, - ) + (self.get_mem_dataset(), self.max_mem_stats(), self.state) } /// Get chart info for cpu & memory in one function @@ -451,4 +442,4 @@ impl Columns { net_tx: (Header::Tx, 5), } } -} \ No newline at end of file +} diff --git a/src/docker_data/message.rs b/src/docker_data/message.rs index a2c51cc..a730830 100644 --- a/src/docker_data/message.rs +++ b/src/docker_data/message.rs @@ -7,4 +7,4 @@ pub enum DockerMessage { Unpause(String), Stop(String), Quit, -} \ No newline at end of file +} diff --git a/src/docker_data/mod.rs b/src/docker_data/mod.rs index 4547f11..c0fcd41 100644 --- a/src/docker_data/mod.rs +++ b/src/docker_data/mod.rs @@ -33,6 +33,7 @@ enum SpawnId { /// Cpu & Mem stats take twice as long as the update interval to get a value, so will have two being executed at the same time /// SpawnId::Stats takes container_id and binate value to enable both cycles of the same container_id to be inserted into the hashmap /// Binate value is toggled when all join handles have been spawned off +/// Also effectively means that if the docker_update interval minimum will be 1000ms #[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)] enum Binate { One, @@ -113,22 +114,20 @@ impl DockerData { let mem_stat = stats.memory_stats.usage.unwrap_or(0); let mem_limit = stats.memory_stats.limit.unwrap_or(0); - let some_key = stats + let op_key = stats .networks .as_ref() .and_then(|networks| networks.keys().next().cloned()); let cpu_stats = Self::calculate_usage(&stats); - let no_bytes = || (0, 0); - - let (rx, tx) = if let Some(key) = some_key { + let (rx, tx) = if let Some(key) = op_key { match stats.networks.unwrap_or_default().get(&key) { Some(data) => (data.rx_bytes, data.tx_bytes), - None => no_bytes(), + None => (0, 0), } } else { - no_bytes() + (0, 0) }; if is_running { @@ -155,8 +154,6 @@ impl DockerData { let docker = Arc::clone(&self.docker); let app_data = Arc::clone(&self.app_data); let spawns = Arc::clone(&self.spawns); - let id = id.clone(); - let key = SpawnId::Stats((id.clone(), self.binate)); let spawn_key = key.clone(); @@ -228,19 +225,18 @@ impl DockerData { docker: Arc, id: String, timestamps: bool, - since: i64, + since: u64, app_data: Arc>, spawns: Arc>>>, ) { let options = Some(LogsOptions:: { stdout: true, timestamps, - since, + since: since as i64, ..Default::default() }); let mut logs = docker.logs(&id, options); - let mut output = vec![]; while let Some(value) = logs.next().await { @@ -259,15 +255,18 @@ impl DockerData { fn init_all_logs(&mut self, all_ids: &[(bool, String)]) { for (_, id) in all_ids.iter() { let docker = Arc::clone(&self.docker); - let timestamps = self.timestamps; - let id = id.clone(); let app_data = Arc::clone(&self.app_data); let spawns = Arc::clone(&self.spawns); let key = SpawnId::Log(id.clone()); self.spawns.lock().insert( key, tokio::spawn(Self::update_log( - docker, id, timestamps, 0, app_data, spawns, + docker, + id.clone(), + self.timestamps, + 0, + app_data, + spawns, )), ); } @@ -278,20 +277,24 @@ impl DockerData { let all_ids = self.update_all_containers().await; let optional_index = self.app_data.lock().get_selected_log_index(); if let Some(index) = optional_index { - // this could be neater - let id = self.app_data.lock().containers.items[index].id.clone(); - let key = SpawnId::Log(id.clone()); - - self.spawns.lock().entry(key).or_insert_with(|| { - let since = self.app_data.lock().containers.items[index].last_updated as i64; - let docker = Arc::clone(&self.docker); - let timestamps = self.timestamps; - let app_data = Arc::clone(&self.app_data); - let spawns = Arc::clone(&self.spawns); - tokio::spawn(Self::update_log( - docker, id, timestamps, since, app_data, spawns, - )) - }); + if let Some(container) = self.app_data.lock().containers.items.get(index) { + self.spawns + .lock() + .entry(SpawnId::Log(container.id.clone())) + .or_insert_with(|| { + let docker = Arc::clone(&self.docker); + let app_data = Arc::clone(&self.app_data); + let spawns = Arc::clone(&self.spawns); + tokio::spawn(Self::update_log( + docker, + container.id.clone(), + self.timestamps, + container.last_updated, + app_data, + spawns, + )) + }); + } }; self.update_all_container_stats(&all_ids); } @@ -391,8 +394,6 @@ impl DockerData { .lock() .set_error(AppError::DockerCommand(DockerControls::Unpause)); }; - // loading sping take uuid to remove - // stop_loading_sping(uuid) self.stop_loading_spin(&loading_spin, loading_uuid); self.update_everything().await; } diff --git a/src/main.rs b/src/main.rs index b39db48..ae69b15 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,23 +46,21 @@ async fn main() { // Create docker daemon handler, and only spawn up the docker data handler if ping returns non-error match Docker::connect_with_socket_defaults() { - Ok(docker) => { - match docker.ping().await { - Ok(_) => { - let docker = Arc::new(docker); - let is_running = Arc::clone(&is_running); - tokio::spawn(DockerData::init( - args, - docker_app_data, - docker, - docker_gui_state, - docker_rx, - is_running, - )); - } - Err(_) => app_data.lock().set_error(AppError::DockerConnect), + Ok(docker) => match docker.ping().await { + Ok(_) => { + let docker = Arc::new(docker); + let is_running = Arc::clone(&is_running); + tokio::spawn(DockerData::init( + args, + docker_app_data, + docker, + docker_gui_state, + docker_rx, + is_running, + )); } - } + Err(_) => app_data.lock().set_error(AppError::DockerConnect), + }, Err(_) => app_data.lock().set_error(AppError::DockerConnect), } let input_app_data = Arc::clone(&app_data); @@ -82,7 +80,6 @@ async fn main() { input_is_running, )); - if args.gui { let update_duration = std::time::Duration::from_millis(u64::from(args.docker_interval)); create_ui( @@ -96,8 +93,8 @@ async fn main() { .await .unwrap_or(()); } else { - // Debug mode for testing, mostly pointless, doesn't take terminal nor draw gui - // TODO this needs to be improved to display something actually useful + // Debug mode for testing, mostly pointless, doesn't take terminal nor draw gui + // TODO this needs to be improved to display something actually useful loop { info!("in debug mode"); tokio::time::sleep(std::time::Duration::from_millis(5000)).await; diff --git a/src/parse_args/mod.rs b/src/parse_args/mod.rs index b7ece6b..6a4e13f 100644 --- a/src/parse_args/mod.rs +++ b/src/parse_args/mod.rs @@ -7,7 +7,7 @@ use tracing::error; // #[command(help_template = FULL_TEMPLATE)] #[command(version, about)] pub struct CliArgs { - /// Docker update interval in ms, minimum 1, reccomended 500+ + /// Docker update interval in ms, minimum effectively 1000 #[clap(short = 'd', value_name = "ms", default_value_t = 1000)] pub docker_interval: u32, diff --git a/src/ui/draw_blocks.rs b/src/ui/draw_blocks.rs index 26e56ac..2f1a847 100644 --- a/src/ui/draw_blocks.rs +++ b/src/ui/draw_blocks.rs @@ -40,7 +40,7 @@ const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION"); const ORANGE: Color = Color::Rgb(255, 178, 36); const MARGIN: &str = " "; const ARROW: &str = "▶ "; -const CIRCLE: &str ="⚪ "; +const CIRCLE: &str = "⚪ "; /// Generate block, add a border if is the selected panel, /// add custom title based on state of each panel @@ -471,7 +471,7 @@ pub fn heading_bar( .block(block()) .alignment(Alignment::Right); - // If no containers, don't display the headers, could maybe do this first? + // If no containers, don't display the headers, could maybe do this first? let index = if has_containers { 1 } else { 0 }; f.render_widget(paragraph, split_bar[index]); } diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 35a8b28..e2dc511 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -104,11 +104,11 @@ async fn run_app( } else { let mut now = Instant::now(); loop { - if terminal.draw(|f| ui(f, &app_data, &gui_state)).is_err() { - return Err(AppError::Terminal); + if terminal.draw(|f| ui(f, &app_data, &gui_state)).is_err() { + return Err(AppError::Terminal); } - // TODO could only draw if in gui mode, that way all inputs & docker commands will run, and can just trace!("{event"}) all over the place - // refactor this into own function, so can be called without drawing to the terminal + // TODO could only draw if in gui mode, that way all inputs & docker commands will run, and can just trace!("{event"}) all over the place + // refactor this into own function, so can be called without drawing to the terminal if crossterm::event::poll(input_poll_rate).unwrap_or(false) { if let Ok(event) = event::read() { if let Event::Key(key) = event { From 41cbb84f2896f8be2c37eba87e390d998aff7382 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Sat, 1 Oct 2022 23:27:38 +0000 Subject: [PATCH 07/22] feat: use ContainerId new_type --- src/app_data/container_state.rs | 43 +++++++++++++++++++++++++++++++-- src/app_data/mod.rs | 33 +++++++++++-------------- src/docker_data/message.rs | 12 +++++---- src/docker_data/mod.rs | 34 +++++++++++++------------- src/input_handler/mod.rs | 1 + 5 files changed, 80 insertions(+), 43 deletions(-) diff --git a/src/app_data/container_state.rs b/src/app_data/container_state.rs index 3734b34..6e363dd 100644 --- a/src/app_data/container_state.rs +++ b/src/app_data/container_state.rs @@ -11,6 +11,45 @@ const ONE_KB: f64 = 1000.0; const ONE_MB: f64 = ONE_KB * 1000.0; const ONE_GB: f64 = ONE_MB * 1000.0; +#[derive(Debug, Clone, Eq, Hash, PartialEq)] +pub struct ContainerId(String); + +impl From for ContainerId { + fn from(x: String) -> Self { + Self(x) + } +} + +impl From<&String> for ContainerId { + fn from(x: &String) -> Self { + Self(x.clone()) + } +} + +impl From<&str> for ContainerId { + fn from(x: &str) -> Self { + Self(x.to_owned()) + } +} + +impl ContainerId { + pub fn get(&self) -> &str { + self.0.as_str() + } +} + +impl Ord for ContainerId { + fn cmp(&self, other: &Self) -> Ordering { + self.0.cmp(&other.0) + } +} + +impl PartialOrd for ContainerId { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + #[derive(Debug, Clone)] pub struct StatefulList { pub state: ListState, @@ -326,7 +365,7 @@ pub type CpuTuple = (Vec<(f64, f64)>, CpuStats, State); pub struct ContainerItem { pub cpu_stats: VecDeque, pub docker_controls: StatefulList, - pub id: String, + pub id: ContainerId, pub image: String, pub last_updated: u64, pub logs: StatefulList>, @@ -341,7 +380,7 @@ pub struct ContainerItem { impl ContainerItem { /// Create a new container item - pub fn new(id: String, status: String, image: String, state: State, name: String) -> Self { + pub fn new(id: ContainerId, status: String, image: String, state: State, name: String) -> Self { let mut docker_controls = StatefulList::new(DockerControls::gen_vec(state)); docker_controls.start(); Self { diff --git a/src/app_data/mod.rs b/src/app_data/mod.rs index a0ba4d9..f1a8f7a 100644 --- a/src/app_data/mod.rs +++ b/src/app_data/mod.rs @@ -163,20 +163,14 @@ impl AppData { } /// Find the id of the currently selected container. - /// If any containers on system, will always return a string. + /// If any containers on system, will always return a container id /// Only returns None when no containers found. - pub fn get_selected_container_id(&self) -> Option { + pub fn get_selected_container_id(&self) -> Option { let mut output = None; if let Some(index) = self.containers.state.selected() { - let id = self - .containers - .items - .iter() - .skip(index) - .take(1) - .map(|i| i.id.clone()) - .collect::(); - output = Some(id); + if let Some(x) = self.containers.items.get(index) { + output = Some(x.id.clone()); + } } output } @@ -307,7 +301,7 @@ impl AppData { } } - pub fn initialised(&mut self, all_ids: &[(bool, String)]) -> bool { + pub fn initialised(&mut self, all_ids: &[(bool, ContainerId)]) -> bool { let count_is_running = all_ids.iter().filter(|i| i.0).count(); let number_with_cpu_status = self .containers @@ -379,7 +373,7 @@ impl AppData { } /// Get all containers ids - pub fn get_all_ids(&self) -> Vec { + pub fn get_all_ids(&self) -> Vec { self.containers .items .iter() @@ -388,14 +382,14 @@ impl AppData { } /// find container given id - fn get_container_by_id(&mut self, id: &str) -> Option<&mut ContainerItem> { - self.containers.items.iter_mut().find(|i| i.id == id) + fn get_container_by_id(&mut self, id: &ContainerId) -> Option<&mut ContainerItem> { + self.containers.items.iter_mut().find(|i| &i.id == id) } /// Update container mem, cpu, & network stats, in single function so only need to call .lock() once pub fn update_stats( &mut self, - id: &str, + id: &ContainerId, cpu_stat: Option, mem_stat: Option, mem_limit: u64, @@ -435,7 +429,7 @@ impl AppData { if !containers .iter() .filter_map(|i| i.id.as_ref()) - .any(|x| x == id) + .any(|x| ContainerId::from(x) == id.clone()) { // If removed container is currently selected, then change selected to previous // This will default to 0 in any edge cases @@ -476,7 +470,8 @@ impl AppData { .as_ref() .map_or("".to_owned(), std::clone::Clone::clone); - if let Some(current_container) = self.get_container_by_id(id) { + let id = ContainerId::from(id.as_str()); + if let Some(current_container) = self.get_container_by_id(&id) { if current_container.name != name { current_container.name = name; }; @@ -512,7 +507,7 @@ impl AppData { } /// update logs of a given container, based on id - pub fn update_log_by_id(&mut self, output: &[String], id: &str) { + pub fn update_log_by_id(&mut self, output: &[String], id: &ContainerId) { let tz = Self::get_systemtime(); let color = self.args.color; let raw = self.args.raw; diff --git a/src/docker_data/message.rs b/src/docker_data/message.rs index a730830..f7de6f5 100644 --- a/src/docker_data/message.rs +++ b/src/docker_data/message.rs @@ -1,10 +1,12 @@ +use crate::app_data::ContainerId; + #[derive(Debug, Clone)] pub enum DockerMessage { Update, - Start(String), - Restart(String), - Pause(String), - Unpause(String), - Stop(String), + Start(ContainerId), + Restart(ContainerId), + Pause(ContainerId), + Unpause(ContainerId), + Stop(ContainerId), Quit, } diff --git a/src/docker_data/mod.rs b/src/docker_data/mod.rs index c0fcd41..6744f4a 100644 --- a/src/docker_data/mod.rs +++ b/src/docker_data/mod.rs @@ -16,7 +16,7 @@ use tokio::{sync::mpsc::Receiver, task::JoinHandle}; use uuid::Uuid; use crate::{ - app_data::{AppData, DockerControls}, + app_data::{AppData, ContainerId, DockerControls}, app_error::AppError, parse_args::CliArgs, ui::GuiState, @@ -26,8 +26,8 @@ pub use message::DockerMessage; #[derive(Debug, Clone, Eq, Hash, PartialEq)] enum SpawnId { - Stats((String, Binate)), - Log(String), + Stats((ContainerId, Binate)), + Log(ContainerId), } /// Cpu & Mem stats take twice as long as the update interval to get a value, so will have two being executed at the same time @@ -94,7 +94,7 @@ impl DockerData { /// remove if from spawns hashmap when complete async fn update_container_stat( docker: Arc, - id: String, + id: ContainerId, app_data: Arc>, is_running: bool, spawns: Arc>>>, @@ -102,7 +102,7 @@ impl DockerData { ) { let mut stream = docker .stats( - &id, + id.get(), Some(StatsOptions { stream: false, one_shot: !is_running, @@ -149,7 +149,7 @@ impl DockerData { } /// Update all stats, spawn each container into own tokio::spawn thread - fn update_all_container_stats(&mut self, all_ids: &[(bool, String)]) { + fn update_all_container_stats(&mut self, all_ids: &[(bool, ContainerId)]) { for (is_running, id) in all_ids.iter() { let docker = Arc::clone(&self.docker); let app_data = Arc::clone(&self.app_data); @@ -174,7 +174,7 @@ impl DockerData { /// Get all current containers, handle into ContainerItem in the app_data struct rather than here /// Just make sure that items sent are guaranteed to have an id /// Will ignore any container that contains `oxker` as an entry point - pub async fn update_all_containers(&mut self) -> Vec<(bool, String)> { + pub async fn update_all_containers(&mut self) -> Vec<(bool, ContainerId)> { let containers = self .docker .list_containers(Some(ListContainersOptions:: { @@ -211,7 +211,7 @@ impl DockerData { ( i.state == Some("running".to_owned()) || i.state == Some("restarting".to_owned()), - id.clone(), + ContainerId::from(id.as_str()), ) }) }) @@ -223,7 +223,7 @@ impl DockerData { /// remove if from spawns hashmap when complete async fn update_log( docker: Arc, - id: String, + id: ContainerId, timestamps: bool, since: u64, app_data: Arc>, @@ -232,11 +232,11 @@ impl DockerData { let options = Some(LogsOptions:: { stdout: true, timestamps, - since: since as i64, + since: i64::try_from(since).unwrap_or_default(), ..Default::default() }); - let mut logs = docker.logs(&id, options); + let mut logs = docker.logs(id.get(), options); let mut output = vec![]; while let Some(value) = logs.next().await { @@ -252,7 +252,7 @@ impl DockerData { } /// Update all logs, spawn each container into own tokio::spawn thread - fn init_all_logs(&mut self, all_ids: &[(bool, String)]) { + fn init_all_logs(&mut self, all_ids: &[(bool, ContainerId)]) { for (_, id) in all_ids.iter() { let docker = Arc::clone(&self.docker); let app_data = Arc::clone(&self.app_data); @@ -349,7 +349,7 @@ impl DockerData { match message { DockerMessage::Pause(id) => { let loading_spin = self.loading_spin(loading_uuid).await; - if docker.pause_container(&id).await.is_err() { + if docker.pause_container(id.get()).await.is_err() { app_data .lock() .set_error(AppError::DockerCommand(DockerControls::Pause)); @@ -358,7 +358,7 @@ impl DockerData { } DockerMessage::Restart(id) => { let loading_spin = self.loading_spin(loading_uuid).await; - if docker.restart_container(&id, None).await.is_err() { + if docker.restart_container(id.get(), None).await.is_err() { app_data .lock() .set_error(AppError::DockerCommand(DockerControls::Restart)); @@ -368,7 +368,7 @@ impl DockerData { DockerMessage::Start(id) => { let loading_spin = self.loading_spin(loading_uuid).await; if docker - .start_container(&id, None::>) + .start_container(id.get(), None::>) .await .is_err() { @@ -380,7 +380,7 @@ impl DockerData { } DockerMessage::Stop(id) => { let loading_spin = self.loading_spin(loading_uuid).await; - if docker.stop_container(&id, None).await.is_err() { + if docker.stop_container(id.get(), None).await.is_err() { app_data .lock() .set_error(AppError::DockerCommand(DockerControls::Stop)); @@ -389,7 +389,7 @@ impl DockerData { } DockerMessage::Unpause(id) => { let loading_spin = self.loading_spin(loading_uuid).await; - if docker.unpause_container(&id).await.is_err() { + if docker.unpause_container(id.get()).await.is_err() { app_data .lock() .set_error(AppError::DockerCommand(DockerControls::Unpause)); diff --git a/src/input_handler/mod.rs b/src/input_handler/mod.rs index b253beb..abbaf3d 100644 --- a/src/input_handler/mod.rs +++ b/src/input_handler/mod.rs @@ -137,6 +137,7 @@ impl InputHandler { } /// Handle any keyboard button events + #[allow(clippy::too_many_lines)] async fn button_press(&mut self, key_code: KeyCode) { let show_error = self.app_data.lock().show_error; let show_info = self.gui_state.lock().show_help; From 31fb2cb1e6dcff000e93403538d8f1b00660d746 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Sat, 1 Oct 2022 23:28:08 +0000 Subject: [PATCH 08/22] fix: u16::try_from for text widths --- src/parse_args/mod.rs | 1 + src/ui/draw_blocks.rs | 43 ++++++++++++++++++++++--------------------- src/ui/mod.rs | 4 ++-- 3 files changed, 25 insertions(+), 23 deletions(-) diff --git a/src/parse_args/mod.rs b/src/parse_args/mod.rs index 6a4e13f..26b0e20 100644 --- a/src/parse_args/mod.rs +++ b/src/parse_args/mod.rs @@ -4,6 +4,7 @@ use clap::Parser; use tracing::error; #[derive(Parser, Debug, Clone, Copy)] +#[allow(clippy::struct_excessive_bools)] // #[command(help_template = FULL_TEMPLATE)] #[command(version, about)] pub struct CliArgs { diff --git a/src/ui/draw_blocks.rs b/src/ui/draw_blocks.rs index 2f1a847..f4708c9 100644 --- a/src/ui/draw_blocks.rs +++ b/src/ui/draw_blocks.rs @@ -168,7 +168,7 @@ pub fn containers( format!( "{}{:>width$}", MARGIN, - i.id.chars().take(8).collect::(), + i.id.get().chars().take(8).collect::(), width = &widths.id.1 ), blue, @@ -343,6 +343,7 @@ fn make_chart<'a, T: Stats + Display>( } /// Draw heading bar at top of program, always visible +#[allow(clippy::too_many_lines)] pub fn heading_bar( area: Rect, columns: &Columns, @@ -407,7 +408,7 @@ pub fn heading_bar( width = width - block.2 ), }; - let count = text.chars().count() as u16; + let count = u16::try_from(text.chars().count()).unwrap_or_default(); let status = Paragraph::new(text) .block(block.0) .alignment(Alignment::Left); @@ -437,12 +438,12 @@ pub fn heading_bar( let suffix = if info_visible { "exit" } else { "show" }; let info_text = format!("( h ) {} help {}", suffix, MARGIN); - let info_width = info_text.chars().count() as u16; + let info_width = info_text.chars().count(); - let column_width = area.width - info_width; + let column_width = usize::from(area.width) - info_width; let column_width = if column_width > 0 { column_width } else { 1 }; let splits = if has_containers { - vec![Constraint::Min(column_width), Constraint::Min(info_width)] + vec![Constraint::Min(column_width.try_into().unwrap_or_default()), Constraint::Min(info_width.try_into().unwrap_or_default())] } else { vec![Constraint::Percentage(100)] }; @@ -541,8 +542,8 @@ pub fn help_box(f: &mut Frame<'_, B>) { .border_style(Style::default().fg(Color::Black)); let area = popup( - lines as u16, - max_line_width as u16, + lines, + max_line_width, f.size(), BoxLocation::MiddleCentre, ); @@ -551,9 +552,9 @@ pub fn help_box(f: &mut Frame<'_, B>) { .direction(Direction::Vertical) .constraints( [ - Constraint::Max(NAME_TEXT.lines().count() as u16), - Constraint::Max(description_text.lines().count() as u16), - Constraint::Max(help_text.lines().count() as u16), + Constraint::Max(NAME_TEXT.lines().count().try_into().unwrap_or_default()), + Constraint::Max(description_text.lines().count().try_into().unwrap_or_default()), + Constraint::Max(help_text.lines().count().try_into().unwrap_or_default()), ] .as_ref(), ) @@ -605,8 +606,8 @@ pub fn error(f: &mut Frame<'_, B>, error: AppError, seconds: Option< .alignment(Alignment::Center); let area = popup( - lines as u16, - max_line_width as u16, + lines, + max_line_width, f.size(), BoxLocation::MiddleCentre, ); @@ -634,8 +635,8 @@ pub fn info(f: &mut Frame<'_, B>, text: String) { .alignment(Alignment::Center); let area = popup( - lines as u16, - max_line_width as u16, + lines, + max_line_width, f.size(), BoxLocation::BottomRight, ); @@ -644,21 +645,21 @@ pub fn info(f: &mut Frame<'_, B>, text: String) { } /// draw a box in the one of the BoxLocations, based on max line width + number of lines -fn popup(text_lines: u16, text_width: u16, r: Rect, box_location: BoxLocation) -> Rect { +fn popup(text_lines: usize, text_width: usize, r: Rect, box_location: BoxLocation) -> Rect { // Make sure blank_space can't be an negative, as will crash - let blank_vertical = if r.height > text_lines { - (r.height - text_lines) / 2 + let blank_vertical = if usize::from(r.height) > text_lines { + (usize::from(r.height) - text_lines) / 2 } else { 1 }; - let blank_horizontal = if r.width > text_width { - (r.width - text_width) / 2 + let blank_horizontal = if usize::from(r.width) > text_width { + (usize::from(r.width) - text_width) / 2 } else { 1 }; - let v_constraints = box_location.get_vertical_constraints(blank_vertical, text_lines); - let h_constraints = box_location.get_horizontal_constraints(blank_horizontal, text_width); + let v_constraints = box_location.get_vertical_constraints(blank_vertical.try_into().unwrap_or_default(), text_lines.try_into().unwrap_or_default()); + let h_constraints = box_location.get_horizontal_constraints(blank_horizontal.try_into().unwrap_or_default(), text_width.try_into().unwrap_or_default()); let indexes = box_location.get_indexes(); diff --git a/src/ui/mod.rs b/src/ui/mod.rs index e2dc511..257a70e 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -148,7 +148,7 @@ fn ui( ) { // set max height for container section, needs +4 to deal with docker commands list and borders let height = app_data.lock().get_container_len(); - let height = if height < 12 { (height + 4) as u16 } else { 12 }; + let height = if height < 12 { height + 4 } else { 12 }; let column_widths = app_data.lock().get_width(); let has_containers = !app_data.lock().containers.items.is_empty(); @@ -168,7 +168,7 @@ fn ui( // Split into 3, containers+controls, logs, then graphs let upper_main = Layout::default() .direction(Direction::Vertical) - .constraints([Constraint::Max(height as u16), Constraint::Percentage(50)].as_ref()) + .constraints([Constraint::Max(height.try_into().unwrap_or_default()), Constraint::Percentage(50)].as_ref()) .split(whole_layout[1]); let top_split = if has_containers { From a7b8df6b215c3869e623d9cbeb6e6bc3f37dcc35 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Sat, 1 Oct 2022 23:40:25 +0000 Subject: [PATCH 09/22] refactor: derive Default for CpuStats + ByteStats --- src/app_data/container_state.rs | 14 +++++++------- src/app_data/mod.rs | 4 ++-- src/ui/draw_blocks.rs | 4 ++-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/app_data/container_state.rs b/src/app_data/container_state.rs index 6e363dd..5c6f054 100644 --- a/src/app_data/container_state.rs +++ b/src/app_data/container_state.rs @@ -253,7 +253,7 @@ pub trait Stats { /// Struct for frequently updated CPU stats /// So can use custom display formatter /// Use trait Stats for use as generic in draw_chart function -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Default, Clone, Copy)] pub struct CpuStats { value: f64, } @@ -306,7 +306,7 @@ impl fmt::Display for CpuStats { /// Struct for frequently updated memory usage stats /// So can use custom display formatter /// Use trait Stats for use as generic in draw_chart function -#[derive(Debug, Clone, Copy, Eq)] +#[derive(Debug, Default, Clone, Copy, Eq)] pub struct ByteStats { value: u64, } @@ -390,11 +390,11 @@ impl ContainerItem { image, last_updated: 0, logs: StatefulList::new(vec![]), - mem_limit: ByteStats::new(0), + mem_limit: ByteStats::default(), mem_stats: VecDeque::with_capacity(60), name, - rx: ByteStats::new(0), - tx: ByteStats::new(0), + rx: ByteStats::default(), + tx: ByteStats::default(), state, status, } @@ -404,7 +404,7 @@ impl ContainerItem { fn max_cpu_stats(&self) -> CpuStats { match self.cpu_stats.iter().max() { Some(value) => *value, - None => CpuStats::new(0.0), + None => CpuStats::default(), } } @@ -412,7 +412,7 @@ impl ContainerItem { fn max_mem_stats(&self) -> ByteStats { match self.mem_stats.iter().max() { Some(value) => *value, - None => ByteStats::new(0), + None => ByteStats::default(), } } diff --git a/src/app_data/mod.rs b/src/app_data/mod.rs index f1a8f7a..e99b0a7 100644 --- a/src/app_data/mod.rs +++ b/src/app_data/mod.rs @@ -328,12 +328,12 @@ impl AppData { &container .cpu_stats .back() - .unwrap_or(&CpuStats::new(0.0)) + .unwrap_or(&CpuStats::default()) .to_string(), ); let mem_count = count(&format!( "{} / {}", - container.mem_stats.back().unwrap_or(&ByteStats::new(0)), + container.mem_stats.back().unwrap_or(&ByteStats::default()), container.mem_limit )); diff --git a/src/ui/draw_blocks.rs b/src/ui/draw_blocks.rs index f4708c9..7532f6c 100644 --- a/src/ui/draw_blocks.rs +++ b/src/ui/draw_blocks.rs @@ -138,7 +138,7 @@ pub fn containers( let mems = format!( "{:>1} / {:>1}", - i.mem_stats.back().unwrap_or(&ByteStats::new(0)), + i.mem_stats.back().unwrap_or(&ByteStats::default()), i.mem_limit ); @@ -155,7 +155,7 @@ pub fn containers( format!( "{}{:>width$}", MARGIN, - i.cpu_stats.back().unwrap_or(&CpuStats::new(0.0)), + i.cpu_stats.back().unwrap_or(&CpuStats::default()), width = &widths.cpu.1 ), state_style, From f5fc44629543a68b2995830ebb39e78259552c3c Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Sun, 2 Oct 2022 00:31:01 +0000 Subject: [PATCH 10/22] refactor: use map_or_else --- src/app_data/mod.rs | 12 +++++------ src/docker_data/mod.rs | 5 ++--- src/input_handler/mod.rs | 2 +- src/ui/draw_blocks.rs | 44 ++++++++++++++++++++-------------------- src/ui/mod.rs | 8 +++++++- 5 files changed, 38 insertions(+), 33 deletions(-) diff --git a/src/app_data/mod.rs b/src/app_data/mod.rs index e99b0a7..322bbae 100644 --- a/src/app_data/mod.rs +++ b/src/app_data/mod.rs @@ -66,12 +66,12 @@ impl AppData { pub fn set_sorted(&mut self, x: Option<(Header, SortedOrder)>) { self.sorted_by = x; self.sort_containers(); - self.containers.state.select( - self.containers - .items - .iter() - .position(|i| Some(i.id.clone()) == self.get_selected_container_id()), - ); + self.containers + .state + .select(self.containers.items.iter().position(|i| { + self.get_selected_container_id() + .map_or_else(|| false, |id| i.id == id) + })); } /// Generate a default app_state pub fn default(args: CliArgs) -> Self { diff --git a/src/docker_data/mod.rs b/src/docker_data/mod.rs index 6744f4a..a648abf 100644 --- a/src/docker_data/mod.rs +++ b/src/docker_data/mod.rs @@ -78,9 +78,8 @@ impl DockerData { .cpu_stats .cpu_usage .percpu_usage - .clone() - .unwrap_or_default() - .len() as u64 + .as_ref() + .map_or_else(|| 0, |i| i.len()) as u64 }) as f64; if system_delta > 0.0 && cpu_delta > 0.0 { cpu_percentage = (cpu_delta / system_delta) * online_cpus * 100.0; diff --git a/src/input_handler/mod.rs b/src/input_handler/mod.rs index abbaf3d..91f2418 100644 --- a/src/input_handler/mod.rs +++ b/src/input_handler/mod.rs @@ -137,7 +137,7 @@ impl InputHandler { } /// Handle any keyboard button events - #[allow(clippy::too_many_lines)] + #[allow(clippy::too_many_lines)] async fn button_press(&mut self, key_code: KeyCode) { let show_error = self.app_data.lock().show_error; let show_info = self.gui_state.lock().show_help; diff --git a/src/ui/draw_blocks.rs b/src/ui/draw_blocks.rs index 7532f6c..ee5304e 100644 --- a/src/ui/draw_blocks.rs +++ b/src/ui/draw_blocks.rs @@ -443,7 +443,10 @@ pub fn heading_bar( let column_width = usize::from(area.width) - info_width; let column_width = if column_width > 0 { column_width } else { 1 }; let splits = if has_containers { - vec![Constraint::Min(column_width.try_into().unwrap_or_default()), Constraint::Min(info_width.try_into().unwrap_or_default())] + vec![ + Constraint::Min(column_width.try_into().unwrap_or_default()), + Constraint::Min(info_width.try_into().unwrap_or_default()), + ] } else { vec![Constraint::Percentage(100)] }; @@ -541,19 +544,20 @@ pub fn help_box(f: &mut Frame<'_, B>) { .border_type(BorderType::Rounded) .border_style(Style::default().fg(Color::Black)); - let area = popup( - lines, - max_line_width, - f.size(), - BoxLocation::MiddleCentre, - ); + let area = popup(lines, max_line_width, f.size(), BoxLocation::MiddleCentre); let split_popup = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Max(NAME_TEXT.lines().count().try_into().unwrap_or_default()), - Constraint::Max(description_text.lines().count().try_into().unwrap_or_default()), + Constraint::Max( + description_text + .lines() + .count() + .try_into() + .unwrap_or_default(), + ), Constraint::Max(help_text.lines().count().try_into().unwrap_or_default()), ] .as_ref(), @@ -605,12 +609,7 @@ pub fn error(f: &mut Frame<'_, B>, error: AppError, seconds: Option< .block(block) .alignment(Alignment::Center); - let area = popup( - lines, - max_line_width, - f.size(), - BoxLocation::MiddleCentre, - ); + let area = popup(lines, max_line_width, f.size(), BoxLocation::MiddleCentre); f.render_widget(Clear, area); f.render_widget(paragraph, area); } @@ -634,12 +633,7 @@ pub fn info(f: &mut Frame<'_, B>, text: String) { .block(block) .alignment(Alignment::Center); - let area = popup( - lines, - max_line_width, - f.size(), - BoxLocation::BottomRight, - ); + let area = popup(lines, max_line_width, f.size(), BoxLocation::BottomRight); f.render_widget(Clear, area); f.render_widget(paragraph, area); } @@ -658,8 +652,14 @@ fn popup(text_lines: usize, text_width: usize, r: Rect, box_location: BoxLocatio 1 }; - let v_constraints = box_location.get_vertical_constraints(blank_vertical.try_into().unwrap_or_default(), text_lines.try_into().unwrap_or_default()); - let h_constraints = box_location.get_horizontal_constraints(blank_horizontal.try_into().unwrap_or_default(), text_width.try_into().unwrap_or_default()); + let v_constraints = box_location.get_vertical_constraints( + blank_vertical.try_into().unwrap_or_default(), + text_lines.try_into().unwrap_or_default(), + ); + let h_constraints = box_location.get_horizontal_constraints( + blank_horizontal.try_into().unwrap_or_default(), + text_width.try_into().unwrap_or_default(), + ); let indexes = box_location.get_indexes(); diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 257a70e..b126dbd 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -168,7 +168,13 @@ fn ui( // Split into 3, containers+controls, logs, then graphs let upper_main = Layout::default() .direction(Direction::Vertical) - .constraints([Constraint::Max(height.try_into().unwrap_or_default()), Constraint::Percentage(50)].as_ref()) + .constraints( + [ + Constraint::Max(height.try_into().unwrap_or_default()), + Constraint::Percentage(50), + ] + .as_ref(), + ) .split(whole_layout[1]); let top_split = if has_containers { From 6bee4d007ad1cced4affd17b952464b8484c8982 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Sun, 2 Oct 2022 01:14:42 +0000 Subject: [PATCH 11/22] refactor: clone()'s removed, allow(precision_loss) --- src/app_data/container_state.rs | 10 +++++-- src/app_data/mod.rs | 52 +++++++++++++++------------------ src/docker_data/mod.rs | 4 +-- src/ui/color_match.rs | 8 ++--- 4 files changed, 38 insertions(+), 36 deletions(-) diff --git a/src/app_data/container_state.rs b/src/app_data/container_state.rs index 5c6f054..b1b83f5 100644 --- a/src/app_data/container_state.rs +++ b/src/app_data/container_state.rs @@ -337,6 +337,8 @@ impl ByteStats { self.value = value; } } + +#[allow(clippy::cast_precision_loss)] impl Stats for ByteStats { fn get_value(&self) -> f64 { self.value as f64 @@ -346,7 +348,7 @@ impl Stats for ByteStats { /// convert from bytes to kB, MB, GB etc impl fmt::Display for ByteStats { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let as_f64 = self.value as f64; + let as_f64 = self.get_value(); let p = match as_f64 { x if x >= ONE_GB => format!("{y:.2} GB", y = as_f64 / ONE_GB), x if x >= ONE_MB => format!("{y:.2} MB", y = as_f64 / ONE_MB), @@ -383,13 +385,15 @@ impl ContainerItem { pub fn new(id: ContainerId, status: String, image: String, state: State, name: String) -> Self { let mut docker_controls = StatefulList::new(DockerControls::gen_vec(state)); docker_controls.start(); + let mut logs = StatefulList::new(vec![]); + logs.end(); Self { cpu_stats: VecDeque::with_capacity(60), docker_controls, id, image, last_updated: 0, - logs: StatefulList::new(vec![]), + logs, mem_limit: ByteStats::default(), mem_stats: VecDeque::with_capacity(60), name, @@ -417,6 +421,7 @@ impl ContainerItem { } /// Convert cpu stats into a vec for the charts function + #[allow(clippy::cast_precision_loss)] fn get_cpu_dataset(&self) -> Vec<(f64, f64)> { self.cpu_stats .iter() @@ -426,6 +431,7 @@ impl ContainerItem { } /// Convert mem stats into a Vec for the charts function + #[allow(clippy::cast_precision_loss)] fn get_mem_dataset(&self) -> Vec<(f64, f64)> { self.mem_stats .iter() diff --git a/src/app_data/mod.rs b/src/app_data/mod.rs index 322bbae..c40cc1f 100644 --- a/src/app_data/mod.rs +++ b/src/app_data/mod.rs @@ -163,7 +163,7 @@ impl AppData { } /// Find the id of the currently selected container. - /// If any containers on system, will always return a container id + /// If any containers on system, will always return a ContainerId /// Only returns None when no containers found. pub fn get_selected_container_id(&self) -> Option { let mut output = None; @@ -323,6 +323,7 @@ impl AppData { let mut output = Columns::new(); let count = |x: &String| x.chars().count(); + // Should probably find a refactor here somewhere for container in &self.containers.items { let cpu_count = count( &container @@ -418,18 +419,18 @@ impl AppData { } /// Update, or insert, containers - pub fn update_containers(&mut self, containers: &mut [ContainerSummary]) { + pub fn update_containers(&mut self, all_containers: &mut [ContainerSummary]) { let all_ids = self.get_all_ids(); - if !containers.is_empty() && self.containers.state.selected().is_none() { + if !all_containers.is_empty() && self.containers.state.selected().is_none() { self.containers.start(); } for (index, id) in all_ids.iter().enumerate() { - if !containers + if !all_containers .iter() .filter_map(|i| i.id.as_ref()) - .any(|x| ContainerId::from(x) == id.clone()) + .any(|x| &ContainerId::from(x) == id) { // If removed container is currently selected, then change selected to previous // This will default to 0 in any edge cases @@ -443,15 +444,14 @@ impl AppData { } } - for i in containers.iter_mut() { + for i in all_containers.iter_mut() { if let Some(id) = i.id.as_ref() { - // maybe if no name then continue? let name = i.names.as_mut().map_or("".to_owned(), |n| { n.get_mut(0).map_or("".to_owned(), |f| { if f.starts_with('/') { f.remove(0); } - f.clone() + (*f).to_string() }) }); @@ -470,36 +470,32 @@ impl AppData { .as_ref() .map_or("".to_owned(), std::clone::Clone::clone); - let id = ContainerId::from(id.as_str()); - if let Some(current_container) = self.get_container_by_id(&id) { - if current_container.name != name { - current_container.name = name; + let id = ContainerId::from(id); + // If container info already in containers Vec, then just update details + if let Some(item) = self.get_container_by_id(&id) { + if item.name != name { + item.name = name; }; - if current_container.status != status { - current_container.status = status; + if item.status != status { + item.status = status; }; - if current_container.state != state { - current_container.docker_controls.items = DockerControls::gen_vec(state); - + if item.state != state { + item.docker_controls.items = DockerControls::gen_vec(state); // Update the list state, needs to be None if the gen_vec returns an empty vec match state { State::Removing | State::Restarting | State::Unknown => { - current_container.docker_controls.state.select(None); + item.docker_controls.state.select(None); } - _ => current_container.docker_controls.start(), + _ => item.docker_controls.start(), }; - current_container.state = state; + item.state = state; }; - if current_container.image != image { - // limit image name to 64 chars? - // current_container.image = image.chars().into_iter().take(64).collect(); - current_container.image = image; + if item.image != image { + item.image = image; }; + // else container not known, so make new ContainerItem and push into containers Vec } else { - // limit image name to 64 chars? - // let mut container = ContainerItem::new(id.clone(), status, image.chars().into_iter().take(64).collect(), state, name); - let mut container = ContainerItem::new(id.clone(), status, image, state, name); - container.logs.end(); + let container = ContainerItem::new(id, status, image, state, name); self.containers.items.push(container); } } diff --git a/src/docker_data/mod.rs b/src/docker_data/mod.rs index a648abf..92e661c 100644 --- a/src/docker_data/mod.rs +++ b/src/docker_data/mod.rs @@ -63,6 +63,7 @@ pub struct DockerData { impl DockerData { /// Use docker stats to caluclate current cpu usage + #[allow(clippy::cast_precision_loss)] fn calculate_usage(stats: &Stats) -> f64 { let mut cpu_percentage = 0.0; let previous_cpu = stats.precpu_stats.cpu_usage.total_usage; @@ -79,7 +80,7 @@ impl DockerData { .cpu_usage .percpu_usage .as_ref() - .map_or_else(|| 0, |i| i.len()) as u64 + .map_or_else(|| 0, std::vec::Vec::len) as u64 }) as f64; if system_delta > 0.0 && cpu_delta > 0.0 { cpu_percentage = (cpu_delta / system_delta) * online_cpus * 100.0; @@ -154,7 +155,6 @@ impl DockerData { let app_data = Arc::clone(&self.app_data); let spawns = Arc::clone(&self.spawns); let key = SpawnId::Stats((id.clone(), self.binate)); - let spawn_key = key.clone(); self.spawns.lock().entry(key).or_insert_with(|| { tokio::spawn(Self::update_container_stat( diff --git a/src/ui/color_match.rs b/src/ui/color_match.rs index 5c423f9..f26e179 100644 --- a/src/ui/color_match.rs +++ b/src/ui/color_match.rs @@ -10,11 +10,11 @@ pub mod log_sanitizer { pub fn colorize_logs<'a>(input: &str) -> Vec> { vec![Spans::from( categorise_text(input) - .into_iter() + .iter() .map(|i| { - let fg_color = color_ansi_to_tui(i.fg.unwrap_or(CansiColor::White)); - let bg_color = color_ansi_to_tui(i.bg.unwrap_or(CansiColor::Black)); - let style = Style::default().bg(bg_color).fg(fg_color); + let style = Style::default() + .bg(color_ansi_to_tui(i.fg.unwrap_or(CansiColor::White))) + .fg(color_ansi_to_tui(i.bg.unwrap_or(CansiColor::Black))); if i.blink.is_some() { style.add_modifier(Modifier::SLOW_BLINK); } From f12a83056bb55500a4b538d4da814fbb349f2d0e Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Sun, 2 Oct 2022 01:19:21 +0000 Subject: [PATCH 12/22] refactor: Paragraph::new from str, rather than variable declaration --- src/ui/draw_blocks.rs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/ui/draw_blocks.rs b/src/ui/draw_blocks.rs index ee5304e..36a62e4 100644 --- a/src/ui/draw_blocks.rs +++ b/src/ui/draw_blocks.rs @@ -109,8 +109,7 @@ pub fn commands( &mut app_data.lock().containers.items[i].docker_controls.state, ); } else { - let debug_text = String::from(""); - let paragraph = Paragraph::new(debug_text) + let paragraph = Paragraph::new("") .block(block) .alignment(Alignment::Center); f.render_widget(paragraph, area); @@ -194,8 +193,7 @@ pub fn containers( }) .collect::>(); if items.is_empty() { - let debug_text = String::from("no containers running"); - let paragraph = Paragraph::new(debug_text) + let paragraph = Paragraph::new("no containers running") .block(block) .alignment(Alignment::Center); f.render_widget(paragraph, area); @@ -222,8 +220,7 @@ pub fn logs( let init = app_data.lock().init; if !init { - let parsing_logs = format!("parsing logs {}", loading_icon); - let paragraph = Paragraph::new(parsing_logs) + let paragraph = Paragraph::new(format!("parsing logs {}", loading_icon)) .style(Style::default()) .block(block) .alignment(Alignment::Center); @@ -247,8 +244,7 @@ pub fn logs( &mut app_data.lock().containers.items[index].logs.state, ); } else { - let debug_text = String::from("no logs found"); - let paragraph = Paragraph::new(debug_text) + let paragraph = Paragraph::new("no logs found") .block(block) .alignment(Alignment::Center); f.render_widget(paragraph, area); From c41c0e4954d97ae0749394065c70222d893150ac Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Fri, 7 Oct 2022 01:43:08 +0000 Subject: [PATCH 13/22] fix: color match bg/fg mix --- src/ui/color_match.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ui/color_match.rs b/src/ui/color_match.rs index f26e179..24d206a 100644 --- a/src/ui/color_match.rs +++ b/src/ui/color_match.rs @@ -13,8 +13,8 @@ pub mod log_sanitizer { .iter() .map(|i| { let style = Style::default() - .bg(color_ansi_to_tui(i.fg.unwrap_or(CansiColor::White))) - .fg(color_ansi_to_tui(i.bg.unwrap_or(CansiColor::Black))); + .bg(color_ansi_to_tui(i.bg.unwrap_or(CansiColor::Black))) + .fg(color_ansi_to_tui(i.fg.unwrap_or(CansiColor::White))); if i.blink.is_some() { style.add_modifier(Modifier::SLOW_BLINK); } From 3661d696e9bf2e218f56e84b5e5bb99293f9234d Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Fri, 7 Oct 2022 01:43:58 +0000 Subject: [PATCH 14/22] refactor: map_or_else to map_or --- src/app_data/mod.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/app_data/mod.rs b/src/app_data/mod.rs index c40cc1f..37a5c8d 100644 --- a/src/app_data/mod.rs +++ b/src/app_data/mod.rs @@ -70,7 +70,7 @@ impl AppData { .state .select(self.containers.items.iter().position(|i| { self.get_selected_container_id() - .map_or_else(|| false, |id| i.id == id) + .map_or(false, |id| i.id == id) })); } /// Generate a default app_state @@ -259,8 +259,8 @@ impl AppData { /// Get the title for log panel for selected container /// will be "logs x/x" pub fn get_log_title(&self) -> String { - self.get_selected_log_index().map_or_else( - || String::from(""), + self.get_selected_log_index().map_or( + "".to_owned(), |index| self.containers.items[index].logs.get_state_title(), ) } @@ -430,7 +430,7 @@ impl AppData { if !all_containers .iter() .filter_map(|i| i.id.as_ref()) - .any(|x| &ContainerId::from(x) == id) + .any(|x| x == id.get()) { // If removed container is currently selected, then change selected to previous // This will default to 0 in any edge cases @@ -446,8 +446,8 @@ impl AppData { for i in all_containers.iter_mut() { if let Some(id) = i.id.as_ref() { - let name = i.names.as_mut().map_or("".to_owned(), |n| { - n.get_mut(0).map_or("".to_owned(), |f| { + let name = i.names.as_mut().map_or("".to_owned(), |names| { + names.first_mut().map_or("".to_owned(), |f| { if f.starts_with('/') { f.remove(0); } From 5c9f253695b51b2cf86dafdeb92da438a93ec4ee Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Fri, 7 Oct 2022 01:44:21 +0000 Subject: [PATCH 15/22] docs: --help explanation improved --- src/parse_args/mod.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/parse_args/mod.rs b/src/parse_args/mod.rs index 26b0e20..5c70ce9 100644 --- a/src/parse_args/mod.rs +++ b/src/parse_args/mod.rs @@ -5,7 +5,6 @@ use tracing::error; #[derive(Parser, Debug, Clone, Copy)] #[allow(clippy::struct_excessive_bools)] -// #[command(help_template = FULL_TEMPLATE)] #[command(version, about)] pub struct CliArgs { /// Docker update interval in ms, minimum effectively 1000 @@ -16,11 +15,11 @@ pub struct CliArgs { #[clap(short = 't')] pub timestamp: bool, - /// Attempt to colorize the logs + /// Attempt to colorize the logs, conflicts with "-r" #[clap(short = 'c', conflicts_with = "raw")] pub color: bool, - /// Show raw logs, default is to remove ansi formatting + /// Show raw logs, default is to remove ansi formatting, conflicts with "-c" #[clap(short = 'r', conflicts_with = "color")] pub raw: bool, From 3e26f292c7dc5e13af4580952767ebe821aa5183 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Fri, 7 Oct 2022 01:45:01 +0000 Subject: [PATCH 16/22] refactor: map_or_else to map_or --- src/ui/draw_blocks.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/ui/draw_blocks.rs b/src/ui/draw_blocks.rs index 36a62e4..40dc62c 100644 --- a/src/ui/draw_blocks.rs +++ b/src/ui/draw_blocks.rs @@ -51,10 +51,7 @@ fn generate_block<'a>( panel: SelectablePanel, ) -> Block<'a> { gui_state.lock().update_map(Region::Panel(panel), area); - let mut block = Block::default() - .borders(Borders::ALL) - .border_type(BorderType::Rounded); - let current_selected_panel = gui_state.lock().selected_panel; + let current_selected_panel = gui_state.lock().selected_panel; let title = match panel { SelectablePanel::Containers => { format!( @@ -68,7 +65,10 @@ fn generate_block<'a>( } SelectablePanel::Commands => String::from(""), }; - block = block.title(title); + let mut block = Block::default() + .borders(Borders::ALL) + .border_type(BorderType::Rounded) + .title(title); if current_selected_panel == panel { block = block.border_style(Style::default().fg(Color::LightCyan)); } @@ -109,9 +109,7 @@ pub fn commands( &mut app_data.lock().containers.items[i].docker_controls.state, ); } else { - let paragraph = Paragraph::new("") - .block(block) - .alignment(Alignment::Center); + let paragraph = Paragraph::new("").block(block).alignment(Alignment::Center); f.render_widget(paragraph, area); } } From 5660b34d5149dce27706ff6daa90b854e6f84e14 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Fri, 7 Oct 2022 02:22:26 +0000 Subject: [PATCH 17/22] refactor: map_or_else to map_or --- src/app_data/container_state.rs | 16 ++++++++-------- src/app_error.rs | 8 ++++---- src/docker_data/mod.rs | 11 ++++++----- 3 files changed, 18 insertions(+), 17 deletions(-) diff --git a/src/app_data/container_state.rs b/src/app_data/container_state.rs index b1b83f5..c299de4 100644 --- a/src/app_data/container_state.rs +++ b/src/app_data/container_state.rs @@ -136,10 +136,10 @@ pub enum State { impl State { pub const fn get_color(self) -> Color { match self { - Self::Running => Color::Green, + Self::Paused => Color::Yellow, Self::Removing => Color::LightRed, Self::Restarting => Color::LightGreen, - Self::Paused => Color::Yellow, + Self::Running => Color::Green, _ => Color::Red, } } @@ -204,19 +204,19 @@ impl fmt::Display for State { #[derive(Debug, Clone, Copy)] pub enum DockerControls { Pause, - Unpause, Restart, - Stop, Start, + Stop, + Unpause, } impl DockerControls { pub const fn get_color(self) -> Color { match self { + Self::Pause => Color::Yellow, + Self::Restart => Color::Magenta, Self::Start => Color::Green, Self::Stop => Color::Red, - Self::Restart => Color::Magenta, - Self::Pause => Color::Yellow, Self::Unpause => Color::Blue, } } @@ -237,10 +237,10 @@ impl fmt::Display for DockerControls { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let disp = match self { Self::Pause => "pause", - Self::Unpause => "unpause", Self::Restart => "restart", - Self::Stop => "stop", Self::Start => "start", + Self::Stop => "stop", + Self::Unpause => "unpause", }; write!(f, "{}", disp) } diff --git a/src/app_error.rs b/src/app_error.rs index 385b227..8770daf 100644 --- a/src/app_error.rs +++ b/src/app_error.rs @@ -5,10 +5,10 @@ use std::fmt; #[allow(unused)] #[derive(Debug, Clone, Copy)] pub enum AppError { + DockerCommand(DockerControls), DockerConnect, DockerInterval, InputPoll, - DockerCommand(DockerControls), MouseCapture(bool), Terminal, } @@ -17,15 +17,15 @@ pub enum AppError { impl fmt::Display for AppError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { + Self::DockerCommand(s) => write!(f, "Unable to {} container", s), Self::DockerConnect => write!(f, "Unable to access docker daemon"), Self::DockerInterval => write!(f, "Docker update interval needs to be greater than 0"), Self::InputPoll => write!(f, "Unable to poll user input"), - Self::Terminal => write!(f, "Unable to draw to terminal"), - Self::DockerCommand(s) => write!(f, "Unable to {} container", s), Self::MouseCapture(x) => { - let reason = if *x { "en" } else { "dis" }; + let reason = if *x { "en" } else { "dis" }; write!(f, "Unbale to {}able mouse capture", reason) } + Self::Terminal => write!(f, "Unable to draw to terminal"), } } } diff --git a/src/docker_data/mod.rs b/src/docker_data/mod.rs index 92e661c..dac0021 100644 --- a/src/docker_data/mod.rs +++ b/src/docker_data/mod.rs @@ -80,7 +80,7 @@ impl DockerData { .cpu_usage .percpu_usage .as_ref() - .map_or_else(|| 0, std::vec::Vec::len) as u64 + .map_or(0, std::vec::Vec::len) as u64 }) as f64; if system_delta > 0.0 && cpu_delta > 0.0 { cpu_percentage = (cpu_delta / system_delta) * online_cpus * 100.0; @@ -122,10 +122,11 @@ impl DockerData { let cpu_stats = Self::calculate_usage(&stats); let (rx, tx) = if let Some(key) = op_key { - match stats.networks.unwrap_or_default().get(&key) { - Some(data) => (data.rx_bytes, data.tx_bytes), - None => (0, 0), - } + stats + .networks + .unwrap_or_default() + .get(&key) + .map_or((0, 0), |f| (f.rx_bytes, f.tx_bytes)) } else { (0, 0) }; From a77f690a494a87e08fdaab745d9ed128d8d4df45 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Fri, 7 Oct 2022 02:43:04 +0000 Subject: [PATCH 18/22] refactor: replace iter() to into_iter(), and remove useless .iters()'s --- src/app_data/mod.rs | 24 +++++++++++++++--------- src/app_error.rs | 6 +++--- src/docker_data/mod.rs | 14 +++++++------- src/ui/draw_blocks.rs | 10 +++++----- 4 files changed, 30 insertions(+), 24 deletions(-) diff --git a/src/app_data/mod.rs b/src/app_data/mod.rs index 37a5c8d..c137fbf 100644 --- a/src/app_data/mod.rs +++ b/src/app_data/mod.rs @@ -259,10 +259,10 @@ impl AppData { /// Get the title for log panel for selected container /// will be "logs x/x" pub fn get_log_title(&self) -> String { - self.get_selected_log_index().map_or( - "".to_owned(), - |index| self.containers.items[index].logs.get_state_title(), - ) + self.get_selected_log_index() + .map_or("".to_owned(), |index| { + self.containers.items[index].logs.get_state_title() + }) } /// select next selected log line @@ -301,6 +301,8 @@ impl AppData { } } + + /// Check if the initial parsing has been completed, by making sure that all ids given (which are running) have a non empty cpu_stats vecdec pub fn initialised(&mut self, all_ids: &[(bool, ContainerId)]) -> bool { let count_is_running = all_ids.iter().filter(|i| i.0).count(); let number_with_cpu_status = self @@ -382,7 +384,7 @@ impl AppData { .collect::>() } - /// find container given id + /// return a mutable container by given id fn get_container_by_id(&mut self, id: &ContainerId) -> Option<&mut ContainerItem> { self.containers.items.iter_mut().find(|i| &i.id == id) } @@ -443,8 +445,10 @@ impl AppData { } } } + // Trim a &String and return String + let trim_owned = |x: &String| x.trim().to_owned(); - for i in all_containers.iter_mut() { + for i in all_containers { if let Some(id) = i.id.as_ref() { let name = i.names.as_mut().map_or("".to_owned(), |names| { names.first_mut().map_or("".to_owned(), |f| { @@ -458,12 +462,12 @@ impl AppData { let state = State::from( i.state .as_ref() - .map_or("dead".to_owned(), |f| f.trim().to_owned()), + .map_or("dead".to_owned(), trim_owned), ); let status = i .status .as_ref() - .map_or("".to_owned(), |f| f.trim().to_owned()); + .map_or("".to_owned(), trim_owned); let image = i .image @@ -512,7 +516,7 @@ impl AppData { container.last_updated = tz; let current_len = container.logs.items.len(); - for i in output.iter() { + for i in output { let lines = if color { log_sanitizer::colorize_logs(i) } else if raw { @@ -523,6 +527,8 @@ impl AppData { container.logs.items.push(ListItem::new(lines)); } + // Set the logs selected row for each container + // Either when no long currently selected, or currently selected (before updated) is already at end if container.logs.state.selected().is_none() || container.logs.state.selected().map_or(1, |f| f + 1) == current_len { diff --git a/src/app_error.rs b/src/app_error.rs index 8770daf..1f90db6 100644 --- a/src/app_error.rs +++ b/src/app_error.rs @@ -17,15 +17,15 @@ pub enum AppError { impl fmt::Display for AppError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - Self::DockerCommand(s) => write!(f, "Unable to {} container", s), + Self::DockerCommand(s) => write!(f, "Unable to {} container", s), Self::DockerConnect => write!(f, "Unable to access docker daemon"), Self::DockerInterval => write!(f, "Docker update interval needs to be greater than 0"), Self::InputPoll => write!(f, "Unable to poll user input"), Self::MouseCapture(x) => { - let reason = if *x { "en" } else { "dis" }; + let reason = if *x { "en" } else { "dis" }; write!(f, "Unbale to {}able mouse capture", reason) } - Self::Terminal => write!(f, "Unable to draw to terminal"), + Self::Terminal => write!(f, "Unable to draw to terminal"), } } } diff --git a/src/docker_data/mod.rs b/src/docker_data/mod.rs index dac0021..d0a3e47 100644 --- a/src/docker_data/mod.rs +++ b/src/docker_data/mod.rs @@ -151,7 +151,7 @@ impl DockerData { /// Update all stats, spawn each container into own tokio::spawn thread fn update_all_container_stats(&mut self, all_ids: &[(bool, ContainerId)]) { - for (is_running, id) in all_ids.iter() { + for (is_running, id) in all_ids { let docker = Arc::clone(&self.docker); let app_data = Arc::clone(&self.app_data); let spawns = Arc::clone(&self.spawns); @@ -185,13 +185,13 @@ impl DockerData { .unwrap_or_default(); let mut output = containers - .iter() + .into_iter() .filter_map(|f| match f.id { Some(_) => { if f.command.as_ref().map_or(false, |c| c.contains("oxker")) { None } else { - Some(f.clone()) + Some(f) } } None => None, @@ -205,13 +205,13 @@ impl DockerData { // Just get the containers that are currently running, or being restarted, no point updating info on paused or dead containers output - .iter() + .into_iter() .filter_map(|i| { - i.id.as_ref().map(|id| { + i.id.map(|id| { ( i.state == Some("running".to_owned()) || i.state == Some("restarting".to_owned()), - ContainerId::from(id.as_str()), + ContainerId::from(id), ) }) }) @@ -253,7 +253,7 @@ impl DockerData { /// Update all logs, spawn each container into own tokio::spawn thread fn init_all_logs(&mut self, all_ids: &[(bool, ContainerId)]) { - for (_, id) in all_ids.iter() { + for (_, id) in all_ids { let docker = Arc::clone(&self.docker); let app_data = Arc::clone(&self.app_data); let spawns = Arc::clone(&self.spawns); diff --git a/src/ui/draw_blocks.rs b/src/ui/draw_blocks.rs index 40dc62c..0dafee3 100644 --- a/src/ui/draw_blocks.rs +++ b/src/ui/draw_blocks.rs @@ -51,7 +51,7 @@ fn generate_block<'a>( panel: SelectablePanel, ) -> Block<'a> { gui_state.lock().update_map(Region::Panel(panel), area); - let current_selected_panel = gui_state.lock().selected_panel; + let current_selected_panel = gui_state.lock().selected_panel; let title = match panel { SelectablePanel::Containers => { format!( @@ -65,10 +65,10 @@ fn generate_block<'a>( } SelectablePanel::Commands => String::from(""), }; - let mut block = Block::default() - .borders(Borders::ALL) - .border_type(BorderType::Rounded) - .title(title); + let mut block = Block::default() + .borders(Borders::ALL) + .border_type(BorderType::Rounded) + .title(title); if current_selected_panel == panel { block = block.border_style(Style::default().fg(Color::LightCyan)); } From 62fb22478697cc9a7ab9fb562a724965b437233a Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Fri, 7 Oct 2022 03:04:06 +0000 Subject: [PATCH 19/22] refactor: String::from("") > String::new() --- src/app_data/container_state.rs | 2 +- src/ui/color_match.rs | 2 +- src/ui/draw_blocks.rs | 2 +- src/ui/gui_state.rs | 8 ++++---- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/app_data/container_state.rs b/src/app_data/container_state.rs index c299de4..b8b32b9 100644 --- a/src/app_data/container_state.rs +++ b/src/app_data/container_state.rs @@ -109,7 +109,7 @@ impl StatefulList { pub fn get_state_title(&self) -> String { if self.items.is_empty() { - String::from("") + String::new() } else { let len = self.items.len(); let c = self diff --git a/src/ui/color_match.rs b/src/ui/color_match.rs index 24d206a..8ad3112 100644 --- a/src/ui/color_match.rs +++ b/src/ui/color_match.rs @@ -41,7 +41,7 @@ pub mod log_sanitizer { /// Remove all ansi formatting from a given string and create tui-rs spans pub fn remove_ansi<'a>(input: &str) -> Vec> { - let mut output = String::from(""); + let mut output = String::new(); for i in categorise_text(input) { output.push_str(i.text); } diff --git a/src/ui/draw_blocks.rs b/src/ui/draw_blocks.rs index 0dafee3..50c4177 100644 --- a/src/ui/draw_blocks.rs +++ b/src/ui/draw_blocks.rs @@ -63,7 +63,7 @@ fn generate_block<'a>( SelectablePanel::Logs => { format!(" {} {} ", panel.title(), app_data.lock().get_log_title()) } - SelectablePanel::Commands => String::from(""), + SelectablePanel::Commands => String::new(), }; let mut block = Block::default() .borders(Borders::ALL) diff --git a/src/ui/gui_state.rs b/src/ui/gui_state.rs index b4c586f..f98b990 100644 --- a/src/ui/gui_state.rs +++ b/src/ui/gui_state.rs @@ -251,22 +251,22 @@ impl GuiState { self.selected_panel = self.selected_panel.prev(); } - /// Advance loading animation + /// Insert a new loading_uuid into hashset, and advance the animation by one frame pub fn next_loading(&mut self, uuid: Uuid) { self.loading_icon = self.loading_icon.next(); self.is_loading.insert(uuid); } - /// if is_loading, return loading animation frame, else single space + /// If is_loading has any entries, return the current loading_icon, else an emtpy string pub fn get_loading(&mut self) -> String { if self.is_loading.is_empty() { - String::from(" ") + String::new() } else { self.loading_icon.to_string() } } - /// set is_loading to false, but keep animation frame at same state + /// Remove a loading_uuid from the is_loading hashset pub fn remove_loading(&mut self, uuid: Uuid) { self.is_loading.remove(&uuid); } From 991448eb3cd033afaba5316572b1e30325b06d9e Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Fri, 7 Oct 2022 20:33:53 +0000 Subject: [PATCH 20/22] docs: changelog --- CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38933d4..76cb81a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,11 +5,15 @@ ### Docs + readme.md updated, [a05bf561cc6d96237f683ab0b3c782d6841974d9] +### Features ++ use newtype construct for container id, [41cbb84f2896f8be2c37eba87e390d998aff7382] + ### Refactors + Impl Copy where able to, [e76878f424d72b943713ef84e95e25fada77d79e] + async fn to just fn, [17dc604befac75cb9dc0311a0e43f9927fe0ca30] - - ++ remove pointless clone()'s & variable declarations, [6731002ee42c9460042c2c38aff5101b1bcebbe6] ++ replace Strig::from("") with String::new(), [62fb22478697cc9a7ab9fb562a724965b437233a] ++ replace map_or_else with map_or, [3e26f292c7dc5e13af4580952767ebe821aa5183], [5660b34d5149dce27706ff6daa90b854e6f84e14] # v0.1.4 ### 2022-09-07 From b5055b4a7c84057854eda0790c17ad44c74195ce Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Fri, 7 Oct 2022 21:01:09 +0000 Subject: [PATCH 21/22] docs: changelog --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76cb81a..a25f689 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,9 +10,9 @@ ### Refactors + Impl Copy where able to, [e76878f424d72b943713ef84e95e25fada77d79e] -+ async fn to just fn, [17dc604befac75cb9dc0311a0e43f9927fe0ca30] ++ replace async fn with just fn, [17dc604befac75cb9dc0311a0e43f9927fe0ca30] + remove pointless clone()'s & variable declarations, [6731002ee42c9460042c2c38aff5101b1bcebbe6] -+ replace Strig::from("") with String::new(), [62fb22478697cc9a7ab9fb562a724965b437233a] ++ replace String::from("") with String::new(), [62fb22478697cc9a7ab9fb562a724965b437233a] + replace map_or_else with map_or, [3e26f292c7dc5e13af4580952767ebe821aa5183], [5660b34d5149dce27706ff6daa90b854e6f84e14] # v0.1.4 From 6492012d5fb0fe50798c8281a5f934a83624a7d6 Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Fri, 7 Oct 2022 21:13:21 +0000 Subject: [PATCH 22/22] chore: release v0.1.5 --- .github/release-body.md | 25 ++++++++++++------------- CHANGELOG.md | 19 +++++++++++-------- Cargo.toml | 2 +- src/app_data/mod.rs | 22 +++++++--------------- 4 files changed, 31 insertions(+), 37 deletions(-) diff --git a/.github/release-body.md b/.github/release-body.md index 895c033..f83c62b 100644 --- a/.github/release-body.md +++ b/.github/release-body.md @@ -1,22 +1,21 @@ -### 2022-09-07 +### 2022-10-07 + ### Chores -+ dependencies updated, [a3168daa3f769a6747dfbe61103073a7e80a1485], [78e59160bb6a978ee80e3a99eb72f051fb64e737] ++ Update clap to v4, [15597dbe6942ec053541398ce0e9dedc10a4d3ea] + +### Docs ++ readme.md updated, [a05bf561cc6d96237f683ab0b3c782d6841974d9] ### Features -+ containerize self, github action to build and push to [Docker Hub](https://hub.docker.com/r/mrjackwills/oxker), [07f972022a69f22bac57925e6ad84234381f7890] -+ gui_state is_loading use a HashSet to enable multiple things be loading at the same time, [66583e1b037b7e2f3e47948d70d8a4c6f6a2f2d5] -+ github action publish to crates.io, [90b2e3f6db0d5f63840cd80888a30da6ecc22f20] -+ derive Eq where appropriate, [d7c2601f959bc12a64cd25cef59c837e1e8c2b2a] -+ ignore containers 'oxker' containers, [1be9f52ad4a68f93142784e9df630c59cdec0a79] -+ update container info if container is either running OR restarting, [5f12362db7cb61ca68f75b99ecfc9725380d87d2] - -### Fixes -+ devcontainer updated, [3bde4f5629539cab3dbb57556663ab81685f9d7a] -+ Use Binate enum to enable two cycles of cpu/mem update to be executed (for each container) at the same time, refactor hashmap spawn insertions, [7ec58e79a1316ad1f7e50a2781dea0fe8422c588] ++ use newtype construct for container id, [41cbb84f2896f8be2c37eba87e390d998aff7382] ### Refactors -+ improved way to remove leading '/' of container name, [832e9782d7765872cbb84df6b3703fc08cb353c9] ++ Impl Copy where able to, [e76878f424d72b943713ef84e95e25fada77d79e] ++ replace async fn with just fn, [17dc604befac75cb9dc0311a0e43f9927fe0ca30] ++ remove pointless clone()'s & variable declarations, [6731002ee42c9460042c2c38aff5101b1bcebbe6] ++ replace String::from("") with String::new(), [62fb22478697cc9a7ab9fb562a724965b437233a] ++ replace map_or_else with map_or, [3e26f292c7dc5e13af4580952767ebe821aa5183], [5660b34d5149dce27706ff6daa90b854e6f84e14] see CHANGELOG.md for more details diff --git a/CHANGELOG.md b/CHANGELOG.md index a25f689..0ac02d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,19 +1,22 @@ +# v0.1.5 +### 2022-10-07 + ### Chores -+ Update clap to v4, [15597dbe6942ec053541398ce0e9dedc10a4d3ea] ++ Update clap to v4, [15597dbe](https://github.com/mrjackwills/oxker/commit/15597dbe6942ec053541398ce0e9dedc10a4d3ea), ### Docs -+ readme.md updated, [a05bf561cc6d96237f683ab0b3c782d6841974d9] ++ readme.md updated, [a05bf561](https://github.com/mrjackwills/oxker/commit/a05bf561cc6d96237f683ab0b3c782d6841974d9), ### Features -+ use newtype construct for container id, [41cbb84f2896f8be2c37eba87e390d998aff7382] ++ use newtype construct for container id, [41cbb84f](https://github.com/mrjackwills/oxker/commit/41cbb84f2896f8be2c37eba87e390d998aff7382), ### Refactors -+ Impl Copy where able to, [e76878f424d72b943713ef84e95e25fada77d79e] -+ replace async fn with just fn, [17dc604befac75cb9dc0311a0e43f9927fe0ca30] -+ remove pointless clone()'s & variable declarations, [6731002ee42c9460042c2c38aff5101b1bcebbe6] -+ replace String::from("") with String::new(), [62fb22478697cc9a7ab9fb562a724965b437233a] -+ replace map_or_else with map_or, [3e26f292c7dc5e13af4580952767ebe821aa5183], [5660b34d5149dce27706ff6daa90b854e6f84e14] ++ Impl Copy where able to, [e76878f4](https://github.com/mrjackwills/oxker/commit/e76878f424d72b943713ef84e95e25fada77d79e), ++ replace async fn with just fn, [17dc604b](https://github.com/mrjackwills/oxker/commit/17dc604befac75cb9dc0311a0e43f9927fe0ca30), ++ remove pointless clone()'s & variable declarations, [6731002e](https://github.com/mrjackwills/oxker/commit/6731002ee42c9460042c2c38aff5101b1bcebbe6), ++ replace String::from("") with String::new(), [62fb2247](https://github.com/mrjackwills/oxker/commit/62fb22478697cc9a7ab9fb562a724965b437233a), ++ replace map_or_else with map_or, [3e26f292](https://github.com/mrjackwills/oxker/commit/3e26f292c7dc5e13af4580952767ebe821aa5183),, [5660b34d](https://github.com/mrjackwills/oxker/commit/5660b34d5149dce27706ff6daa90b854e6f84e14), # v0.1.4 ### 2022-09-07 diff --git a/Cargo.toml b/Cargo.toml index 79d4580..bb371ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "oxker" -version = "0.1.4" +version = "0.1.5" edition = "2021" authors = ["Jack Wills "] description = "A simple tui to view & control docker containers" diff --git a/src/app_data/mod.rs b/src/app_data/mod.rs index c137fbf..abb6f8b 100644 --- a/src/app_data/mod.rs +++ b/src/app_data/mod.rs @@ -301,8 +301,7 @@ impl AppData { } } - - /// Check if the initial parsing has been completed, by making sure that all ids given (which are running) have a non empty cpu_stats vecdec + /// Check if the initial parsing has been completed, by making sure that all ids given (which are running) have a non empty cpu_stats vecdec pub fn initialised(&mut self, all_ids: &[(bool, ContainerId)]) -> bool { let count_is_running = all_ids.iter().filter(|i| i.0).count(); let number_with_cpu_status = self @@ -445,8 +444,8 @@ impl AppData { } } } - // Trim a &String and return String - let trim_owned = |x: &String| x.trim().to_owned(); + // Trim a &String and return String + let trim_owned = |x: &String| x.trim().to_owned(); for i in all_containers { if let Some(id) = i.id.as_ref() { @@ -459,15 +458,8 @@ impl AppData { }) }); - let state = State::from( - i.state - .as_ref() - .map_or("dead".to_owned(), trim_owned), - ); - let status = i - .status - .as_ref() - .map_or("".to_owned(), trim_owned); + let state = State::from(i.state.as_ref().map_or("dead".to_owned(), trim_owned)); + let status = i.status.as_ref().map_or("".to_owned(), trim_owned); let image = i .image @@ -527,8 +519,8 @@ impl AppData { container.logs.items.push(ListItem::new(lines)); } - // Set the logs selected row for each container - // Either when no long currently selected, or currently selected (before updated) is already at end + // Set the logs selected row for each container + // Either when no long currently selected, or currently selected (before updated) is already at end if container.logs.state.selected().is_none() || container.logs.state.selected().map_or(1, |f| f + 1) == current_len {