Skip to main content

pimalaya_cli/
printer.rs

1//! Command output rendering to stdout.
2//!
3//! The [`Printer`] trait abstracts how a command emits what it prints:
4//! events while it runs, then its result. The [`StdoutPrinter`]
5//! implementation writes plain text or JSON to stdout, the
6//! [`CapturePrinter`] keeps it as JSON values for a caller such as an MCP
7//! server.
8//!
9//! Every value a command prints is data: a named type whose `Display`
10//! writes the text form and whose `Serialize` writes the JSON one. There
11//! is no message wrapper, a sentence being the text form of data, never
12//! data itself. A record's text form is [`Fields`], a list's [`Columns`].
13//!
14//! [`Columns`]: crate::columns::Columns
15//! [`Fields`]: crate::fields::Fields
16
17use std::{
18    fmt,
19    io::{IsTerminal, Stdout, Write, stdout},
20};
21
22use anyhow::{Context, Result, bail};
23use serde::Serialize;
24use serde_json::Value;
25
26use crate::{clap::args::JsonFlag, output::Bytes};
27
28/// Sink a command writes its output to.
29pub trait Printer {
30    /// Writes the result of the command, as text or JSON.
31    fn out<T: fmt::Display + Serialize>(&mut self, data: T) -> Result<()>;
32
33    /// Writes an event, something the command observed while running,
34    /// before its result.
35    ///
36    /// An event serializes as an object whose root carries `event`, a
37    /// kebab-case name, which a result never carries.
38    fn event<T: fmt::Display + Serialize>(&mut self, event: T) -> Result<()>;
39
40    /// Writes bytes as the result of the command: verbatim in text mode,
41    /// as a [`Bytes`] object under JSON.
42    fn out_bytes(&mut self, bytes: Bytes) -> Result<()>;
43
44    /// Whether the printer emits JSON.
45    fn is_json(&self) -> bool {
46        false
47    }
48}
49
50/// A [`Printer`] writing plain text or JSON to stdout.
51pub struct StdoutPrinter {
52    stdout: Stdout,
53    json: bool,
54}
55
56impl StdoutPrinter {
57    /// Builds a stdout printer, emitting JSON when the flag is set.
58    pub fn new(json: &JsonFlag) -> Self {
59        Self {
60            stdout: stdout(),
61            json: json.enabled,
62        }
63    }
64
65    fn write_json_line<T: Serialize>(&mut self, data: &T) -> Result<()> {
66        serde_json::to_writer(&mut self.stdout, data).context("Print JSON to stdout error")?;
67        writeln!(self.stdout)?;
68        self.stdout.flush()?;
69        Ok(())
70    }
71}
72
73impl Printer for StdoutPrinter {
74    fn out<T: fmt::Display + Serialize>(&mut self, data: T) -> Result<()> {
75        if !self.json {
76            write!(self.stdout, "{data}")?;
77            return Ok(());
78        }
79
80        if self.stdout.is_terminal() {
81            serde_json::to_writer_pretty(&mut self.stdout, &data)
82                .context("Print pretty JSON to stdout error")?;
83            writeln!(self.stdout)?;
84            return Ok(());
85        }
86
87        // NOTE: one value per line, flushed, so a process printing
88        // several values (a REPL session, a watch) emits
89        // newline-delimited JSON.
90        self.write_json_line(&data)
91    }
92
93    fn event<T: fmt::Display + Serialize>(&mut self, event: T) -> Result<()> {
94        // NOTE: an event is one compact line even on a terminal, so a
95        // stream of them stays one value per line.
96        if self.json {
97            return self.write_json_line(&event);
98        }
99
100        // NOTE: text events go to a terminal only, so a redirected stdout
101        // captures the result alone.
102        if self.stdout.is_terminal() {
103            write!(self.stdout, "{event}")?;
104            self.stdout.flush()?;
105        }
106
107        Ok(())
108    }
109
110    fn out_bytes(&mut self, bytes: Bytes) -> Result<()> {
111        if self.json {
112            return self.out(bytes);
113        }
114
115        self.stdout
116            .write_all(&bytes.data)
117            .context("Write bytes to stdout error")?;
118        self.stdout.flush().context("Flush stdout error")?;
119
120        Ok(())
121    }
122
123    fn is_json(&self) -> bool {
124        self.json
125    }
126}
127
128/// A [`Printer`] keeping each value and event a command prints as JSON,
129/// for a caller that hands them on rather than printing them.
130#[derive(Debug, Default)]
131pub struct CapturePrinter {
132    /// The values printed, in order.
133    pub values: Vec<Value>,
134    /// The events printed, in order.
135    pub events: Vec<Value>,
136}
137
138impl CapturePrinter {
139    /// The one value the command printed, failing when it printed none or
140    /// several.
141    pub fn into_single(mut self) -> Result<Value> {
142        if self.values.len() != 1 {
143            let n = self.values.len();
144            bail!("The command printed {n} values, one expected");
145        }
146
147        Ok(self.values.remove(0))
148    }
149}
150
151impl Printer for CapturePrinter {
152    fn out<T: fmt::Display + Serialize>(&mut self, data: T) -> Result<()> {
153        self.values.push(serde_json::to_value(&data)?);
154        Ok(())
155    }
156
157    fn event<T: fmt::Display + Serialize>(&mut self, event: T) -> Result<()> {
158        self.events.push(serde_json::to_value(&event)?);
159        Ok(())
160    }
161
162    fn out_bytes(&mut self, bytes: Bytes) -> Result<()> {
163        self.out(bytes)
164    }
165
166    fn is_json(&self) -> bool {
167        true
168    }
169}
170
171/// A [`Printer`] keeping the rendered output in memory, for tests.
172#[cfg(test)]
173#[derive(Default)]
174pub struct TestPrinter {
175    /// The text form of the result.
176    pub output: String,
177    /// The text form of each event, in order.
178    pub events: Vec<String>,
179}
180
181#[cfg(test)]
182impl Printer for TestPrinter {
183    fn out<T: fmt::Display + Serialize>(&mut self, data: T) -> Result<()> {
184        self.output = data.to_string();
185        Ok(())
186    }
187
188    fn event<T: fmt::Display + Serialize>(&mut self, event: T) -> Result<()> {
189        self.events.push(event.to_string());
190        Ok(())
191    }
192
193    fn out_bytes(&mut self, bytes: Bytes) -> Result<()> {
194        self.output = String::from_utf8_lossy(&bytes.data).into_owned();
195        Ok(())
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use serde_json::json;
202
203    use crate::printer::{CapturePrinter, Printer};
204
205    #[test]
206    fn a_single_value_is_taken_and_events_kept_apart() {
207        let mut printer = CapturePrinter::default();
208        printer.event(json!({ "event": "a" })).unwrap();
209        printer.out(json!({ "id": 1 })).unwrap();
210
211        assert_eq!(printer.events, [json!({ "event": "a" })]);
212        assert_eq!(printer.into_single().unwrap(), json!({ "id": 1 }));
213    }
214
215    #[test]
216    fn the_count_of_values_is_the_one_printed() {
217        let none = CapturePrinter::default().into_single().unwrap_err();
218        assert_eq!(
219            none.to_string(),
220            "The command printed 0 values, one expected"
221        );
222
223        let mut printer = CapturePrinter::default();
224        printer.out(json!(1)).unwrap();
225        printer.out(json!(2)).unwrap();
226
227        let two = printer.into_single().unwrap_err();
228        assert_eq!(
229            two.to_string(),
230            "The command printed 2 values, one expected"
231        );
232    }
233}