Skip to main content

tui/tabs/
plist.rs

1//! Parsing of a data tab's reply: a list of plists, one per row.
2
3use cli_core::render::{ErrorReply, RenderError, WireValue, parse_wire, reparse_list};
4use scripting::nomiscript::{Value, format_value, list_to_vec};
5
6/// The rows of a list reply, each built by `row`; `nil` is no rows. A string
7/// value is the printed list a `form-options` reply carries.
8pub fn parse_rows<T>(
9    wire: &str,
10    row: impl Fn(&Value) -> Result<T, String>,
11) -> Result<Vec<T>, String> {
12    match parse_wire(wire) {
13        Err(RenderError::Server(ErrorReply { code, message, .. })) => {
14            Err(format!("[{code}] {message}"))
15        }
16        Err(e) => Err(e.to_string()),
17        Ok(WireValue::Value(Value::String(text))) => {
18            let printed = reparse_list(&text).map_err(|e| e.to_string())?;
19            rows_of(&printed, row)
20        }
21        Ok(WireValue::Value(value)) => rows_of(&value, row),
22    }
23}
24
25fn rows_of<T>(list: &Value, row: impl Fn(&Value) -> Result<T, String>) -> Result<Vec<T>, String> {
26    match list {
27        Value::Nil => Ok(Vec::new()),
28        value => list_to_vec(value)
29            .ok_or_else(|| format!("unexpected reply type: {}", format_value(value)))?
30            .iter()
31            .map(row)
32            .collect(),
33    }
34}
35
36/// The truth value after the `name` keyword: `t` or `nil`.
37pub fn plist_flag(plist: &Value, name: &str) -> Option<bool> {
38    let items = list_to_vec(plist)?;
39    let pos = items
40        .iter()
41        .position(|v| matches!(v, Value::Symbol(s) if s.eq_ignore_ascii_case(name)))?;
42    match items.get(pos + 1)? {
43        Value::T => Some(true),
44        Value::Nil => Some(false),
45        _ => None,
46    }
47}
48
49/// The string after the `name` keyword of `plist`.
50pub fn plist_text(plist: &Value, name: &str) -> Option<String> {
51    let items = list_to_vec(plist)?;
52    let pos = items
53        .iter()
54        .position(|v| matches!(v, Value::Symbol(s) if s.eq_ignore_ascii_case(name)))?;
55    match items.get(pos + 1)? {
56        Value::String(text) => Some(text.clone()),
57        _ => None,
58    }
59}