Skip to main content

stratum_node_cli/
output.rs

1//! The one place `stratum` writes to the terminal.
2//!
3//! Results go to standard output: human-readable lines, or one JSON value
4//! under `--json`. Notes, prompts and errors go to standard error. Text
5//! that came from the node is passed through [`sanitize`] first so that a
6//! response cannot drive the terminal with control sequences, and every
7//! string written is passed through `redact` so that a registered secret
8//! (the bootstrap token) never reaches the terminal, even when the node
9//! echoes it back.
10
11use std::io::{self, BufRead as _, IsTerminal as _, Write as _};
12
13use crate::error::CliError;
14use crate::redact::redact;
15
16/// How results are written to standard output.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18#[non_exhaustive]
19pub enum OutputFormat {
20    /// Lines meant for a person.
21    #[default]
22    Human,
23    /// One JSON value per command, for scripts.
24    Json,
25}
26
27/// The terminal writer used by every command.
28///
29/// Writing goes through locked handles with `write!`, so a closed pipe is
30/// reported as an error rather than a panic. Every string written, error
31/// reports included, first has any registered secret replaced by
32/// `<redacted>` (see [`BootstrapToken`](crate::BootstrapToken)).
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub struct Output {
35    format: OutputFormat,
36}
37
38impl Output {
39    /// Creates a writer for `format`.
40    pub fn new(format: OutputFormat) -> Self {
41        Self { format }
42    }
43
44    /// Returns the output format.
45    pub fn format(&self) -> OutputFormat {
46        self.format
47    }
48
49    /// Returns `true` under `--json`.
50    pub(crate) fn is_json(self) -> bool {
51        self.format == OutputFormat::Json
52    }
53
54    /// Writes one line of human output to standard output. Does nothing
55    /// under `--json`.
56    pub(crate) fn line(self, text: &str) -> Result<(), CliError> {
57        if self.is_json() {
58            return Ok(());
59        }
60        write_line(&mut io::stdout().lock(), text)
61    }
62
63    /// Writes one line to standard output in every format: for results that
64    /// are a single value, such as the `Authorization` header.
65    #[expect(
66        clippy::unused_self,
67        reason = "kept on Output so every terminal write goes through the one writer"
68    )]
69    pub(crate) fn value_line(self, text: &str) -> Result<(), CliError> {
70        write_line(&mut io::stdout().lock(), text)
71    }
72
73    /// Writes `value` as pretty JSON to standard output under `--json`. Does
74    /// nothing in human mode.
75    pub(crate) fn json(self, value: &serde_json::Value) -> Result<(), CliError> {
76        if !self.is_json() {
77            return Ok(());
78        }
79        let text = serde_json::to_string_pretty(value)
80            .map_err(|err| CliError::Local(format!("encoding output failed: {err}")))?;
81        write_line(&mut io::stdout().lock(), &text)
82    }
83
84    /// Writes a note to standard error in every format.
85    #[expect(
86        clippy::unused_self,
87        reason = "kept on Output so every terminal write goes through the one writer"
88    )]
89    pub(crate) fn note(self, text: &str) -> Result<(), CliError> {
90        write_line(&mut io::stderr().lock(), text)
91    }
92
93    /// Asks a yes/no question on standard error and reads the answer from
94    /// standard input. Returns `None` when standard input is not a terminal,
95    /// so a script never blocks on a prompt.
96    #[expect(
97        clippy::unused_self,
98        reason = "kept on Output so every terminal write goes through the one writer"
99    )]
100    pub(crate) fn confirm(self, question: &str) -> Result<Option<bool>, CliError> {
101        let stdin = io::stdin();
102        if !stdin.is_terminal() {
103            return Ok(None);
104        }
105        {
106            let mut err = io::stderr().lock();
107            write!(err, "{} [y/N] ", redact(question))
108                .and_then(|()| err.flush())
109                .map_err(|err| write_error(&err))?;
110        }
111        let mut answer = String::new();
112        stdin
113            .lock()
114            .read_line(&mut answer)
115            .map_err(|err| CliError::Local(format!("reading the answer failed: {err}")))?;
116        Ok(Some(matches!(
117            answer.trim(),
118            "y" | "Y" | "yes" | "YES" | "Yes"
119        )))
120    }
121
122    /// Reports a failed command on standard error: `error: <message>` and
123    /// its causes, then any validation details, then a `hint:` line when
124    /// [`CliError::hint`] has one. Under `--json` the report is one JSON
125    /// object, `{"error": {"code", "message", "details", "hint"}, "exit_code"}`,
126    /// where `hint` is `null` when there is none.
127    ///
128    /// Failures to write the report itself are ignored: there is nowhere
129    /// left to report them.
130    pub fn error(&self, error: &CliError) {
131        let message = chain(error);
132        let mut err = io::stderr().lock();
133        if self.is_json() {
134            let value = serde_json::json!({
135                "error": {
136                    "code": error.code(),
137                    "message": message,
138                    "details": error.details(),
139                    "hint": error.hint(),
140                },
141                "exit_code": error.exit_code(),
142            });
143            let _written = writeln!(err, "{}", redact(&value.to_string()));
144        } else {
145            let _written = writeln!(err, "{}", redact(&format!("error: {message}")));
146            for detail in error.details() {
147                let _detail = writeln!(err, "{}", redact(&format!("  {detail}")));
148            }
149            if let Some(hint) = error.hint() {
150                let _hint = writeln!(err, "hint: {hint}");
151            }
152        }
153        let _flushed = err.flush();
154    }
155}
156
157/// Joins an error and its sources with `: `.
158fn chain(error: &CliError) -> String {
159    let mut message = error.to_string();
160    let mut source = std::error::Error::source(error);
161    while let Some(cause) = source {
162        message.push_str(": ");
163        message.push_str(&cause.to_string());
164        source = cause.source();
165    }
166    message
167}
168
169/// Writes `text` with secrets redacted, a newline, and flushes.
170fn write_line(out: &mut impl io::Write, text: &str) -> Result<(), CliError> {
171    writeln!(out, "{}", redact(text))
172        .and_then(|()| out.flush())
173        .map_err(|err| write_error(&err))
174}
175
176/// Maps an output failure.
177fn write_error(err: &io::Error) -> CliError {
178    CliError::Local(format!("writing output failed: {err}"))
179}
180
181/// Escapes control characters, except line feed and tab, in text that came
182/// from the node, so it cannot move the cursor, recolour the terminal or
183/// rewrite earlier lines.
184pub(crate) fn sanitize(text: &str) -> String {
185    let mut clean = String::with_capacity(text.len());
186    for c in text.chars() {
187        if c.is_control() && c != '\n' && c != '\t' {
188            clean.extend(c.escape_default());
189        } else {
190            clean.push(c);
191        }
192    }
193    clean
194}