use crate::output::{OutputFormat, OutputTo};
use crate::protocol::{
BuildError, Event, LogLevel, ProtocolViolation, json_error, json_log, json_progress,
json_result, validate_protocol_event,
};
use crate::redaction::OutputOptions;
use serde_json::Value;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LogFilters(Vec<String>);
impl LogFilters {
pub fn new<I, S>(filters: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut out: Vec<String> = Vec::new();
for entry in filters {
let s = entry
.as_ref()
.trim_matches(|c| matches!(c, ' ' | '\t' | '\n' | '\x0c' | '\r'))
.to_ascii_lowercase();
if !s.is_empty() && !out.contains(&s) {
out.push(s);
}
}
Self(out)
}
pub fn enabled(&self, event: &str) -> bool {
if self.0.is_empty() {
return false;
}
let event_lower = event.to_ascii_lowercase();
if self.0.contains(&"all".to_string()) {
return true;
}
self.0.iter().any(|filter| event_lower.starts_with(filter))
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn as_slice(&self) -> &[String] {
&self.0
}
}
pub fn cli_parse_output(s: &str) -> Result<OutputFormat, String> {
s.parse()
.map_err(|_| "invalid --output format: expected json, yaml, or plain".to_string())
}
pub fn cli_parse_log_filters<S: AsRef<str>>(entries: &[S]) -> LogFilters {
LogFilters::new(entries.iter().map(AsRef::as_ref))
}
#[derive(Debug)]
pub enum CliEmitterError {
Validation(ProtocolViolation),
Build(BuildError),
Lifecycle(String),
Write(std::io::Error),
}
impl std::fmt::Display for CliEmitterError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Validation(v) => write!(f, "{v}"),
Self::Build(e) => write!(f, "{e}"),
Self::Lifecycle(err) => f.write_str(err),
Self::Write(err) => write!(f, "failed to write CLI event: {err}"),
}
}
}
impl CliEmitterError {
pub const fn io_error(&self) -> Option<&std::io::Error> {
match self {
Self::Write(err) => Some(err),
Self::Validation(_) | Self::Build(_) | Self::Lifecycle(_) => None,
}
}
pub fn io_error_kind(&self) -> Option<std::io::ErrorKind> {
self.io_error().map(std::io::Error::kind)
}
}
impl std::error::Error for CliEmitterError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.io_error()
.map(|err| err as &(dyn std::error::Error + 'static))
}
}
impl From<std::io::Error> for CliEmitterError {
fn from(err: std::io::Error) -> Self {
Self::Write(err)
}
}
impl From<BuildError> for CliEmitterError {
fn from(err: BuildError) -> Self {
Self::Build(err)
}
}
pub struct CliEmitter<W: std::io::Write> {
writer: W,
diagnostic: Option<Box<dyn std::io::Write>>,
write_failure_diagnostic: Option<Box<dyn std::io::Write>>,
diagnostic_failed: bool,
format: OutputFormat,
output_options: OutputOptions,
strict_protocol: bool,
terminal_emitted: bool,
write_failure: Option<std::io::ErrorKind>,
failure_reported: bool,
}
impl<W: std::io::Write> CliEmitter<W> {
pub fn stream(writer: W, format: OutputFormat) -> Self {
Self {
writer,
diagnostic: None,
write_failure_diagnostic: None,
diagnostic_failed: false,
format,
output_options: OutputOptions::default(),
strict_protocol: false,
terminal_emitted: false,
write_failure: None,
failure_reported: false,
}
}
pub fn finite(
result_writer: W,
diagnostic: impl std::io::Write + 'static,
format: OutputFormat,
) -> Self {
let mut emitter = Self::stream(result_writer, format);
emitter.diagnostic = Some(Box::new(diagnostic));
emitter
}
#[must_use]
pub fn with_options(mut self, output_options: OutputOptions) -> Self {
self.output_options = output_options;
self
}
pub fn set_options(&mut self, output_options: OutputOptions) {
self.output_options = output_options;
}
#[must_use]
pub fn with_strict_protocol(mut self) -> Self {
self.strict_protocol = true;
self
}
pub const fn format(&self) -> OutputFormat {
self.format
}
pub fn emit(&mut self, event: Event) -> Result<(), CliEmitterError> {
let value = event.into_value();
self.write_event(value)
}
pub fn emit_validated_value(&mut self, value: Value) -> Result<(), CliEmitterError> {
validate_protocol_event(&value, true).map_err(CliEmitterError::Validation)?;
self.write_event(value)
}
pub fn emit_result(&mut self, payload: Value) -> Result<(), CliEmitterError> {
self.emit(json_result(payload).build())
}
pub fn emit_error(&mut self, code: &str, message: &str) -> Result<(), CliEmitterError> {
self.emit(json_error(code, message).build()?)
}
pub fn emit_progress(&mut self, message: &str) -> Result<(), CliEmitterError> {
self.emit(json_progress(serde_json::json!({ "message": message })).build())
}
pub fn emit_log(&mut self, level: LogLevel, message: &str) -> Result<(), CliEmitterError> {
self.emit(
json_log(serde_json::json!({
"level": level.as_str(),
"message": message,
}))
.build(),
)
}
pub fn write_raw(&mut self, bytes: &[u8]) -> Result<(), CliEmitterError> {
if self.terminal_emitted {
return Err(CliEmitterError::Lifecycle(
"cannot write raw output after terminal output".to_string(),
));
}
self.ensure_writable()?;
let written = self
.writer
.write_all(bytes)
.and_then(|()| self.writer.flush());
self.record(written).map_err(CliEmitterError::Write)
}
pub fn finish_raw(&mut self, bytes: &[u8]) -> u8 {
let result = self.write_raw(bytes);
self.terminal_emitted = true;
let intended = u8::from(matches!(result, Err(CliEmitterError::Lifecycle(_))));
self.exit_code(intended)
}
pub fn finish(&mut self, event: Event, success_code: u8) -> u8 {
match self.emit(event) {
Ok(()) | Err(CliEmitterError::Write(_)) => self.exit_code(success_code),
Err(
CliEmitterError::Validation(_)
| CliEmitterError::Build(_)
| CliEmitterError::Lifecycle(_),
) => self.exit_code(1),
}
}
pub fn finish_result(&mut self, payload: Value) -> u8 {
self.finish(json_result(payload).build(), 0)
}
pub fn finish_document_result(
&mut self,
payload: crate::document::Value,
) -> crate::document::DocumentResult<u8> {
use crate::document::Value as DocumentValue;
let json = payload.project_output(self.format != OutputFormat::Json, &mut Vec::new())?;
let event = json_result(json).build().into_value();
let original = DocumentValue::Object([("result".into(), payload)].into_iter().collect());
let written = self.write_event_with_source(event, Some(&original));
Ok(match written {
Ok(()) | Err(CliEmitterError::Write(_)) => self.exit_code(0),
Err(_) => self.exit_code(1),
})
}
pub fn exit_code(&mut self, intended: u8) -> u8 {
match self.write_failure {
None => intended,
Some(std::io::ErrorKind::BrokenPipe) => 0,
Some(_) => {
if !self.failure_reported {
self.failure_reported = true;
self.report_output_write_failed();
}
4
}
}
}
pub const fn write_failure(&self) -> Option<std::io::ErrorKind> {
self.write_failure
}
fn report_output_write_failed(&mut self) {
if self.diagnostic_failed {
return;
}
if let Some(diagnostic) = self
.diagnostic
.as_mut()
.or(self.write_failure_diagnostic.as_mut())
{
let event = crate::cli_afdata::cli_output_write_failed_event();
let rendered =
crate::formatting::render(event.as_value(), self.format, &OutputOptions::default());
let _unwritable = write_event_line(diagnostic.as_mut(), &rendered);
}
}
fn ensure_writable(&self) -> Result<(), CliEmitterError> {
match self.write_failure {
Some(kind) => Err(CliEmitterError::Write(kind.into())),
None => Ok(()),
}
}
pub fn into_inner(self) -> W {
self.writer
}
fn record(&mut self, result: std::io::Result<()>) -> std::io::Result<()> {
if let Err(error) = &result
&& self.write_failure.is_none()
{
self.write_failure = Some(error.kind());
}
result
}
fn write_event(&mut self, event: Value) -> Result<(), CliEmitterError> {
self.write_event_with_source(event, None)
}
fn write_event_with_source(
&mut self,
event: Value,
source: Option<&crate::document::Value>,
) -> Result<(), CliEmitterError> {
validate_protocol_event(&event, self.strict_protocol)
.map_err(CliEmitterError::Validation)?;
let kind = event.get("kind").and_then(Value::as_str).ok_or_else(|| {
CliEmitterError::Validation(ProtocolViolation {
rule: "kind_invalid",
pointer: "/kind".to_string(),
message: "event.kind is required".to_string(),
})
})?;
match kind {
"log" | "progress" => {
if self.terminal_emitted {
return Err(CliEmitterError::Lifecycle(
"cannot emit non-terminal event after terminal event".to_string(),
));
}
}
"result" | "error" => {
if self.terminal_emitted {
return Err(CliEmitterError::Lifecycle(
"cannot emit duplicate terminal event".to_string(),
));
}
}
_ => {
return Err(CliEmitterError::Validation(ProtocolViolation {
rule: "kind_unsupported",
pointer: "/kind".to_string(),
message: format!("unsupported event kind {kind:?}"),
}));
}
}
self.ensure_writable()?;
let terminal = matches!(kind, "result" | "error");
let rendered = if let (OutputFormat::Yaml, Some(source)) = (self.format, source) {
crate::formatting::render_yaml_value(
&self.output_options.redaction.value(&event),
Some(source),
)
} else {
crate::formatting::render(&event, self.format, &self.output_options)
};
let written = match &mut self.diagnostic {
Some(diagnostic) if kind != "result" => {
let written = write_event_line(diagnostic.as_mut(), &rendered);
self.diagnostic_failed = written.is_err();
written
}
_ => write_event_line(&mut self.writer, &rendered),
};
if terminal {
self.terminal_emitted = true;
}
self.record(written)?;
Ok(())
}
}
fn write_event_line(writer: &mut dyn std::io::Write, rendered: &str) -> std::io::Result<()> {
writer.write_all(rendered.as_bytes())?;
writer.write_all(b"\n")?;
writer.flush()
}
#[allow(clippy::disallowed_methods)]
impl CliEmitter<Box<dyn std::io::Write>> {
pub fn from_plan(plan: &crate::cli_spec::OutputPlan) -> Self {
Self::from_output_to(
plan.output_to().unwrap_or(OutputTo::Split),
plan.output_format().unwrap_or(OutputFormat::Json),
)
.with_strict_protocol()
}
pub fn from_output_to(selector: OutputTo, format: OutputFormat) -> Self {
match selector {
OutputTo::Split => Self::finite(Box::new(std::io::stdout()), std::io::stderr(), format),
OutputTo::Stdout => {
let mut emitter = Self::stream(Box::new(std::io::stdout()), format);
emitter.write_failure_diagnostic = Some(Box::new(std::io::stderr()));
emitter
}
OutputTo::Stderr => Self::stream(Box::new(std::io::stderr()), format),
}
}
}
pub fn build_cli_version(
name: &str,
display_name: Option<&str>,
version: &str,
build: Option<&str>,
) -> Event {
let mut payload = serde_json::json!({
"code": "version",
"name": name,
"version": version,
});
if let Some(display_name) = display_name.filter(|text| !text.is_empty()) {
payload["display_name"] = Value::String(display_name.to_string());
}
if let Some(build) = build.filter(|text| !text.is_empty()) {
payload["build"] = Value::String(build.to_string());
}
json_result(payload).build()
}
pub fn cli_render_version(
name: &str,
display_name: Option<&str>,
version: &str,
build: Option<&str>,
format: OutputFormat,
) -> String {
let mut rendered = crate::formatting::render(
build_cli_version(name, display_name, version, build).as_value(),
format,
&OutputOptions::default(),
);
while rendered.ends_with('\n') {
rendered.pop();
}
rendered.push('\n');
rendered
}