conciliator 0.3.10

[WIP] Library for interactive CLI programs
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
/*! Core functionality: dealing with buffers of colored terminal output

Text is never written directly to the terminal, it is written into a buffer first, which then get printed.
The buffer is just a simple `Vec<u8>` (and a boolean to store whether colors are enabled), implementing [`Write`] and [`Paint`] to allow printing colored text.

Dealing with the buffers is somewhat unidiomatic, so it bears some explanation.
Here are four different ways to write the same status message to the terminal:
```rust,no_run
use std::io::Write;
use conciliator::Conciliator;

let con = conciliator::init();
let hello = "Hello";

con.status("Hello!");
con.status(format_args!("{hello}!"));
write!(con.status(..), "{hello}!").unwrap();
con.status(hello).push("!");
```
The [`con.status( … )`](crate::Conciliator::status) method returns a [`Line`], which:
- contains the status tag (e.g. `[ > ] `) and whatever was passed into it (`..` is used to specify "nothing", see [`InitialContent`]),
- implements [`Paint`] (and thus [`Write`]),
- automatically appends a newline (`\n`) character when it gets printed (unless overridden with [`Line::no_newline`]),

Finally, to avoid having to explicitly print every [`Line`], it holds a reference to the [`Stream`] it was obtained from, and the **destructor uses this reference to print the buffer** to the terminal.

*/
use std::env;
use std::fmt::Arguments;
use std::io::{
	self,
	IsTerminal,
	Write,
	Result as IoResult
};
use std::ops::{
	Deref,
	DerefMut
};

use crate::term::EmitEscapes;
use crate::style::Paint;
use crate::push::{
	Inline,
	Pushable
};
use super::Conciliator;

/// Wrapper around a standard output stream (`stdout` or `stderr`)
///
/// Does not implement [`Write`] or [`Paint`] itself.
///
/// While a buffer is written to the underlying stream, it is *locked* (i.e. [`io::Stdout::lock`]).
/// This is to ensure there is no interleaving of the contents of buffers, even in cases where there are multiple [`Stream`]s referencing the same standard output stream.
/// This idea is taken from [termcolor](https://crates.io/crates/termcolor).
///
/// #### Making `cargo test` capture output
///
/// Unfortunately, `cargo test`, will only capture output produced by the [`print!`], [`println!`], [`eprint!`], and [`eprintln!`] macros (see [rust#12309] and [rust#90785]).
/// To accommodate this, *printing has to work and behave differently during tests*: going through the [`print!`] or [`eprint!`] macro instead of directly writing the buffer content to the output stream.
///
/// Because this crate will not be compiled with `cfg(test)` when it is being compiled as a dependency of another crate, it is not possible to automatically choose the correct behavior.
/// Instead, it is controlled by the `test_capture` feature flag, which will unilaterally select the *worse but capture-able* behavior if it is enabled.
/// As mentioned in the [crate-level documentation](crate#capture-output-during-cargo-test), this is why you should **only** enable `test_capture` on a `[dev-dependencies]` entry and **never** for a regular dependency.
///
/// Using the macros to write output is worse because it somewhat arbitrarily restricts the content to be valid UTF-8 like a `&str` or `String`.
/// [`String::from_utf8_lossy`] is used (again, only if the `test_capture` feature is enabled) to enforce this on the content of [`Buffer`], which implements [`Write`] and as such can contain arbitrary byte sequences.
///
/// This means that output during tests, whether captured or not, will have "invalid UTF-8 sequences" replaced "with [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD], which looks like this: �".
/// See [`String::from_utf8_lossy`] for further details.
///
/// [rust#12309]: https://github.com/rust-lang/rust/issues/12309
/// [rust#90785]: https://github.com/rust-lang/rust/issues/90785
/// [U+FFFD]: char::REPLACEMENT_CHARACTER
pub struct Stream {
	inner: StdStream,
	should_color: bool,
}

enum StdStream {
	Out(io::Stdout),
	Err(io::Stderr)
}

/// Buffer for colored text
///
/// A buffer stores text and color escape codes for printing to an output stream.
/// Actually writing the escape codes can be disabled at runtime (i.e. when the underlying stream is not attached to a TTY).  
/// See [`Paint`] for convenient methods to append colored text.
///
/// This has also been taken and adapted from [termcolor](https://crates.io/crates/termcolor).
pub struct Buffer {
	inner: Vec<u8>,
	should_color: bool
}

/// Wrap a [`Buffer`] to print it and a newline when dropped
///
/// This struct "borrows" (figuratively) a [`Buffer`] from a [`Stream`].
/// It holds a reference to this [`Stream`], and the **destructor uses this reference to print the buffer** to the terminal.
///
/// Before the buffer is printed, a **newline character is appended** to it.
/// This can be avoided by using [`Line::no_newline`] to turn it into a [`NoNewLine`].
pub struct Line<'s> {
	/// `Option` because we might need to discard it
	buffer: Option<Buffer>,
	stream: &'s Stream
}

/// Wrap a [`Buffer`] to print it *without* a newline when dropped
///
/// This struct is obtained from [`Line::no_newline`] and apart from *not* appending the newline automatically, it is equivalent to [`Line`].
/// This means it also **prints itself when dropped**.
pub struct NoNewLine<'s> {
	/// `Option` because we might need to discard it
	buffer: Option<Buffer>,
	stream: &'s Stream
}

/// Initial content for a buffer
///
/// This wouldn't actually be the *first* thing in the buffer if it has been
/// obtained using a method that adds the tag, which comes first.
///
/// Unfortunately it is not possible to implement this trait for all
/// [`std::fmt::Display`] types.
/// It is implemented for [`&str`] however, and that is usually enough.
/// If it isn't, the [`Wrap::Plain`](crate::push::Wrap::Plain) wrapper can be used, because this trait is implemented for all [`Inline`] types.
///
/// To provide no initial content, use one of the following:
/// ```rust,no_run
/// # let con = conciliator::init();
/// # use conciliator::Conciliator;
/// con.status(..);
/// con.status(());
/// con.status(None);
/// ```
pub trait InitialContent {
	/// Initialize the buffer
	fn init_buffer(&self, buffer: &mut Buffer);
}

/// Helper trait for implementing the [`Conciliator`]
///
/// This trait establishes the borrow relation and crucially requires the `Line` type to implement [`Paint`]
pub trait GetLine<'l> {
	/// Type of the line buffer (does not have to be the struct [`Line`])
	type Line: 'l + Deref<Target = Buffer> + DerefMut;
	/// Obtain a new line buffer
	fn get_line(&'l self) -> Self::Line;
}

/*
 *	STD STREAM
 */

impl StdStream {
	pub(crate) fn clone(&self) -> Self {
		match self {
			Self::Out(_) => Self::Out(io::stdout()),
			Self::Err(_) => Self::Err(io::stderr()),
		}
	}
	fn is_terminal(&self) -> bool {
		match self {
			Self::Out(out) => out.is_terminal(),
			Self::Err(err) => err.is_terminal()
		}
	}
}

/*
 *	STREAM
 */

impl Stream {
	pub(crate) fn clone(&self) -> Self {
		Self {
			inner: self.inner.clone(),
			..*self
		}
	}
	pub(crate) fn colors_enabled(&self) -> bool {self.should_color}
	/// Initialize on stdout
	///
	/// Colors can be enabled (`Some(true)`) or disabled (`Some(false)`) manually.
	///
	/// Otherwise (`None`), colors will only be enabled if:
	///  - the stdout stream is a TTY, **and**
	///  - the `TERM` environment variable is set to something other than `dumb`, **and**
	///  - the environment variable `NO_COLOR` is *not* set.
	///
	/// This is the algorithm as used by [termcolor](https://crates.io/crates/termcolor)
	pub fn stdout(color_override: Option<bool>) -> Self {
		let inner = StdStream::Out(io::stdout());
		let should_color = color_override.unwrap_or_else(
			|| inner.is_terminal() && Self::should_color()
		);
		Self {inner, should_color}
	}
	/// Initialize on stderr
	///
	/// Colors can be enabled (`Some(true)`) or disabled (`Some(false)`) manually.
	///
	/// Otherwise (`None`), colors will only be enabled if:
	///  - the stderr stream is a TTY, **and**
	///  - the `TERM` environment variable is set to something other than `dumb`, **and**
	///  - the environment variable `NO_COLOR` is *not* set.
	///
	/// This is the algorithm as used by [termcolor](https://crates.io/crates/termcolor)
	pub fn stderr(color_override: Option<bool>) -> Self {
		let inner = StdStream::Err(io::stderr());
		let should_color = color_override.unwrap_or_else(
			|| inner.is_terminal() && Self::should_color()
		);
		Self {inner, should_color}
	}
	/// Get a new [`Buffer`] from this stream, with matching color status
	pub fn buffer(&self) -> Buffer {
		Buffer::new(self.should_color)
	}

	/// Get a new [`Line`] associated with this stream, with matching color status
	pub fn line(&'_ self) -> Line<'_> {
		Line::new(self)
	}

	/// Manually print a buffer by reference
	pub fn print_buffer(&self, buffer: &Buffer) -> io::Result<()> {
		#[cfg(not(any(test, feature = "test_capture")))] {
			// The lock() seems to be redundant, write_all would lock anyway
			match &self.inner {
				StdStream::Out(out) => out.lock().write_all(&buffer.inner),
				StdStream::Err(err) => err.lock().write_all(&buffer.inner)
			}
		}
		#[cfg(any(test, feature = "test_capture"))] {
			let s = String::from_utf8_lossy(&buffer.inner);
			match &self.inner {
				StdStream::Out(_out) => print!("{s}"),
				StdStream::Err(_err) => eprint!("{s}")
			}
			Ok(())
		}
	}

	/// Manually print a byte slice
	pub fn print_bytes(&self, buffer: &[u8]) -> io::Result<()> {
		#[cfg(not(any(test, feature = "test_capture")))] {
			// The lock() seems to be redundant, write_all would lock anyway
			match &self.inner {
				StdStream::Out(out) => out.lock().write_all(buffer),
				StdStream::Err(err) => err.lock().write_all(buffer)
			}
		}
		#[cfg(any(test, feature = "test_capture"))] {
			let s = String::from_utf8_lossy(buffer);
			match &self.inner {
				StdStream::Out(_out) => print!("{s}"),
				StdStream::Err(_err) => eprint!("{s}")
			}
			Ok(())
		}
	}

	/// Flush the underlying stream
	pub fn flush(&self) -> io::Result<()> {
		match &self.inner {
			StdStream::Out(out) => out.lock().flush(),
			StdStream::Err(err) => err.lock().flush()
		}
	}

	/// Manually flush the underlying stream after printing the buffer
	///
	/// This is used by the [`NoNewLine`] buffer wrapper because it cannot rely on a newline character to trigger "automatic" flushing.
	/// Provided as a separate method to avoid locking the output stream twice when using a shared reference.
	#[cfg(not(any(test, feature = "test_capture")))]
	pub(crate) fn print_buffer_and_flush(&self, buffer: &Buffer)
		-> io::Result<()>
	{
		match &self.inner {
			StdStream::Out(out) => {
				let mut out = out.lock();
				out.write_all(&buffer.inner)?;
				out.flush()
			},
			StdStream::Err(err) => {
				let mut err = err.lock();
				err.write_all(&buffer.inner)?;
				err.flush()
			}
		}
	}

	/// Manually flush the underlying stream after printing the buffer
	///
	/// This is used by the [`NoNewLine`] buffer wrapper because it cannot rely on a newline character to trigger "automatic" flushing.
	/// Provided as a separate method to avoid locking the output stream twice when using a shared reference.
	#[cfg(any(test, feature = "test_capture"))]
	pub(crate) fn print_buffer_and_flush(&self, buffer: &Buffer)
		-> io::Result<()>
	{
		let s = String::from_utf8_lossy(&buffer.inner);
		match &self.inner {
			StdStream::Out(out) => {
				let mut out = out.lock();
				print!("{s}");
				out.flush()
			},
			StdStream::Err(err) => {
				let mut err = err.lock();
				eprint!("{s}");
				err.flush()
			}
		}
	}

	fn should_color() -> bool {
		//credit: termcolor
		match env::var_os("TERM") {
			Some(var) if var == "dumb" => false,
			None => false,
			Some(_) => env::var_os("NO_COLOR").is_none()
		}
	}
}

impl<'l> GetLine<'l> for Stream {
	type Line = Line<'l>;
	fn get_line(&'l self) -> Self::Line {self.line()}
}

impl Conciliator for Stream {}

/*
 *	BUFFER
 */

impl Buffer {
	/// Create a new buffer for colored text. If `should_color` is false, all attempts at setting colors or styles via the [`Paint`] trait will be silently ignored.
	pub fn new(should_color: bool) -> Self {
		Self {
			inner: Vec::new(),
			should_color
		}
	}
	/// Append `thing` onto the buffer using the [`Inline`] trait
	pub fn push_inline<T: Inline>(&mut self, thing: &T) -> &mut Self {
		thing.inline(self);
		self
	}
	/// Append `thing` onto the buffer using **either** [`Inline`] or [`Display`](std::fmt::Display), doesn't work if both are implemented for `T`
	///
	/// [`Pushable`] is blanket-implemented for **both** [`Inline`] and [`Display`](std::fmt::Display) types.
	/// This would normally not be possible, because both blanket implementations could apply to the same type, thereby causing a conflict (Rust does not have any specialization or way to express `where T: NOT Trait`).
	/// So instead, this uses a trick that relies on a "marker type" being inferred.
	///
	///
	/// This workaround is described in detail on [`Pushable`], but in short:
	/// - [`Pushable`] has a type parameter `M` (i.e. `trait Pushable<M>`) that is not used except to make distinct implementations possible for the same type
	/// - `impl<T: Display> Pushable<marker::AsDisplay> for T`
	/// - `impl<T: Inline> Pushable<marker::AsInline> for T`
	/// - `push` is implemented for *any* `T: Pushable<M>` with *any* `M`
	/// - when there is only one applicable implementation, the marker type `M` can be inferred and won't need to be specified
	/// - Surprisingly, it just works!
	///
	/// If, however, there are multiple applicable implementations (i.e. for a type implements [`Inline`] *and* [`Display`](std::fmt::Display)), the type cannot be inferred: `type annotations needed`.
	/// In this case, it is easier to just use the more specific function instead of bothering with the type annotations.
	/// (For the time being, the marker types are private, so type annotations are also impossible.)
	///
	///```
	/// use conciliator::{Conciliator, Wrap};
	/// let con = conciliator::init();
	/// con.line(..)
	///     .push("Test") // &str,
	///     .push(123)    // i32 and
	///     .push(' ')    // char all implement Display
	///     .push(Wrap::Alpha(":^)")); // Wrap implements Inline
	///```
	pub fn push<M, T: Pushable<M>>(&mut self, thing: T) -> &mut Self {
		thing.push_into(self);
		self
	}

	/// Clear the contents of the [`Buffer`] so that it can be reused
	///
	/// Note that if you use this method through the [`Deref`] on a [`Line`], it will *still print the newline character when dropped*.
	/// You may want to use [`Line::discard`] instead.
	pub(crate) fn clear(&mut self) {self.inner.clear()}
}


impl Write for Buffer {
	fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
		self.inner.write(buf)
	}
	fn flush(&mut self) -> IoResult<()> {
		self.inner.flush()
	}
}

impl EmitEscapes for Buffer {
	fn escapes_recognized(&self) -> bool {self.should_color}
}


/*
 *	LINE
 */

impl<'s> Line<'s> {
	/// "Borrow" a new `Line` buffer from the [`Stream`]
	pub fn new(stream: &'s Stream) -> Self {
		let buffer = Some(Buffer::new(stream.should_color));
		Self {buffer, stream}
	}
	/// Print this `Line` into the [`Stream`]. This is equivalent to dropping.
	pub fn print(self) {}
	/// Discard and drop this buffer without printing it
	pub fn discard(mut self) {self.buffer.take();}
	/// No longer add the newline when dropped
	pub fn no_newline(mut self) -> NoNewLine<'s> {
		let buffer = self.buffer.take().unwrap();
		NoNewLine {stream: self.stream, buffer: Some(buffer)}
	}
}

impl<'s> Drop for Line<'s> {
	/// The `Line` prints itself to the [`Stream`] when dropped
	fn drop(&mut self) {
		if let Some(buffer) = self.buffer.as_mut() {
			writeln!(buffer, ).unwrap();
			self.stream.print_buffer(buffer).unwrap();
		}
	}
}
impl<'s> Deref for Line<'s> {
	type Target = Buffer;
	fn deref(&self) -> &Self::Target {self.buffer.as_ref().unwrap()}
}
impl<'s> DerefMut for Line<'s> {
	fn deref_mut(&mut self) -> &mut Self::Target {self.buffer.as_mut().unwrap()}
}
impl<'s> Write for Line<'s> {
	fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
		self.inner.write(buf)
	}
	fn flush(&mut self) -> IoResult<()> {
		self.inner.flush()
	}
}

impl<'s> EmitEscapes for Line<'s> {
	fn escapes_recognized(&self) -> bool {self.should_color}
}



/*
 *	NO NEW LINE
 */

impl<'s> NoNewLine<'s> {
	/// Print this `NoNewLine` into the [`Stream`]. This is equivalent to dropping.
	pub fn print(self) {}
	/// Discard and drop this buffer without printing it
	///
	/// This also elides flushing the [`Stream`].
	pub fn discard(mut self) {self.buffer.take();}
}

impl<'s> Drop for NoNewLine<'s> {
	/// The `NoNewLine` prints itself to the [`Stream`] when dropped
	///
	/// This flushes the output stream manually because it cannot rely on the newline triggering "automatic" flushing.
	fn drop(&mut self) {
		if let Some(buffer) = self.buffer.as_mut() {
			self.stream.print_buffer_and_flush(buffer).unwrap();
		}
	}
}
impl<'s> Deref for NoNewLine<'s> {
	type Target = Buffer;
	fn deref(&self) -> &Self::Target {self.buffer.as_ref().unwrap()}
}
impl<'s> DerefMut for NoNewLine<'s> {
	fn deref_mut(&mut self) -> &mut Self::Target {self.buffer.as_mut().unwrap()}
}


/*
 *	INTIAL CONTENT
 */

/// Provide no initial content: `con.status(..)`
///
/// This is unidiomatic but I don't like `con.status(())`
impl InitialContent for std::ops::RangeFull {
	fn init_buffer(&self, _buf: &mut Buffer) {}
}

/// Provide no initial content: `con.status(())`
impl InitialContent for () {
	fn init_buffer(&self, _buf: &mut Buffer) {}
}

/// Provide no initial content: `con.status(None)`
impl InitialContent for Option<()> {
	fn init_buffer(&self, _buf: &mut Buffer) {}
}


/// Initialize the buffer with a string literal: `con.status("Test123 :^)")`
impl InitialContent for &str {
	fn init_buffer(&self, buf: &mut Buffer) {
		buf.push_plain(self);
	}
}

/// Initialize the buffer with a [`String`]: `con.status(format!("Test123 :^)"))`
impl InitialContent for String {
	fn init_buffer(&self, buf: &mut Buffer) {
		buf.push_plain(self);
	}
}

/// Initialize the buffer with [`format_args!`]: just as convenient as [`format!`] but without allocating
///
/// `con.status(format_args!("Test123 :^)"))`
impl InitialContent for Arguments<'_> {
	fn init_buffer(&self, buf: &mut Buffer) {
		buf.push_plain(self);
	}
}

/// Initialize with a [`Inline`] implementor
impl<T: Inline + ?Sized> InitialContent for T {
	fn init_buffer(&self, buf: &mut Buffer) {self.inline(buf)}
}