writer/
lib.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5mod json_writer;
6mod test_buffer;
7mod tool_io;
8mod writer;
9
10pub use json_writer::{format_output, JsonWriter};
11pub use test_buffer::{TestBuffer, TestBuffers};
12pub use tool_io::ToolIO;
13pub use writer::Writer;
14
15/// Enum indicating output formatting.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum Format {
18    Json,
19    JsonPretty,
20}
21
22impl std::str::FromStr for Format {
23    type Err = Error;
24
25    fn from_str(s: &str) -> Result<Self, Self::Err> {
26        match s.to_lowercase().as_ref() {
27            "json-pretty" => Ok(Format::JsonPretty),
28            "json" | "j" => Ok(Format::Json),
29            other => Err(Error::InvalidFormat(other.into())),
30        }
31    }
32}
33
34#[derive(thiserror::Error, Debug)]
35#[error("Error while presenting output")]
36pub enum Error {
37    #[error("Error on the underlying IO stream")]
38    Io(#[from] std::io::Error),
39    #[error("Error formatting JSON output")]
40    Json(#[from] serde_json::Error),
41    #[error("Error parsing utf8 from buffer")]
42    Utf8(#[from] std::string::FromUtf8Error),
43    #[error("`{0}` is not a valid machine format")]
44    InvalidFormat(String),
45    #[error("Schema validation failed: {0}")]
46    SchemaFailure(String),
47}
48
49pub type Result<O, E = Error> = std::result::Result<O, E>;
50
51impl From<Error> for ffx_command_error::Error {
52    fn from(error: Error) -> Self {
53        use ffx_command_error::Error::*;
54        use Error::*;
55        match error {
56            error @ (Io(_) | Json(_) | Utf8(_) | SchemaFailure(_)) => Unexpected(error.into()),
57            error @ InvalidFormat(_) => User(error.into()),
58        }
59    }
60}