Skip to main content

wt/output/
json.rs

1//! JSON output helpers: the newline-delimited framing used by `list` and
2//! `status --all` (spec §7 — one object per line, never a wrapping array).
3
4use serde::Serialize;
5
6use crate::error::Result;
7
8/// Serializes `value` to a single-line JSON string with no trailing newline.
9/// Callers write each line through [`crate::cx::Stream::line`], producing the
10/// newline-delimited stream.
11pub fn to_line<T: Serialize>(value: &T) -> Result<String> {
12    Ok(serde_json::to_string(value)?)
13}
14
15#[cfg(test)]
16mod tests {
17    use super::*;
18
19    #[test]
20    fn to_line_is_single_line() {
21        let line = to_line(&serde_json::json!({"a": 1, "b": [1, 2]})).unwrap();
22        assert!(!line.contains('\n'));
23    }
24
25    #[test]
26    fn lines_join_into_newline_delimited_stream() {
27        let a = to_line(&serde_json::json!({"n": 1})).unwrap();
28        let b = to_line(&serde_json::json!({"n": 2})).unwrap();
29        let stream = format!("{a}\n{b}\n");
30        assert_eq!(stream.lines().count(), 2);
31        // Each line is independently parseable (not a single array document).
32        for l in stream.lines() {
33            let _: serde_json::Value = serde_json::from_str(l).unwrap();
34        }
35    }
36}