rm-lisa 0.3.2

A logging library for rem-verse, with support for inputs, tasks, and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
//! Renderers are responsible for actually rendering a series of log lines.
//!
//! They take in a structure of data that contains an arbitrary sequence of
//! bytes that represent at least one line of a log (or potentially more if the
//! line is very long and we want to split it up!), some metadata attached to
//! that log line, and gives us the final human readable representation.
//!
//! There's nothing special about the renderers implemented in our crate, and
//! if you want to print a custom format, include or exclude certain things you
//! can do so by implementing the [`ConsoleRenderer`] trait.
//!
//! ## Note about ANSI Enabling Code
//!
//! Code related to ANSI-enablement for Windows has been based off of crossterm which
//! is licensed under MIT at the point of forking:
//! <https://github.com/crossterm-rs/crossterm/blob/d5b0e0700752b37cda613c949b7bbe78f956f166/LICENSE>
//!
//! The code has been modified to remove support from the winapi crate, and
//! instead depend on [`windows`] also removed the dependency on once-cell, and
//! instead use the stabilized lazy features of std.

mod color;
mod json;
mod text;

pub use crate::display::renderers::{
	color::ColorConsoleRenderer, json::JSONConsoleRenderer, text::TextConsoleRenderer,
};

use crate::{
	display::tracing::SuperConsoleLogMessage,
	errors::LisaError,
	input::{InputProvider, TerminalInputEvent},
	tasks::{GloballyUniqueTaskId, LisaTaskStatus, TaskEvent},
};
use chrono::{DateTime, Utc};
use fnv::FnvHashMap;
use regex::Regex;
use std::{
	collections::VecDeque,
	fs::File,
	io::{
		BufWriter, Cursor, Empty, IsTerminal, LineWriter, PipeWriter, Sink, Stderr, StderrLock,
		Stdout, StdoutLock, Write,
	},
	net::TcpStream,
	sync::{Arc, OnceLock},
};

#[cfg(unix)]
use std::os::unix::net::UnixStream;
#[cfg(target_os = "windows")]
use std::{
	env::var as env_var,
	sync::{
		Once,
		atomic::{AtomicBool, Ordering as AtomicOrdering},
	},
};
#[cfg(target_os = "windows")]
use windows::Win32::System::Console::{
	CONSOLE_MODE, ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle,
	STD_ERROR_HANDLE, STD_OUTPUT_HANDLE, SetConsoleMode,
};

#[cfg(target_os = "windows")]
/// If we've tried to enable ansi support...
static STDOUT_ANSI_INITIALIZER: Once = Once::new();
#[cfg(target_os = "windows")]
/// Whether or not we do support ANSI Escape Codes.
static STDOUT_SUPPORTS_ANSI_ESCAPE_CODES: AtomicBool = AtomicBool::new(false);

#[cfg(target_os = "windows")]
/// If we've tried to enable ansi support...
static STDERR_ANSI_INITIALIZER: Once = Once::new();
#[cfg(target_os = "windows")]
/// Whether or not we do support ANSI Escape Codes.
static STDERR_SUPPORTS_ANSI_ESCAPE_CODES: AtomicBool = AtomicBool::new(false);
/// Copy of ansi escape code regex that we use for ensuring colored
/// output doesn't get printed!
static ANSI_ESCAPE_CODE_REGEX: OnceLock<Regex> = OnceLock::new();

/// Get a regex that can match all ANSI Escape Codes.
pub fn get_ansi_escape_code_regex() -> Regex {
	ANSI_ESCAPE_CODE_REGEX
		.get_or_init(|| {
			let Ok(regex) = Regex::new(
				r"(?:\x1B[@-Z\\-_]|[\x80-\x9A\x9C-\x9F]|(?:\x1B\[|\x9B)[0-?]*[ -/]*[@-~])",
			) else {
				unimplemented!("Regex is validated pre-compile time...");
			};

			regex
		})
		.clone()
}

/// An arbitrary structure that is capable of rendering log lines.
pub trait ConsoleRenderer: Send + Sync {
	/// Get a renderer if it is compatible, and should be used with a set of
	/// stream features.
	///
	/// The first console renderer that returns true will be used.
	///
	/// ## Parameters
	///
	/// - `features`: The current features for this particular stream.
	/// - `environment_prefix`: a prefix to apply to environment variables,
	///   usually the app name. This makes it so you can have multiple CLI
	///   tools that are each controlled with things like:
	///   `${APP_NAME}_LOG_FORMAT`. Lets say your app name was "sprig", in this
	///   case the environment prefix would be: "SPRIG_".
	#[must_use]
	fn should_use_renderer(
		&self,
		stream_features: &dyn ConsoleOutputFeatures,
		environment_prefix: &str,
	) -> bool;

	/// Return if this renderer supports 'cursor movement', using ANSI escape
	/// codes or similar to move the cursor.
	///
	/// This will enable left/right arrow movement on the associated input
	/// provider.
	#[must_use]
	fn supports_ansi(&self) -> bool;

	/// Get the default PS1 to use for this renderer, if none was provided.
	#[must_use]
	fn default_ps1(&self) -> String;

	/// Update the 'PS1', or characters the get rendered before typing in a
	/// command.
	fn update_ps1(&self, new_ps1: String);

	/// Clear any previously rendered input line if one was rendered.
	#[must_use]
	fn clear_input(&self, term_width: u16) -> String;
	/// Clear any previous rendered tasks in our task list.
	#[must_use]
	fn clear_task_list(&self, task_list_size: usize) -> String;
	/// A flag used to 'pause' rendering log events for awhile.
	///
	/// This will prevent [`ConsoleRenderer::render_message`] calls for your
	/// renderer until this returns false. This should ideally only be used for
	/// renderers that need to pause rendering _while_ user input is happening
	/// because ASCII codes for erasing aren't supported.
	#[must_use]
	fn should_pause_log_events(&self, provider: &dyn InputProvider) -> bool;

	/// Render a log message.
	///
	/// This message will be printed directly to it's source, whether that be
	/// standard out, or standard error. This *can* span multiple lines.
	///
	/// ## Errors
	///
	/// If we can't format the log message into a string, or some other
	/// processing error dependening on the renderer.
	fn render_message(
		&self,
		app_name: &'static str,
		log: SuperConsoleLogMessage,
		term_width: u16,
	) -> Result<String, LisaError>;

	/// Render the console 'input' line for a particular provider.
	///
	/// It is the job of this method to query the provider, and determine how to
	/// render the users input in the terminal.
	///
	/// ## Errors
	///
	/// If we can't format the input line into a string, or other processing
	/// error occurs.
	fn render_input(
		&self,
		app_name: &'static str,
		provider: &dyn InputProvider,
		term_width: u16,
	) -> Result<String, LisaError>;

	/// Re-render the task (you can assume it has been erased by this time it is called).
	///
	/// Passed in will be all new events that have happened (incase you want to render any task
	/// updates), along with the current task states after all `new_task_events` have been
	/// applied.
	///
	/// ## Errors
	///
	/// If there is any error related to rendering tasks, usually a formatting
	/// error but depends on the specific renderer.
	fn rerender_tasks(
		&self,
		new_task_events: &[TaskEvent],
		current_task_states: &FnvHashMap<
			GloballyUniqueTaskId,
			(DateTime<Utc>, String, LisaTaskStatus),
		>,
		tasks_running_since: Option<DateTime<Utc>>,
		term_height: u16,
	) -> Result<String, LisaError>;

	/// Do a 'quick render' of any sort of input, or handle an input on any kind.
	///
	/// This should be as immediate as possible to reduce any sort of latency
	/// from the users who are typing.
	///
	/// ## Errors
	///
	/// If we can't format the input line into a string, or other processing
	/// error occurs.
	fn on_input(
		&self,
		event: TerminalInputEvent,
		provider: &dyn InputProvider,
	) -> Result<String, LisaError>;
}

/// Describe an arbitrary set of features that are available on an output.
///
/// Most outputs should automatically have this implemented, but if you're
/// using a custom type you may need to implement it yourself.
pub trait ConsoleOutputFeatures {
	/// If this output is a TTY.
	#[must_use]
	fn is_atty(&self) -> bool;

	/// Attempt to enable ANSI support, this will return whether or not enabling
	/// was successful.
	#[must_use]
	fn enable_ansi(&self) -> bool;
}

impl ConsoleOutputFeatures for Stdout {
	fn is_atty(&self) -> bool {
		self.is_terminal()
	}

	/// Only windows terminals have to have ansi ENABLED.
	#[cfg(not(target_os = "windows"))]
	fn enable_ansi(&self) -> bool {
		true
	}

	#[cfg(target_os = "windows")]
	fn enable_ansi(&self) -> bool {
		enable_ansi_stdout()
	}
}
impl ConsoleOutputFeatures for StdoutLock<'_> {
	fn is_atty(&self) -> bool {
		self.is_terminal()
	}

	/// Only windows terminals have to have ansi ENABLED.
	#[cfg(not(target_os = "windows"))]
	fn enable_ansi(&self) -> bool {
		true
	}

	#[cfg(target_os = "windows")]
	fn enable_ansi(&self) -> bool {
		enable_ansi_stdout()
	}
}

impl ConsoleOutputFeatures for Stderr {
	fn is_atty(&self) -> bool {
		self.is_terminal()
	}

	/// Only windows terminals have to have ansi ENABLED.
	#[cfg(not(target_os = "windows"))]
	fn enable_ansi(&self) -> bool {
		true
	}

	#[cfg(target_os = "windows")]
	fn enable_ansi(&self) -> bool {
		enable_ansi_stderr()
	}
}
impl ConsoleOutputFeatures for StderrLock<'_> {
	fn is_atty(&self) -> bool {
		self.is_terminal()
	}

	/// Only windows terminals have to have ansi ENABLED.
	#[cfg(not(target_os = "windows"))]
	fn enable_ansi(&self) -> bool {
		true
	}

	#[cfg(target_os = "windows")]
	fn enable_ansi(&self) -> bool {
		enable_ansi_stderr()
	}
}

/// Implement [`ConsoleOutputFeatures`] for lots of types quickly....
macro_rules! impl_default_output_features {
	($type:ty) => {
		impl ConsoleOutputFeatures for $type {
			fn is_atty(&self) -> bool {
				false
			}

			fn enable_ansi(&self) -> bool {
				true
			}
		}
	};
}
impl_default_output_features!(File);
impl_default_output_features!(TcpStream);
impl_default_output_features!(&mut [u8]);
#[cfg(unix)]
impl_default_output_features!(UnixStream);
impl_default_output_features!(Arc<File>);
impl_default_output_features!(Cursor<&mut [u8]>);
impl_default_output_features!(Empty);
impl_default_output_features!(PipeWriter);
impl_default_output_features!(Sink);
#[cfg(unix)]
impl_default_output_features!(&'_ UnixStream);
impl_default_output_features!(Cursor<&mut Vec<u8>>);
impl_default_output_features!(Cursor<Box<[u8]>>);
impl_default_output_features!(Cursor<Vec<u8>>);
impl_default_output_features!(VecDeque<u8>);
impl_default_output_features!(Vec<u8>);

impl<Inner: ConsoleOutputFeatures> ConsoleOutputFeatures for Box<Inner> {
	fn is_atty(&self) -> bool {
		(*(*self)).is_atty()
	}

	fn enable_ansi(&self) -> bool {
		(*(*self)).enable_ansi()
	}
}

impl<Inner: ConsoleOutputFeatures + Write> ConsoleOutputFeatures for BufWriter<Inner> {
	fn is_atty(&self) -> bool {
		self.get_ref().is_atty()
	}

	fn enable_ansi(&self) -> bool {
		self.get_ref().enable_ansi()
	}
}

impl<Inner: ConsoleOutputFeatures + Write> ConsoleOutputFeatures for LineWriter<Inner> {
	fn is_atty(&self) -> bool {
		self.get_ref().is_atty()
	}

	fn enable_ansi(&self) -> bool {
		self.get_ref().enable_ansi()
	}
}

impl<const N: usize> ConsoleOutputFeatures for Cursor<[u8; N]> {
	fn is_atty(&self) -> bool {
		false
	}

	fn enable_ansi(&self) -> bool {
		true
	}
}

#[cfg(target_os = "windows")]
#[must_use]
fn enable_ansi_stdout() -> bool {
	STDOUT_ANSI_INITIALIZER.call_once(|| {
		// Some terminals on Windows like GitBash can't use WinAPI calls directly
		// so when we try to enable the ANSI-flag for Windows this won't work.
		// Because of that we should check first if the TERM-variable is set
		// and see if the current terminal is a terminal who does support ANSI.
		let vt_processing_result = {
			if let Ok(handle) = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) } {
				let mask = ENABLE_VIRTUAL_TERMINAL_PROCESSING;
				let mut current_console_mode = CONSOLE_MODE(0);
				let was_success_get =
					unsafe { GetConsoleMode(handle, &raw mut current_console_mode).is_ok() };

				let mut was_success_set = false;
				if was_success_get {
					if current_console_mode.0 & mask.0 == 0 {
						current_console_mode.0 |= mask.0;
						was_success_set =
							unsafe { SetConsoleMode(handle, current_console_mode).is_ok() };
					} else {
						was_success_set = true;
					}
				}

				was_success_get && was_success_set
			} else {
				false
			}
		};

		STDOUT_SUPPORTS_ANSI_ESCAPE_CODES.store(
			vt_processing_result || env_var("TERM").is_ok_and(|term| term != "dumb"),
			AtomicOrdering::SeqCst,
		);
	});

	STDOUT_SUPPORTS_ANSI_ESCAPE_CODES.load(AtomicOrdering::SeqCst)
}

#[cfg(target_os = "windows")]
#[must_use]
fn enable_ansi_stderr() -> bool {
	STDERR_ANSI_INITIALIZER.call_once(|| {
		// Some terminals on Windows like GitBash can't use WinAPI calls directly
		// so when we try to enable the ANSI-flag for Windows this won't work.
		// Because of that we should check first if the TERM-variable is set
		// and see if the current terminal is a terminal who does support ANSI.
		let vt_processing_result = {
			if let Ok(handle) = unsafe { GetStdHandle(STD_ERROR_HANDLE) } {
				let mask = ENABLE_VIRTUAL_TERMINAL_PROCESSING;
				let mut current_console_mode = CONSOLE_MODE(0);
				let was_success_get =
					unsafe { GetConsoleMode(handle, &raw mut current_console_mode).is_ok() };

				let mut was_success_set = false;
				if was_success_get {
					if current_console_mode.0 & mask.0 == 0 {
						current_console_mode.0 |= mask.0;
						was_success_set =
							unsafe { SetConsoleMode(handle, current_console_mode).is_ok() };
					} else {
						was_success_set = true;
					}
				}

				was_success_get && was_success_set
			} else {
				false
			}
		};

		STDERR_SUPPORTS_ANSI_ESCAPE_CODES.store(
			vt_processing_result || env_var("TERM").is_ok_and(|term| term != "dumb"),
			AtomicOrdering::SeqCst,
		);
	});

	STDERR_SUPPORTS_ANSI_ESCAPE_CODES.load(AtomicOrdering::SeqCst)
}

#[cfg(test)]
mod unit_tests {
	use super::*;

	// More of a compilation test, rather than a runtime test.
	#[test]
	pub fn can_get_regex() {
		_ = get_ansi_escape_code_regex();
	}

	#[test]
	pub fn stdout_output_features() {
		let stdout = std::io::stdout();

		assert_eq!(
			(&stdout as &dyn ConsoleOutputFeatures).is_atty(),
			stdout.is_terminal(),
			"Failed to check if stdout is a tty!",
		);
		// More of a compilation message.
		_ = stdout.enable_ansi();

		let locked = stdout.lock();
		assert_eq!(
			(&locked as &dyn ConsoleOutputFeatures).is_atty(),
			locked.is_terminal(),
			"Failed to check if stdout lock is a tty!",
		);
		// More of a compilation message.
		_ = locked.enable_ansi();
	}

	#[test]
	pub fn stderr_output_features() {
		let stderr = std::io::stderr();

		assert_eq!(
			(&stderr as &dyn ConsoleOutputFeatures).is_atty(),
			stderr.is_terminal(),
			"Failed to check if stderr is a tty!",
		);
		// More of a compilation message.
		_ = stderr.enable_ansi();

		let locked = stderr.lock();
		assert_eq!(
			(&locked as &dyn ConsoleOutputFeatures).is_atty(),
			locked.is_terminal(),
			"Failed to check if stderr lock is a tty!",
		);
		// More of a compilation message.
		_ = locked.enable_ansi();
	}

	#[test]
	pub fn default_output_features() {
		// File / Arc<File>
		{
			let temporary_file = tempfile::tempfile().expect("Failed to create temporary file!");
			assert!(!temporary_file.is_atty());
			assert!(temporary_file.enable_ansi());

			let arc = Arc::new(temporary_file);
			assert!(!arc.is_atty());
			assert!(arc.enable_ansi());
		}

		// Vec<u8> / &mut [u8] / Cursor<Vec<u8>> / VecDequeue<u8>
		{
			let mut data: Vec<u8> = Vec::new();

			assert!(!data.is_atty());
			assert!(data.enable_ansi());

			assert!(!(&mut data as &mut [u8]).is_atty());
			assert!((&mut data as &mut [u8]).enable_ansi());

			let cursor = Cursor::new(data);
			assert!(!cursor.is_atty());
			assert!(cursor.enable_ansi());

			let dequeue: VecDeque<u8> = VecDeque::new();
			assert!(!dequeue.is_atty());
			assert!(dequeue.enable_ansi());
		}

		// Cursor<&mut [u8]> / Cursor<&mut Vec<u8>> / Cursor<Box<[u8]>>
		{
			let mut data: Vec<u8> = Vec::new();

			{
				let to_cursor: &mut [u8] = &mut data;
				let cursor = Cursor::new(to_cursor);

				assert!(!cursor.is_atty());
				assert!(cursor.enable_ansi());
			}

			{
				let cursor: Cursor<&mut Vec<u8>> = Cursor::new(&mut data);
				assert!(!cursor.is_atty());
				assert!(cursor.enable_ansi());
			}

			{
				let cursor: Cursor<Box<[u8]>> = Cursor::new(data.into_boxed_slice());
				assert!(!cursor.is_atty());
				assert!(cursor.enable_ansi());
			}
		}

		{
			let empty = std::io::empty();
			assert!(!empty.is_atty());
			assert!(empty.enable_ansi());
		}
	}
}