Skip to content

Commit

Permalink
fix: warnings not shown before stdin interaction
Browse files Browse the repository at this point in the history
  • Loading branch information
marcospb19 committed Nov 18, 2024
1 parent 639ef19 commit 5b78b96
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
4 changes: 4 additions & 0 deletions src/utils/io.rs
Original file line number Diff line number Diff line change
@@ -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<StdioOutputLocks> {
logger::flush_messages();

let mut stdout = stdout().lock();
stdout.flush()?;
let mut stderr = stderr().lock();
Expand Down
29 changes: 27 additions & 2 deletions src/utils/logger.rs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -49,6 +55,7 @@ pub fn warning(contents: String) {

#[derive(Debug)]
enum Message {
Flush { finished_barrier: Arc<Barrier> },
FlushAndShutdown,
PrintMessage(PrintMessage),
}
Expand Down Expand Up @@ -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<Barrier>,
}
Expand Down Expand Up @@ -173,7 +193,7 @@ mod logger_thread {
}

fn run_logger(log_receiver: LogReceiver, shutdown_barrier: Arc<Barrier>) {
const FLUSH_TIMEOUT: Duration = Duration::from_millis(250);
const FLUSH_TIMEOUT: Duration = Duration::from_millis(200);

let mut buffer = Vec::<String>::with_capacity(16);

Expand Down Expand Up @@ -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;
}
}
}

Expand Down

0 comments on commit 5b78b96

Please sign in to comment.