1use cli_core::render::{ErrorReply, RenderError, WireValue, parse_wire, reparse_list};
4use scripting::nomiscript::{Value, format_value, list_to_vec};
5
6pub 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
36pub 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
49pub 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}