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. Under `--json` the report is
124    /// one JSON object, `{"error": {"code", "message", "details"}, "exit_code"}`.
125    ///
126    /// Failures to write the report itself are ignored: there is nowhere
127    /// left to report them.
128    pub fn error(&self, error: &CliError) {
129        let message = chain(error);
130        let mut err = io::stderr().lock();
131        if self.is_json() {
132            let value = serde_json::json!({
133                "error": {
134                    "code": error.code(),
135                    "message": message,
136                    "details": error.details(),
137                },
138                "exit_code": error.exit_code(),
139            });
140            let _written = writeln!(err, "{}", redact(&value.to_string()));
141        } else {
142            let _written = writeln!(err, "{}", redact(&format!("error: {message}")));
143            for detail in error.details() {
144                let _detail = writeln!(err, "{}", redact(&format!("  {detail}")));
145            }
146        }
147        let _flushed = err.flush();
148    }
149}
150
151/// Joins an error and its sources with `: `.
152fn chain(error: &CliError) -> String {
153    let mut message = error.to_string();
154    let mut source = std::error::Error::source(error);
155    while let Some(cause) = source {
156        message.push_str(": ");
157        message.push_str(&cause.to_string());
158        source = cause.source();
159    }
160    message
161}
162
163/// Writes `text` with secrets redacted, a newline, and flushes.
164fn write_line(out: &mut impl io::Write, text: &str) -> Result<(), CliError> {
165    writeln!(out, "{}", redact(text))
166        .and_then(|()| out.flush())
167        .map_err(|err| write_error(&err))
168}
169
170/// Maps an output failure.
171fn write_error(err: &io::Error) -> CliError {
172    CliError::Local(format!("writing output failed: {err}"))
173}
174
175/// Escapes control characters, except line feed and tab, in text that came
176/// from the node, so it cannot move the cursor, recolour the terminal or
177/// rewrite earlier lines.
178pub(crate) fn sanitize(text: &str) -> String {
179    let mut clean = String::with_capacity(text.len());
180    for c in text.chars() {
181        if c.is_control() && c != '\n' && c != '\t' {
182            clean.extend(c.escape_default());
183        } else {
184            clean.push(c);
185        }
186    }
187    clean
188}