stratum-node-cli 0.1.0-alpha.2

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
//! The one place `stratum` writes to the terminal.
//!
//! Results go to standard output: human-readable lines, or one JSON value
//! under `--json`. Notes, prompts and errors go to standard error. Text
//! that came from the node is passed through [`sanitize`] first so that a
//! response cannot drive the terminal with control sequences, and every
//! string written is passed through `redact` so that a registered secret
//! (the bootstrap token) never reaches the terminal, even when the node
//! echoes it back.

use std::io::{self, BufRead as _, IsTerminal as _, Write as _};

use crate::error::CliError;
use crate::redact::redact;

/// How results are written to standard output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum OutputFormat {
    /// Lines meant for a person.
    #[default]
    Human,
    /// One JSON value per command, for scripts.
    Json,
}

/// The terminal writer used by every command.
///
/// Writing goes through locked handles with `write!`, so a closed pipe is
/// reported as an error rather than a panic. Every string written, error
/// reports included, first has any registered secret replaced by
/// `<redacted>` (see [`BootstrapToken`](crate::BootstrapToken)).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Output {
    format: OutputFormat,
}

impl Output {
    /// Creates a writer for `format`.
    pub fn new(format: OutputFormat) -> Self {
        Self { format }
    }

    /// Returns the output format.
    pub fn format(&self) -> OutputFormat {
        self.format
    }

    /// Returns `true` under `--json`.
    pub(crate) fn is_json(self) -> bool {
        self.format == OutputFormat::Json
    }

    /// Writes one line of human output to standard output. Does nothing
    /// under `--json`.
    pub(crate) fn line(self, text: &str) -> Result<(), CliError> {
        if self.is_json() {
            return Ok(());
        }
        write_line(&mut io::stdout().lock(), text)
    }

    /// Writes one line to standard output in every format: for results that
    /// are a single value, such as the `Authorization` header.
    #[expect(
        clippy::unused_self,
        reason = "kept on Output so every terminal write goes through the one writer"
    )]
    pub(crate) fn value_line(self, text: &str) -> Result<(), CliError> {
        write_line(&mut io::stdout().lock(), text)
    }

    /// Writes `value` as pretty JSON to standard output under `--json`. Does
    /// nothing in human mode.
    pub(crate) fn json(self, value: &serde_json::Value) -> Result<(), CliError> {
        if !self.is_json() {
            return Ok(());
        }
        let text = serde_json::to_string_pretty(value)
            .map_err(|err| CliError::Local(format!("encoding output failed: {err}")))?;
        write_line(&mut io::stdout().lock(), &text)
    }

    /// Writes a note to standard error in every format.
    #[expect(
        clippy::unused_self,
        reason = "kept on Output so every terminal write goes through the one writer"
    )]
    pub(crate) fn note(self, text: &str) -> Result<(), CliError> {
        write_line(&mut io::stderr().lock(), text)
    }

    /// Asks a yes/no question on standard error and reads the answer from
    /// standard input. Returns `None` when standard input is not a terminal,
    /// so a script never blocks on a prompt.
    #[expect(
        clippy::unused_self,
        reason = "kept on Output so every terminal write goes through the one writer"
    )]
    pub(crate) fn confirm(self, question: &str) -> Result<Option<bool>, CliError> {
        let stdin = io::stdin();
        if !stdin.is_terminal() {
            return Ok(None);
        }
        {
            let mut err = io::stderr().lock();
            write!(err, "{} [y/N] ", redact(question))
                .and_then(|()| err.flush())
                .map_err(|err| write_error(&err))?;
        }
        let mut answer = String::new();
        stdin
            .lock()
            .read_line(&mut answer)
            .map_err(|err| CliError::Local(format!("reading the answer failed: {err}")))?;
        Ok(Some(matches!(
            answer.trim(),
            "y" | "Y" | "yes" | "YES" | "Yes"
        )))
    }

    /// Reports a failed command on standard error: `error: <message>` and
    /// its causes, then any validation details. Under `--json` the report is
    /// one JSON object, `{"error": {"code", "message", "details"}, "exit_code"}`.
    ///
    /// Failures to write the report itself are ignored: there is nowhere
    /// left to report them.
    pub fn error(&self, error: &CliError) {
        let message = chain(error);
        let mut err = io::stderr().lock();
        if self.is_json() {
            let value = serde_json::json!({
                "error": {
                    "code": error.code(),
                    "message": message,
                    "details": error.details(),
                },
                "exit_code": error.exit_code(),
            });
            let _written = writeln!(err, "{}", redact(&value.to_string()));
        } else {
            let _written = writeln!(err, "{}", redact(&format!("error: {message}")));
            for detail in error.details() {
                let _detail = writeln!(err, "{}", redact(&format!("  {detail}")));
            }
        }
        let _flushed = err.flush();
    }
}

/// Joins an error and its sources with `: `.
fn chain(error: &CliError) -> String {
    let mut message = error.to_string();
    let mut source = std::error::Error::source(error);
    while let Some(cause) = source {
        message.push_str(": ");
        message.push_str(&cause.to_string());
        source = cause.source();
    }
    message
}

/// Writes `text` with secrets redacted, a newline, and flushes.
fn write_line(out: &mut impl io::Write, text: &str) -> Result<(), CliError> {
    writeln!(out, "{}", redact(text))
        .and_then(|()| out.flush())
        .map_err(|err| write_error(&err))
}

/// Maps an output failure.
fn write_error(err: &io::Error) -> CliError {
    CliError::Local(format!("writing output failed: {err}"))
}

/// Escapes control characters, except line feed and tab, in text that came
/// from the node, so it cannot move the cursor, recolour the terminal or
/// rewrite earlier lines.
pub(crate) fn sanitize(text: &str) -> String {
    let mut clean = String::with_capacity(text.len());
    for c in text.chars() {
        if c.is_control() && c != '\n' && c != '\t' {
            clean.extend(c.escape_default());
        } else {
            clean.push(c);
        }
    }
    clean
}