refactor: clone()'s removed, allow(precision_loss)

This commit is contained in:
Jack Wills
2022-10-02 01:14:42 +00:00
parent f5fc446295
commit 6bee4d007a
4 changed files with 38 additions and 36 deletions
+8 -2
View File
@@ -337,6 +337,8 @@ impl ByteStats {
self.value = value; self.value = value;
} }
} }
#[allow(clippy::cast_precision_loss)]
impl Stats for ByteStats { impl Stats for ByteStats {
fn get_value(&self) -> f64 { fn get_value(&self) -> f64 {
self.value as f64 self.value as f64
@@ -346,7 +348,7 @@ 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 { impl fmt::Display for ByteStats {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 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 { let p = match as_f64 {
x if x >= ONE_GB => format!("{y:.2} GB", y = as_f64 / ONE_GB), 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), 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 { pub fn new(id: ContainerId, 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(); docker_controls.start();
let mut logs = StatefulList::new(vec![]);
logs.end();
Self { Self {
cpu_stats: VecDeque::with_capacity(60), cpu_stats: VecDeque::with_capacity(60),
docker_controls, docker_controls,
id, id,
image, image,
last_updated: 0, last_updated: 0,
logs: StatefulList::new(vec![]), logs,
mem_limit: ByteStats::default(), mem_limit: ByteStats::default(),
mem_stats: VecDeque::with_capacity(60), mem_stats: VecDeque::with_capacity(60),
name, name,
@@ -417,6 +421,7 @@ impl ContainerItem {
} }
/// Convert cpu stats into a vec for the charts function /// Convert cpu stats into a vec for the charts function
#[allow(clippy::cast_precision_loss)]
fn get_cpu_dataset(&self) -> Vec<(f64, f64)> { fn get_cpu_dataset(&self) -> Vec<(f64, f64)> {
self.cpu_stats self.cpu_stats
.iter() .iter()
@@ -426,6 +431,7 @@ impl ContainerItem {
} }
/// Convert mem stats into a Vec for the charts function /// Convert mem stats into a Vec for the charts function
#[allow(clippy::cast_precision_loss)]
fn get_mem_dataset(&self) -> Vec<(f64, f64)> { fn get_mem_dataset(&self) -> Vec<(f64, f64)> {
self.mem_stats self.mem_stats
.iter() .iter()
+24 -28
View File
@@ -163,7 +163,7 @@ impl AppData {
} }
/// Find the id of the currently selected container. /// 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. /// Only returns None when no containers found.
pub fn get_selected_container_id(&self) -> Option<ContainerId> { pub fn get_selected_container_id(&self) -> Option<ContainerId> {
let mut output = None; let mut output = None;
@@ -323,6 +323,7 @@ impl AppData {
let mut output = Columns::new(); let mut output = Columns::new();
let count = |x: &String| x.chars().count(); let count = |x: &String| x.chars().count();
// Should probably find a refactor here somewhere
for container in &self.containers.items { for container in &self.containers.items {
let cpu_count = count( let cpu_count = count(
&container &container
@@ -418,18 +419,18 @@ impl AppData {
} }
/// Update, or insert, containers /// 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(); 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(); self.containers.start();
} }
for (index, id) in all_ids.iter().enumerate() { for (index, id) in all_ids.iter().enumerate() {
if !containers if !all_containers
.iter() .iter()
.filter_map(|i| i.id.as_ref()) .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 // If removed container is currently selected, then change selected to previous
// This will default to 0 in any edge cases // 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() { 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| { let name = i.names.as_mut().map_or("".to_owned(), |n| {
n.get_mut(0).map_or("".to_owned(), |f| { n.get_mut(0).map_or("".to_owned(), |f| {
if f.starts_with('/') { if f.starts_with('/') {
f.remove(0); f.remove(0);
} }
f.clone() (*f).to_string()
}) })
}); });
@@ -470,36 +470,32 @@ impl AppData {
.as_ref() .as_ref()
.map_or("".to_owned(), std::clone::Clone::clone); .map_or("".to_owned(), std::clone::Clone::clone);
let id = ContainerId::from(id.as_str()); let id = ContainerId::from(id);
if let Some(current_container) = self.get_container_by_id(&id) { // If container info already in containers Vec, then just update details
if current_container.name != name { if let Some(item) = self.get_container_by_id(&id) {
current_container.name = name; if item.name != name {
item.name = name;
}; };
if current_container.status != status { if item.status != status {
current_container.status = status; item.status = status;
}; };
if current_container.state != state { if item.state != state {
current_container.docker_controls.items = DockerControls::gen_vec(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 // Update the list state, needs to be None if the gen_vec returns an empty vec
match state { match state {
State::Removing | State::Restarting | State::Unknown => { 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 { if item.image != image {
// limit image name to 64 chars? item.image = image;
// current_container.image = image.chars().into_iter().take(64).collect();
current_container.image = image;
}; };
// else container not known, so make new ContainerItem and push into containers Vec
} else { } else {
// limit image name to 64 chars? let container = ContainerItem::new(id, status, image, 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); self.containers.items.push(container);
} }
} }
+2 -2
View File
@@ -63,6 +63,7 @@ pub struct DockerData {
impl DockerData { impl DockerData {
/// Use docker stats to caluclate current cpu usage /// Use docker stats to caluclate current cpu usage
#[allow(clippy::cast_precision_loss)]
fn calculate_usage(stats: &Stats) -> f64 { fn calculate_usage(stats: &Stats) -> f64 {
let mut cpu_percentage = 0.0; let mut cpu_percentage = 0.0;
let previous_cpu = stats.precpu_stats.cpu_usage.total_usage; let previous_cpu = stats.precpu_stats.cpu_usage.total_usage;
@@ -79,7 +80,7 @@ impl DockerData {
.cpu_usage .cpu_usage
.percpu_usage .percpu_usage
.as_ref() .as_ref()
.map_or_else(|| 0, |i| i.len()) as u64 .map_or_else(|| 0, std::vec::Vec::len) as u64
}) as f64; }) as f64;
if system_delta > 0.0 && cpu_delta > 0.0 { if system_delta > 0.0 && cpu_delta > 0.0 {
cpu_percentage = (cpu_delta / system_delta) * online_cpus * 100.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 app_data = Arc::clone(&self.app_data);
let spawns = Arc::clone(&self.spawns); let spawns = Arc::clone(&self.spawns);
let key = SpawnId::Stats((id.clone(), self.binate)); let key = SpawnId::Stats((id.clone(), self.binate));
let spawn_key = key.clone(); let spawn_key = key.clone();
self.spawns.lock().entry(key).or_insert_with(|| { self.spawns.lock().entry(key).or_insert_with(|| {
tokio::spawn(Self::update_container_stat( tokio::spawn(Self::update_container_stat(
+4 -4
View File
@@ -10,11 +10,11 @@ pub mod log_sanitizer {
pub fn colorize_logs<'a>(input: &str) -> Vec<Spans<'a>> { pub fn colorize_logs<'a>(input: &str) -> Vec<Spans<'a>> {
vec![Spans::from( vec![Spans::from(
categorise_text(input) categorise_text(input)
.into_iter() .iter()
.map(|i| { .map(|i| {
let fg_color = color_ansi_to_tui(i.fg.unwrap_or(CansiColor::White)); let style = Style::default()
let bg_color = color_ansi_to_tui(i.bg.unwrap_or(CansiColor::Black)); .bg(color_ansi_to_tui(i.fg.unwrap_or(CansiColor::White)))
let style = Style::default().bg(bg_color).fg(fg_color); .fg(color_ansi_to_tui(i.bg.unwrap_or(CansiColor::Black)));
if i.blink.is_some() { if i.blink.is_some() {
style.add_modifier(Modifier::SLOW_BLINK); style.add_modifier(Modifier::SLOW_BLINK);
} }