kutil_cli/debug/debuggable.rs
1use super::{prefix::*, theme::*};
2
3use std::io::*;
4
5//
6// Debuggable
7//
8
9/// Can write a debug representation of itself that can be indented, styled, and multiline.
10///
11/// Designed to support complex nested hierarchies.
12pub trait Debuggable {
13 /// Write the debug representation.
14 ///
15 /// Required behavior for implementations:
16 ///
17 /// 1. Representations *must not* end in a newline.
18 /// 2. All lines *after* the first (but *not* the first) *must* start with the provided prefix.
19 fn write_debug_representation<WriteT>(
20 &self,
21 writer: &mut WriteT,
22 prefix: &DebugPrefix,
23 theme: &Theme,
24 ) -> Result<()>
25 where
26 WriteT: Write;
27
28 /// Write the debug representation with the default theme and a final newline.
29 fn write_debug<WriteT>(&self, writer: &mut WriteT) -> Result<()>
30 where
31 WriteT: Write,
32 {
33 let theme = Theme::default();
34 self.write_debug_representation(writer, &DebugPrefix::new(theme.delimiter), &theme)?;
35 writeln!(writer)
36 }
37
38 /// Write the debug representation with the plain theme and a final newline.
39 fn write_debug_plain<WriteT>(&self, writer: &mut WriteT) -> Result<()>
40 where
41 WriteT: Write,
42 {
43 let theme = Theme::plain();
44 self.write_debug_representation(writer, &DebugPrefix::new(theme.delimiter), &theme)?;
45 writeln!(writer)
46 }
47
48 /// Print the debug representation to [anstream::stdout] with the default theme and a final newline.
49 ///
50 /// Panics on write [Error].
51 fn print_debug(&self) {
52 self.write_debug(&mut anstream::stdout()).unwrap();
53 }
54
55 /// Print the debug representation to [stdout] with the plain theme and a final newline.
56 ///
57 /// Panics on write [Error].
58 fn print_debug_plain(&self) {
59 self.write_debug_plain(&mut stdout()).unwrap();
60 }
61
62 /// Print the debug representation to [anstream::stderr] with the default theme and a final newline.
63 ///
64 /// Panics on write [Error].
65 fn eprint_debug(&self) {
66 self.write_debug(&mut anstream::stdout()).unwrap();
67 }
68
69 /// Print the debug representation to [stderr] with the plain theme and a final newline.
70 ///
71 /// Panics on write [Error].
72 fn eprint_debug_plain(&self) {
73 self.write_debug_plain(&mut stdout()).unwrap();
74 }
75
76 /// Capture [write_debug_representation](Debuggable::write_debug_representation) into a string.
77 fn to_debug_string(&self, theme: &Theme) -> Result<String> {
78 let mut writer = BufWriter::new(Vec::new());
79 self.write_debug_representation(&mut writer, &DebugPrefix::new(theme.delimiter), theme)?;
80 match String::from_utf8(writer.into_inner().unwrap().into()) {
81 Ok(string) => Ok(string),
82 Err(error) => Err(Error::new(ErrorKind::Other, format!("{}", error))),
83 }
84 }
85}