From 40489705fb88a50956487cc04d08a824f5722841 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Artur=20Corr=C3=AAa=20Souza?= Date: Fri, 24 May 2024 09:54:26 -0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=82=20use=20BufWriter=20in=20list=20co?= =?UTF-8?q?mmand=20to=20avoid=20println!=20in=20a=20loop=20(#75)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 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(()) }