From fdacab9c804e31301815397c1030649541e2cea0 Mon Sep 17 00:00:00 2001 From: arcstur Date: Thu, 23 May 2024 18:58:07 -0300 Subject: [PATCH] fix: use BufWriter in list command to avoid println! in a loop --- src/commands/list.rs | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/src/commands/list.rs b/src/commands/list.rs index eebb3e2..f79224a 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -4,6 +4,7 @@ use crate::models; use api::client::ApiClient; use colored::Colorize; use models::ResultWithDefaultError; +use std::io::{self, BufWriter, Write}; pub struct ListCommand; @@ -19,19 +20,31 @@ impl ListCommand { "Couldn't fetch time entries the from API".red(), error ), - Ok(entities) => match entity.unwrap_or(Entity::TimeEntry) { - Entity::TimeEntry => entities - .time_entries - .iter() - .take(count.unwrap_or(usize::max_value())) - .for_each(|time_entry| println!("{}", time_entry)), + Ok(entities) => { + // use this to avoid calling println! in a loop: + // + let stdout = io::stdout(); + let mut handle = BufWriter::new(stdout); - Entity::Project => entities - .projects - .iter() - .take(count.unwrap_or(usize::max_value())) - .for_each(|(_, projects)| println!("{}", projects)), - }, + // TODO: better error handling for writeln! + match entity.unwrap_or(Entity::TimeEntry) { + Entity::TimeEntry => entities + .time_entries + .iter() + .take(count.unwrap_or(usize::max_value())) + .for_each(|time_entry| { + writeln!(handle, "{}", time_entry).expect("failed to print") + }), + + Entity::Project => entities + .projects + .iter() + .take(count.unwrap_or(usize::max_value())) + .for_each(|(_, projects)| { + writeln!(handle, "{}", projects).expect("failed to print") + }), + }; + } } Ok(()) }