1
//! Parsing of a data tab's reply: a list of plists, one per row.
2

            
3
use cli_core::render::{ErrorReply, RenderError, WireValue, parse_wire, reparse_list};
4
use 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.
8
177
pub fn parse_rows<T>(
9
177
    wire: &str,
10
177
    row: impl Fn(&Value) -> Result<T, String>,
11
177
) -> Result<Vec<T>, String> {
12
177
    match parse_wire(wire) {
13
        Err(RenderError::Server(ErrorReply { code, message, .. })) => {
14
12
            Err(format!("[{code}] {message}"))
15
        }
16
        Err(e) => Err(e.to_string()),
17
        Ok(WireValue::Value(Value::String(text))) => {
18
56
            let printed = reparse_list(&text).map_err(|e| e.to_string())?;
19
56
            rows_of(&printed, row)
20
        }
21
109
        Ok(WireValue::Value(value)) => rows_of(&value, row),
22
    }
23
177
}
24

            
25
165
fn rows_of<T>(list: &Value, row: impl Fn(&Value) -> Result<T, String>) -> Result<Vec<T>, String> {
26
165
    match list {
27
21
        Value::Nil => Ok(Vec::new()),
28
144
        value => list_to_vec(value)
29
1
            .ok_or_else(|| format!("unexpected reply type: {}", format_value(value)))?
30
            .iter()
31
143
            .map(row)
32
            .collect(),
33
    }
34
165
}
35

            
36
/// The truth value after the `name` keyword: `t` or `nil`.
37
338
pub fn plist_flag(plist: &Value, name: &str) -> Option<bool> {
38
338
    let items = list_to_vec(plist)?;
39
338
    let pos = items
40
338
        .iter()
41
2027
        .position(|v| matches!(v, Value::Symbol(s) if s.eq_ignore_ascii_case(name)))?;
42
337
    match items.get(pos + 1)? {
43
315
        Value::T => Some(true),
44
22
        Value::Nil => Some(false),
45
        _ => None,
46
    }
47
338
}
48

            
49
/// The string after the `name` keyword of `plist`.
50
849
pub fn plist_text(plist: &Value, name: &str) -> Option<String> {
51
849
    let items = list_to_vec(plist)?;
52
849
    let pos = items
53
849
        .iter()
54
2734
        .position(|v| matches!(v, Value::Symbol(s) if s.eq_ignore_ascii_case(name)))?;
55
844
    match items.get(pos + 1)? {
56
843
        Value::String(text) => Some(text.clone()),
57
1
        _ => None,
58
    }
59
849
}