Skip to main content

foundry_cli/
json.rs

1//! Shared JSON output primitives for Foundry CLIs.
2
3use alloy_dyn_abi::DynSolValue;
4use eyre::Result;
5use foundry_common::{
6    fmt::{format_tokens, serialize_value_as_json},
7    sh_println, shell,
8};
9use serde::{Deserialize, Serialize};
10use serde_json::{Value, to_string};
11
12/// The current version of Foundry's top-level JSON output envelope.
13pub const JSON_SCHEMA_VERSION: u32 = 1;
14
15/// Stable top-level envelope for complete machine-readable command output.
16///
17/// This envelope represents a terminal command outcome. Long-running commands
18/// that stream intermediate records should use a separate event type and reserve
19/// this shape for final, complete results.
20#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
21pub struct JsonEnvelope<T> {
22    /// Version of the envelope schema.
23    pub schema_version: u32,
24    /// Whether the command completed successfully.
25    ///
26    /// Only meaningful for a complete/terminal command outcome.
27    pub success: bool,
28    /// Command-specific payload.
29    pub data: Option<T>,
30    /// Structured errors emitted by the command.
31    pub errors: Vec<JsonMessage>,
32    /// Structured warnings emitted by the command.
33    pub warnings: Vec<JsonMessage>,
34}
35
36impl<T> JsonEnvelope<T> {
37    /// Creates a successful envelope with command-specific data.
38    pub const fn success(data: T) -> Self {
39        Self {
40            schema_version: JSON_SCHEMA_VERSION,
41            success: true,
42            data: Some(data),
43            errors: Vec::new(),
44            warnings: Vec::new(),
45        }
46    }
47
48    /// Creates a successful envelope with command-specific data and warnings.
49    pub const fn success_with_warnings(data: T, warnings: Vec<JsonMessage>) -> Self {
50        Self {
51            schema_version: JSON_SCHEMA_VERSION,
52            success: true,
53            data: Some(data),
54            errors: Vec::new(),
55            warnings,
56        }
57    }
58}
59
60impl JsonEnvelope<()> {
61    /// Creates a failed envelope with one structured error.
62    pub fn error(error: JsonMessage) -> Self {
63        Self::failure(vec![error])
64    }
65
66    /// Creates a failed envelope with structured errors.
67    pub const fn failure(errors: Vec<JsonMessage>) -> Self {
68        Self {
69            schema_version: JSON_SCHEMA_VERSION,
70            success: false,
71            data: None,
72            errors,
73            warnings: Vec::new(),
74        }
75    }
76}
77
78/// Severity level for a structured JSON diagnostic.
79///
80/// These levels classify diagnostics attached to an envelope. Progress,
81/// informational, and debug records should be modeled as command output data or
82/// stream events instead.
83#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(rename_all = "snake_case")]
85pub enum JsonMessageLevel {
86    /// Error message.
87    Error,
88    /// Warning message.
89    Warning,
90}
91
92/// Structured diagnostic entry for JSON output.
93///
94/// Diagnostics describe errors and warnings associated with command output. They
95/// are not intended for progress, informational, or debug events.
96#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
97pub struct JsonMessage {
98    /// Diagnostic severity level.
99    pub level: JsonMessageLevel,
100    /// Stable machine-readable diagnostic code.
101    pub code: String,
102    /// Human-readable diagnostic message.
103    pub message: String,
104    /// Optional structured context for the diagnostic.
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub details: Option<Value>,
107}
108
109impl JsonMessage {
110    /// Creates a structured error without details.
111    pub fn error(code: impl Into<String>, message: impl Into<String>) -> Self {
112        Self {
113            level: JsonMessageLevel::Error,
114            code: code.into(),
115            message: message.into(),
116            details: None,
117        }
118    }
119
120    /// Creates a structured warning without details.
121    pub fn warning(code: impl Into<String>, message: impl Into<String>) -> Self {
122        Self {
123            level: JsonMessageLevel::Warning,
124            code: code.into(),
125            message: message.into(),
126            details: None,
127        }
128    }
129
130    /// Adds structured details to the diagnostic.
131    pub fn with_details(mut self, details: Value) -> Self {
132        self.details = Some(details);
133        self
134    }
135}
136
137/// Prints a serializable object: envelope-wrapped in `--json` mode, pretty-printed otherwise.
138///
139/// Use this for objects that have no human-readable `Display` format (block data, RPC responses,
140/// etc.).
141pub fn print_json_object<T: Serialize>(value: T) -> Result<()> {
142    if foundry_common::shell::is_json() {
143        print_json_success(value)
144    } else {
145        sh_println!("{}", serde_json::to_string_pretty(&value)?)?;
146        Ok(())
147    }
148}
149
150/// Prints a value as one compact JSON line on stdout and flushes.
151///
152/// Bypasses the shell verbosity layer so `--quiet` cannot suppress structured
153/// output the caller explicitly asked for.
154pub fn print_json<T: Serialize>(value: &T) -> Result<()> {
155    let s = to_string(value)?;
156    let mut shell = foundry_common::shell::Shell::get();
157    let out = shell.out();
158    writeln!(out, "{s}")?;
159    out.flush()?;
160    Ok(())
161}
162
163/// Prints a successful JSON envelope to stdout.
164pub fn print_json_success<T: Serialize>(data: T) -> Result<()> {
165    print_json(&JsonEnvelope::success(data))
166}
167
168/// Prints a successful JSON envelope with warnings to stdout.
169pub fn print_json_success_with_warnings<T: Serialize>(
170    data: T,
171    warnings: Vec<JsonMessage>,
172) -> Result<()> {
173    print_json(&JsonEnvelope::success_with_warnings(data, warnings))
174}
175
176/// Prints command output that may already be JSON: parsed and envelope-wrapped in `--json` mode,
177/// plain text otherwise. If the output is not valid JSON, it is wrapped as a scalar string.
178pub fn print_json_value_or_scalar(value: impl AsRef<str> + std::fmt::Display) -> Result<()> {
179    if shell::is_json() {
180        match serde_json::from_str::<Value>(value.as_ref()) {
181            Ok(value) => print_json_success(value),
182            Err(_) => print_json_success(value.as_ref()),
183        }
184    } else {
185        sh_println!("{value}")?;
186        Ok(())
187    }
188}
189
190/// Prints a scalar value: JSON envelope in `--json` mode, plain text otherwise.
191pub fn print_scalar(value: impl Serialize + std::fmt::Display) -> Result<()> {
192    if shell::is_json() {
193        print_json_success(value)
194    } else {
195        sh_println!("{value}")?;
196        Ok(())
197    }
198}
199
200/// Prints a list of serializable items: JSON envelope wrapping an array in `--json` mode,
201/// one item per line otherwise.
202pub fn print_list<T: Serialize + std::fmt::Display>(items: &[T]) -> Result<()> {
203    if shell::is_json() {
204        print_json_success(items)
205    } else {
206        for item in items {
207            sh_println!("{item}")?;
208        }
209        Ok(())
210    }
211}
212
213/// Prints ABI-decoded tokens: JSON envelope wrapping a value array in `--json` mode,
214/// one formatted token per line otherwise.
215pub fn print_tokens(tokens: &[DynSolValue]) -> Result<()> {
216    if shell::is_json() {
217        let values = tokens
218            .iter()
219            .cloned()
220            .map(|t| serialize_value_as_json(t, None, true))
221            .collect::<Result<Vec<Value>>>()?;
222        print_json_success(values)
223    } else {
224        format_tokens(tokens).try_for_each(|t| sh_println!("{t}"))
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use serde_json::{json, to_value};
232
233    #[derive(Serialize)]
234    struct BuildData {
235        contracts: usize,
236    }
237
238    #[test]
239    fn success_envelope_serializes_all_top_level_fields() {
240        let envelope = JsonEnvelope::success(BuildData { contracts: 2 });
241
242        let json = to_string(&envelope).unwrap();
243
244        assert_eq!(
245            json,
246            r#"{"schema_version":1,"success":true,"data":{"contracts":2},"errors":[],"warnings":[]}"#
247        );
248    }
249
250    #[test]
251    fn warning_details_are_structured() {
252        let warning = JsonMessage::warning("compiler.remappings", "auto-detected remappings")
253            .with_details(json!({ "count": 3 }));
254        let envelope =
255            JsonEnvelope::success_with_warnings(BuildData { contracts: 1 }, vec![warning]);
256
257        let value = to_value(&envelope).unwrap();
258
259        assert_eq!(value["success"], true);
260        assert_eq!(value["warnings"][0]["level"], "warning");
261        assert_eq!(value["warnings"][0]["code"], "compiler.remappings");
262        assert_eq!(value["warnings"][0]["details"]["count"], 3);
263    }
264
265    #[test]
266    fn failure_envelope_serializes_null_data_and_structured_errors() {
267        let error = JsonMessage::error("config.invalid", "invalid foundry.toml")
268            .with_details(json!({ "path": "foundry.toml" }));
269        let envelope = JsonEnvelope::error(error);
270
271        let value = to_value(&envelope).unwrap();
272
273        assert_eq!(value["schema_version"], JSON_SCHEMA_VERSION);
274        assert_eq!(value["success"], false);
275        assert!(value["data"].is_null());
276        assert_eq!(value["errors"][0]["level"], "error");
277        assert_eq!(value["errors"][0]["code"], "config.invalid");
278        assert_eq!(value["errors"][0]["details"]["path"], "foundry.toml");
279        assert_eq!(value["warnings"], json!([]));
280    }
281}