tinsel 1.1.0

Clean terminal output with a little sparkle: live step lists, spinners, tables, trees, prompts and full-screen apps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! JSON, indented and coloured: for showing API responses and config.

use std::fmt;

use crate::block::Block;
use crate::style::paint;
use crate::style::palette::{AMBER, BLUSH, MUTED, ROSE, SAGE};
use crate::term::content_width;
use crate::text;

/// Why [`json`] couldn't read its input, and where.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JsonError {
    line: usize,
    column: usize,
    message: String,
}

impl JsonError {
    /// The line the problem is on, from 1.
    pub fn line(&self) -> usize {
        self.line
    }

    /// The column, from 1, counted in characters.
    pub fn column(&self) -> usize {
        self.column
    }

    /// What was wrong, without where: "expected a value", say.
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for JsonError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} at line {}, column {}", self.message, self.line, self.column)
    }
}

impl std::error::Error for JsonError {}

/// A parsed value, keeping strings and numbers exactly as written.
enum Value<'a> {
    Object(Vec<(&'a str, Value<'a>)>),
    Array(Vec<Value<'a>>),
    String(&'a str),
    Number(&'a str),
    Literal(&'a str),
}

/// JSON text indented and coloured: keys in blush, strings in sage, numbers in amber,
/// `true`/`false`/`null` in rose. Short arrays of plain values stay on one line. Key order
/// and the exact text of strings and numbers are kept.
///
/// ```
/// let pretty = tinsel::json(r#"{"name":"my-app","ports":[80,443],"tls":true}"#)?;
/// pretty.print();
/// assert_eq!(pretty.plain().lines().nth(2), Some(r#"    "ports": [80, 443],"#));
/// # Ok::<(), tinsel::JsonError>(())
/// ```
///
/// # Errors
///
/// A [`JsonError`] saying what's wrong and where, if `src` isn't valid JSON.
pub fn json(src: &str) -> Result<Block, JsonError> {
    let mut p = Parser { src, at: 0, depth: 0 };
    p.space();
    let value = p.value()?;
    p.space();
    if p.at < src.len() {
        return Err(p.error("unexpected text after the end"));
    }
    let mut out = Vec::new();
    let mut first = String::from("  ");
    draw(&value, 1, &mut first, &mut out);
    out.push(first);
    Ok(out.into())
}

/// How deep arrays and objects may nest before the input is refused, so a hostile
/// `[[[[…` can't run the parser out of stack.
const MAX_DEPTH: usize = 512;

struct Parser<'a> {
    src: &'a str,
    at: usize,
    depth: usize,
}

impl<'a> Parser<'a> {
    fn peek(&self) -> Option<u8> {
        self.src.as_bytes().get(self.at).copied()
    }

    fn space(&mut self) {
        while self.peek().is_some_and(|b| b.is_ascii_whitespace()) {
            self.at += 1;
        }
    }

    fn error(&self, message: &str) -> JsonError {
        let before = &self.src[..self.at.min(self.src.len())];
        let line = before.matches('\n').count() + 1;
        let column = before.rsplit('\n').next().map_or(0, |l| l.chars().count()) + 1;
        JsonError {
            line,
            column,
            message: message.into(),
        }
    }

    fn expect(&mut self, b: u8, what: &str) -> Result<(), JsonError> {
        self.space();
        if self.peek() == Some(b) {
            self.at += 1;
            Ok(())
        } else {
            Err(self.error(&format!("expected {what}")))
        }
    }

    fn value(&mut self) -> Result<Value<'a>, JsonError> {
        self.space();
        if matches!(self.peek(), Some(b'{' | b'[')) {
            if self.depth >= MAX_DEPTH {
                return Err(self.error("this nests too deeply"));
            }
            self.depth += 1;
            let value = self.nested();
            self.depth -= 1;
            return value;
        }
        self.scalar()
    }

    /// An object or an array.
    fn nested(&mut self) -> Result<Value<'a>, JsonError> {
        match self.peek() {
            Some(b'{') => {
                self.at += 1;
                let mut fields = Vec::new();
                self.space();
                if self.peek() == Some(b'}') {
                    self.at += 1;
                    return Ok(Value::Object(fields));
                }
                loop {
                    self.space();
                    if self.peek() != Some(b'"') {
                        return Err(self.error("expected a key in quotes"));
                    }
                    let key = self.string()?;
                    self.expect(b':', "':' after the key")?;
                    fields.push((key, self.value()?));
                    self.space();
                    match self.peek() {
                        Some(b',') => self.at += 1,
                        Some(b'}') => {
                            self.at += 1;
                            return Ok(Value::Object(fields));
                        }
                        _ => return Err(self.error("expected ',' or '}'")),
                    }
                }
            }
            Some(b'[') => {
                self.at += 1;
                let mut items = Vec::new();
                self.space();
                if self.peek() == Some(b']') {
                    self.at += 1;
                    return Ok(Value::Array(items));
                }
                loop {
                    items.push(self.value()?);
                    self.space();
                    match self.peek() {
                        Some(b',') => self.at += 1,
                        Some(b']') => {
                            self.at += 1;
                            return Ok(Value::Array(items));
                        }
                        _ => return Err(self.error("expected ',' or ']'")),
                    }
                }
            }
            _ => self.scalar(),
        }
    }

    /// A string, number or literal.
    fn scalar(&mut self) -> Result<Value<'a>, JsonError> {
        match self.peek() {
            Some(b'"') => Ok(Value::String(self.string()?)),
            Some(b'-' | b'0'..=b'9') => {
                let start = self.at;
                while self.peek().is_some_and(|b| b.is_ascii_digit() || b"+-.eE".contains(&b)) {
                    self.at += 1;
                }
                let n = &self.src[start..self.at];
                if n.parse::<f64>().is_err() {
                    self.at = start;
                    return Err(self.error("this isn't a number"));
                }
                Ok(Value::Number(n))
            }
            Some(_) => {
                for word in ["true", "false", "null"] {
                    if self.src[self.at..].starts_with(word) {
                        self.at += word.len();
                        return Ok(Value::Literal(word));
                    }
                }
                Err(self.error("expected a value"))
            }
            None => Err(self.error("the text ended too soon")),
        }
    }

    /// A string, quotes included, exactly as written.
    fn string(&mut self) -> Result<&'a str, JsonError> {
        let start = self.at;
        self.at += 1;
        loop {
            match self.peek() {
                Some(b'"') => {
                    self.at += 1;
                    return Ok(&self.src[start..self.at]);
                }
                Some(b'\\') => {
                    self.at += 1;
                    match self.peek() {
                        Some(b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't') => self.at += 1,
                        Some(b'u')
                            if self
                                .src
                                .as_bytes()
                                .get(self.at + 1..self.at + 5)
                                .is_some_and(|h| h.iter().all(u8::is_ascii_hexdigit)) =>
                        {
                            self.at += 5
                        }
                        None => {}
                        Some(_) => return Err(self.error("this escape isn't one JSON knows")),
                    }
                }
                // Control characters must be escaped in JSON, and letting them through
                // would let the input send its own escape sequences to the terminal.
                Some(b) if b < 0x20 => return Err(self.error("a control character must be escaped in a string")),
                Some(_) => self.at += 1,
                None => {
                    self.at = start;
                    return Err(self.error("this string never ends"));
                }
            }
        }
    }
}

/// A string as written, but with DEL and the C1 controls (which JSON allows raw) shown
/// as `\u` escapes, so no string can reach the terminal as a control sequence.
fn shown(s: &str) -> std::borrow::Cow<'_, str> {
    if !s.chars().any(|c| ('\u{7f}'..='\u{9f}').contains(&c)) {
        return s.into();
    }
    s.chars()
        .map(|c| {
            if ('\u{7f}'..='\u{9f}').contains(&c) {
                format!("\\u{:04x}", c as u32)
            } else {
                c.to_string()
            }
        })
        .collect::<String>()
        .into()
}

/// Short arrays of plain values on one line, if they fit.
fn inline(value: &Value) -> Option<String> {
    let Value::Array(items) = value else { return None };
    let parts: Option<Vec<String>> = items
        .iter()
        .map(|v| match v {
            Value::String(s) => Some(paint(SAGE, &shown(s))),
            Value::Number(n) => Some(paint(AMBER, n)),
            Value::Literal(l) => Some(paint(ROSE, l)),
            _ => None,
        })
        .collect();
    let line = format!(
        "{}{}{}",
        paint(MUTED, "["),
        parts?.join(&paint(MUTED, ", ")),
        paint(MUTED, "]")
    );
    (text::width(&line) <= 40).then_some(line)
}

/// Draw `value` onto the end of `line`, pushing finished lines to `out`.
fn draw(value: &Value, depth: usize, line: &mut String, out: &mut Vec<String>) {
    let indent = |d: usize| format!("  {}", "  ".repeat(d));
    match value {
        Value::String(s) => *line += &paint(SAGE, &shown(s)),
        Value::Number(n) => *line += &paint(AMBER, n),
        Value::Literal(l) => *line += &paint(ROSE, l),
        Value::Array(items) if items.is_empty() => *line += &paint(MUTED, "[]"),
        Value::Object(fields) if fields.is_empty() => *line += &paint(MUTED, "{}"),
        Value::Array(_) if inline(value).is_some_and(|l| text::width(line) + text::width(&l) < content_width()) => {
            *line += &inline(value).unwrap_or_default();
        }
        Value::Array(items) => {
            *line += &paint(MUTED, "[");
            for (i, item) in items.iter().enumerate() {
                out.push(std::mem::replace(line, indent(depth)));
                draw(item, depth + 1, line, out);
                if i + 1 < items.len() {
                    *line += &paint(MUTED, ",");
                }
            }
            out.push(std::mem::replace(line, indent(depth - 1)));
            *line += &paint(MUTED, "]");
        }
        Value::Object(fields) => {
            *line += &paint(MUTED, "{");
            for (i, (key, v)) in fields.iter().enumerate() {
                out.push(std::mem::replace(line, indent(depth)));
                *line += &format!("{}{} ", paint(BLUSH, &shown(key)), paint(MUTED, ":"));
                draw(v, depth + 1, line, out);
                if i + 1 < fields.len() {
                    *line += &paint(MUTED, ",");
                }
            }
            out.push(std::mem::replace(line, indent(depth - 1)));
            *line += &paint(MUTED, "}");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn indents_nested_values() {
        crate::set_color_mode(crate::ColorMode::None);
        let out = json(r#"{"a":{"b":[1,{"c":null}]},"e":[],"s":"x\"y"}"#).unwrap();
        assert_eq!(
            out.plain(),
            [
                "  {",
                r#"    "a": {"#,
                r#"      "b": ["#,
                "        1,",
                "        {",
                r#"          "c": null"#,
                "        }",
                "      ]",
                "    },",
                r#"    "e": [],"#,
                r#"    "s": "x\"y""#,
                "  }",
            ]
            .join("\n")
        );
    }

    #[test]
    fn says_where_it_went_wrong() {
        let e = json("{\n  \"a\": 1,\n  \"b\" 2\n}").unwrap_err();
        assert_eq!(
            (e.line(), e.column(), e.message()),
            (3, 7, "expected ':' after the key")
        );
        assert_eq!(e.to_string(), "expected ':' after the key at line 3, column 7");
        assert!(json("[1, 2").is_err());
        assert!(json("\"open").is_err());
        assert!(json("1 2").is_err());
    }

    #[test]
    fn empty_objects_and_short_arrays_stay_on_one_line() {
        crate::set_color_mode(crate::ColorMode::None);
        let out = json(r#"{"o":{},"a":["x",1,true]}"#).unwrap().plain();
        assert!(
            out.contains(r#""o": {}"#) && out.contains(r#""a": ["x", 1, true]"#),
            "{out}"
        );
    }

    #[test]
    fn long_or_nested_arrays_get_a_line_each() {
        crate::set_color_mode(crate::ColorMode::None);
        let long = format!(r#"["{}", "{}"]"#, "a".repeat(30), "b".repeat(30));
        assert_eq!(json(&long).unwrap().len(), 4);
        assert_eq!(json("[[1]]").unwrap().len(), 3);
    }

    #[test]
    fn explains_each_kind_of_mistake() {
        let msg = |s: &str| json(s).unwrap_err().to_string();
        assert!(msg("{1: 2}").starts_with("expected a key in quotes"));
        assert!(msg(r#"{"a": 1 "b"}"#).starts_with("expected ',' or '}'"));
        assert!(msg("[1-2]").starts_with("this isn't a number"));
        assert!(msg("[nope]").starts_with("expected a value"));
        assert!(msg("[1,").starts_with("the text ended too soon"));
        assert!(msg(r#""\q""#).starts_with("this escape isn't one JSON knows"));
        assert!(msg(r#""\u12""#).starts_with("this escape isn't one JSON knows"));
    }

    #[test]
    fn deep_nesting_is_an_error_not_a_stack_overflow() {
        assert!(
            json(&"[".repeat(200_000))
                .unwrap_err()
                .to_string()
                .starts_with("this nests too deeply")
        );
        assert!(json(&"{\"a\":".repeat(200_000)).is_err());
        let ok = format!("{}{}", "[".repeat(MAX_DEPTH), "]".repeat(MAX_DEPTH));
        assert!(json(&ok).is_ok());
        let deep = format!("{}{}", "[".repeat(MAX_DEPTH + 1), "]".repeat(MAX_DEPTH + 1));
        assert!(json(&deep).is_err());
    }

    #[test]
    fn strings_cannot_carry_control_characters_to_the_terminal() {
        crate::set_color_mode(crate::ColorMode::None);
        assert!(json("\"\x1b[31mred\"").is_err());
        assert!(json("{\"a\tb\": 1}").is_err());
        assert!(json(r#""\u001b\n\"\\\/""#).is_ok());
        let out = json("[\"a\u{9b}31m\"]").unwrap().plain();
        assert!(!out.contains('\u{9b}') && out.contains(r"\u009b"), "{out}");
    }
}