stratum_node_cli/
output.rs1use std::io::{self, BufRead as _, IsTerminal as _, Write as _};
12
13use crate::error::CliError;
14use crate::redact::redact;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18#[non_exhaustive]
19pub enum OutputFormat {
20 #[default]
22 Human,
23 Json,
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub struct Output {
35 format: OutputFormat,
36}
37
38impl Output {
39 pub fn new(format: OutputFormat) -> Self {
41 Self { format }
42 }
43
44 pub fn format(&self) -> OutputFormat {
46 self.format
47 }
48
49 pub(crate) fn is_json(self) -> bool {
51 self.format == OutputFormat::Json
52 }
53
54 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 #[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 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 #[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 #[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 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
151fn 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
163fn 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
170fn write_error(err: &io::Error) -> CliError {
172 CliError::Local(format!("writing output failed: {err}"))
173}
174
175pub(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}