From 5b78b96fa11ab6d66e1dbf877189f62502a7174f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Marcos=20P=2E=20Bezerra?= Date: Sun, 17 Nov 2024 23:39:31 -0300 Subject: [PATCH] fix: warnings not shown before stdin interaction --- src/utils/io.rs | 4 ++++ src/utils/logger.rs | 29 +++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/utils/io.rs b/src/utils/io.rs index 7e05d84e3..27a1aef91 100644 --- a/src/utils/io.rs +++ b/src/utils/io.rs @@ -1,8 +1,12 @@ use std::io::{self, stderr, stdout, StderrLock, StdoutLock, Write}; +use crate::utils::logger; + type StdioOutputLocks = (StdoutLock<'static>, StderrLock<'static>); pub fn lock_and_flush_output_stdio() -> io::Result { + logger::flush_messages(); + let mut stdout = stdout().lock(); stdout.flush()?; let mut stderr = stderr().lock(); diff --git a/src/utils/logger.rs b/src/utils/logger.rs index c03dd9af8..aeedecd34 100644 --- a/src/utils/logger.rs +++ b/src/utils/logger.rs @@ -1,10 +1,16 @@ -use std::sync::{mpsc, OnceLock}; +use std::sync::{mpsc, Arc, Barrier, OnceLock}; pub use logger_thread::spawn_logger_thread; use super::colors::{ORANGE, RESET, YELLOW}; use crate::accessible::is_running_in_accessible_mode; +/// Asks logger to flush all messages, useful before starting STDIN interaction. +#[track_caller] +pub fn flush_messages() { + logger_thread::send_flush_message_and_wait(); +} + /// An `[INFO]` log to be displayed if we're not running accessibility mode. /// /// Same as `.info_accessible()`, but only displayed if accessibility mode @@ -49,6 +55,7 @@ pub fn warning(contents: String) { #[derive(Debug)] enum Message { + Flush { finished_barrier: Arc }, FlushAndShutdown, PrintMessage(PrintMessage), } @@ -134,6 +141,19 @@ mod logger_thread { .expect("Failed to send shutdown message"); } + #[track_caller] + pub(super) fn send_flush_message_and_wait() { + let barrier = Arc::new(Barrier::new(2)); + + get_sender() + .send(Message::Flush { + finished_barrier: barrier.clone(), + }) + .expect("Failed to send shutdown message"); + + barrier.wait(); + } + pub struct LoggerThreadHandle { shutdown_barrier: Arc, } @@ -173,7 +193,7 @@ mod logger_thread { } fn run_logger(log_receiver: LogReceiver, shutdown_barrier: Arc) { - const FLUSH_TIMEOUT: Duration = Duration::from_millis(250); + const FLUSH_TIMEOUT: Duration = Duration::from_millis(200); let mut buffer = Vec::::with_capacity(16); @@ -202,6 +222,11 @@ mod logger_thread { flush_logs_to_stderr(&mut buffer); break; } + Message::Flush { finished_barrier } => { + flush_logs_to_stderr(&mut buffer); + finished_barrier.wait(); + break; + } } }