use crate::secret_client::error::SecretClientError;
use serde::Serialize;
use std::io::{self, Write};
pub struct JsonStdout {
inner: io::Stdout,
}
impl JsonStdout {
pub fn new() -> Self {
Self {
inner: io::stdout(),
}
}
pub fn write<T: Serialize>(&mut self, value: &T) -> Result<(), SecretClientError> {
let json = serde_json::to_string(value)?;
writeln!(self.inner, "{}", json)?;
self.inner.flush()?;
Ok(())
}
}
impl Default for JsonStdout {
fn default() -> Self {
Self::new()
}
}
#[macro_export]
macro_rules! json_println {
($value:expr) => {{
let mut stdout = $crate::secret_client::stdout::JsonStdout::new();
stdout.write($value)
}};
}
mod guards {
use std::fmt;
pub struct DisabledPrintln;
impl fmt::Display for DisabledPrintln {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("println! is disabled - use json_println! instead")
}
}
#[allow(unused_macros)]
macro_rules! println {
($($arg:tt)*) => {
compile_error!(
"println! is disabled in this module. Use json_println! or stderr! instead."
);
};
}
#[allow(unused_macros)]
macro_rules! print {
($($arg:tt)*) => {
compile_error!(
"print! is disabled in this module. Use json_println! or stderr! instead."
);
};
}
}
pub fn stderr(msg: &str) -> io::Result<()> {
let stderr = io::stderr();
let mut handle = stderr.lock();
writeln!(handle, "{}", msg)?;
Ok(())
}
#[macro_export]
macro_rules! stderr {
($($arg:tt)*) => {{
let msg = format!($($arg)*);
$crate::secret_client::stdout::stderr(&msg)
}};
}