Skip to main content

iphone_cli/
human.rs

1//! `--human`: the same results, laid out for a person reading a terminal.
2
3use serde_json::Value;
4
5fn s(v: &Value) -> String {
6    match v {
7        Value::String(s) => s.clone(),
8        Value::Null => String::new(),
9        other => other.to_string(),
10    }
11}
12
13fn element_line(e: &Value) -> String {
14    let mut line = format!("{:<13}", s(&e["role"]));
15    if let Some(l) = e["label"].as_str() {
16        line.push_str(&format!(" \"{l}\""));
17    }
18    if let Some(v) = e["value"].as_str() {
19        line.push_str(&format!(" = \"{v}\""));
20    }
21    if let Some(i) = e["identifier"].as_str() {
22        line.push_str(&format!(" #{i}"));
23    }
24    if let f @ Value::Object(_) = &e["frame"] {
25        line.push_str(&format!(
26            "  @{},{} {}x{}",
27            s(&f["x"]),
28            s(&f["y"]),
29            s(&f["w"]),
30            s(&f["h"])
31        ));
32    }
33    if e["enabled"] == false {
34        line.push_str("  (disabled)");
35    }
36    if e["selected"] == true {
37        line.push_str("  (selected)");
38    }
39    if e["focused"] == true {
40        line.push_str("  (focused)");
41    }
42    if e["on_screen"] == false {
43        line.push_str("  (off screen)");
44    }
45    line.push_str(&format!("  [{}]", s(&e["id"])));
46    line
47}
48
49fn type_observation(v: &Value, out: &mut Vec<String>) {
50    if v.get("value_changed").is_some() {
51        let parts: Vec<String> = [
52            "verified",
53            "value_before",
54            "value",
55            "value_changed",
56            "screen_changed",
57            "submit_sent",
58        ]
59        .iter()
60        .map(|key| format!("{key}={}", v[*key]))
61        .collect();
62        out.push(format!("  {}", parts.join("  ")));
63    }
64    if let Some(message) = v["warning"]["message"].as_str() {
65        out.push(format!("  ⚠ {}: {message}", s(&v["warning"]["code"])));
66        if let Some(hint) = v["warning"]["hint"].as_str() {
67            out.push(format!("  → {hint}"));
68        }
69    }
70}
71
72pub fn render(cmd: &str, v: &Value) -> String {
73    let mut out = Vec::new();
74    if v["ok"] != true {
75        out.push(format!(
76            "✗ {} ({}): {}",
77            s(&v["error"]["code"]),
78            s(&v["outcome"]),
79            s(&v["error"]["message"])
80        ));
81        if let Some(h) = v["error"]["hint"].as_str() {
82            out.push(format!("  → {h}"));
83        }
84        if let Some(c) = v["candidates"].as_array() {
85            for e in c {
86                out.push(format!("  · {}", element_line(e)));
87            }
88        }
89        if let step @ Value::Object(_) = &v["failed_step"] {
90            out.push(format!("  step {} ({})", s(&step["index"]), s(&step["kind"])));
91        }
92        if let call @ Value::Object(_) = &v["failed_call"] {
93            out.push(match call["line"].as_u64() {
94                Some(line) => format!("  line {line}: {}", s(&call["cmd"])),
95                None => format!("  in {}", s(&call["cmd"])),
96            });
97        }
98        if let Some(line) = v["line"].as_u64() {
99            out.push(format!("  line {line}"));
100        }
101        if let Some(sent) = v["inputs_sent"].as_u64().filter(|n| *n > 0) {
102            out.push(format!("  {sent} calls had already sent input"));
103        }
104        if let Some(labels) = v["screen_summary"]["labels"].as_array() {
105            let l: Vec<String> = labels.iter().map(s).collect();
106            out.push(format!("  on screen: {}", l.join(" · ")));
107        }
108        type_observation(v, &mut out);
109        out.push(format!("  {} ms", s(&v["elapsed_ms"])));
110        return out.join("\n");
111    }
112    match cmd {
113        "connect" => {
114            out.push(format!("✓ {}  wifi  {}  UDID verified, address saved", s(&v["udid"]), s(&v["ip"])));
115            out.push(s(&v["hint"]));
116        }
117        "read" | "find" => {
118            if cmd == "read" {
119                let apps: Vec<String> = v["apps"]
120                    .as_array()
121                    .map(|a| a.iter().map(|x| s(&x["name"])).collect())
122                    .unwrap_or_default();
123                out.push(format!(
124                    "{}  {}x{}  {} elements",
125                    apps.join(", "),
126                    s(&v["screen"]["width"]),
127                    s(&v["screen"]["height"]),
128                    s(&v["count"])
129                ));
130            } else {
131                out.push(format!("{} match(es) for {}", s(&v["count"]), s(&v["selector"])));
132            }
133            for e in v["elements"].as_array().into_iter().flatten() {
134                let indent = "  ".repeat(e["depth"].as_u64().unwrap_or(0) as usize);
135                out.push(format!("{indent}{}", element_line(e)));
136            }
137        }
138        "diagnose" => {
139            out.push(s(&v["report"]));
140            for finding in v["findings"].as_array().into_iter().flatten() {
141                out.push(format!("  {}", s(finding)));
142            }
143            out.push(s(&v["hint"]));
144        }
145        "doctor" => {
146            for c in v["checks"].as_array().into_iter().flatten() {
147                let mark = match c["status"].as_str() {
148                    Some("ok") => "✓",
149                    Some("fail") => "✗",
150                    Some("warn") => "!",
151                    Some("skipped") => "-",
152                    _ => "·",
153                };
154                let req = if c["required"] == true { "required" } else { "recommended" };
155                let mut line = format!("{mark} {:<22} {req}", s(&c["check"]));
156                if let Some(d) = c["detail"].as_str() {
157                    line.push_str(&format!("  ({d})"));
158                }
159                out.push(line);
160                if c["status"] != "ok"
161                    && let Some(a) = c["user_action"].as_str() {
162                        out.push(format!("    → {a}"));
163                    }
164            }
165            out.push(if v["ready"] == true { "ready".into() } else { "not ready".to_string() });
166        }
167        "devices" => {
168            for d in v["devices"].as_array().into_iter().flatten() {
169                out.push(format!(
170                    "{}  {}  iOS {}  {}  {}",
171                    s(&d["udid"]),
172                    s(&d["connection"]),
173                    s(&d["ios_version"]),
174                    s(&d["model"]),
175                    s(&d["state"])
176                ));
177            }
178            if out.is_empty() {
179                out.push("no devices".into());
180            }
181        }
182        "apps" => {
183            for a in v["apps"].as_array().into_iter().flatten() {
184                out.push(format!("{:<44} {}", s(&a["bundle_id"]), s(&a["name"])));
185            }
186        }
187        "scripts" => {
188            for r in v["scripts"].as_array().into_iter().flatten() {
189                out.push(format!("{:<24} {}  [{}]", s(&r["name"]), s(&r["description"]), s(&r["source"])));
190            }
191        }
192        "script" | "batch" => {
193            for line in v["logs"].as_array().into_iter().flatten() {
194                out.push(format!("  {}", s(line)));
195            }
196            for st in v["steps"].as_array().into_iter().flatten() {
197                out.push(format!(
198                    "✓ {:>2} {:<13} {:>5} ms",
199                    s(&st["index"]),
200                    s(&st["kind"]),
201                    s(&st["elapsed_ms"])
202                ));
203                if st["kind"] == "type" {
204                    type_observation(st, &mut out);
205                }
206            }
207            if let Some(o) = v["outputs"].as_object() {
208                for (k, val) in o {
209                    out.push(format!("{k} = {}", match val {
210                        Value::String(x) => x.clone(),
211                        other => serde_json::to_string_pretty(other).unwrap_or_default(),
212                    }));
213                }
214            }
215            out.push(format!("{} ms", s(&v["elapsed_ms"])));
216        }
217        _ => {
218            let mut parts = vec!["✓".to_string()];
219            for key in ["screen_changed", "foreground", "found", "scrolls", "value", "clipboard_restored", "path", "state", "stopped", "on", "focus", "set_by_iph"] {
220                if v.get("value_changed").is_some() && matches!(key, "value" | "screen_changed") {
221                    continue;
222                }
223                if !v[key].is_null() {
224                    parts.push(format!("{key}={}", s(&v[key])));
225                }
226            }
227            let e = &v["element"];
228            if e.is_object() {
229                let name = ["label", "value", "role"].iter().map(|k| s(&e[*k])).find(|n| !n.is_empty()).unwrap_or_default();
230                parts.push(format!("element=\"{name}\""));
231            }
232            parts.push(format!("{} ms", s(&v["elapsed_ms"])));
233            out.push(parts.join("  "));
234        }
235    }
236    type_observation(v, &mut out);
237    out.join("\n")
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243    use serde_json::json;
244
245    #[test]
246    fn type_warnings_and_unknown_observations_are_visible() {
247        let mut value = json!({
248            "ok": true, "value_before": "", "value": "", "verified": true,
249            "value_changed": false, "screen_changed": false, "submit_sent": false,
250            "warning": {"code": "value_unchanged", "message": "value is unchanged", "hint": "check paste permission"},
251        });
252        let text = render("type", &value);
253        assert!(text.contains("value_before=\"\""));
254        assert!(text.contains("value_changed=false"));
255        assert!(text.contains("value_unchanged: value is unchanged"));
256        assert!(text.contains("check paste permission"));
257        let mut step = value.clone();
258        step["kind"] = json!("type");
259        let batch = json!({"ok": true, "steps": [step]});
260        assert!(render("batch", &batch).contains("value_unchanged: value is unchanged"));
261        value["value"] = Value::Null;
262        value["value_changed"] = Value::Null;
263        value["screen_changed"] = Value::Null;
264        value["verified"] = json!(false);
265        let text = render("type", &value);
266        assert!(text.contains("value=null"));
267        assert!(text.contains("screen_changed=null"));
268        value["ok"] = json!(false);
269        value["error"] = json!({"code": "type_not_verified", "message": "Return withheld"});
270        let text = render("type", &value);
271        assert!(text.contains("Return withheld"));
272        assert!(text.contains("value_changed=null"));
273        assert!(text.contains("value_unchanged: value is unchanged"));
274    }
275
276    #[test]
277    fn element_without_label() {
278        let v = json!({"ok": true, "element": {"role": "search_field", "value": "검색"}, "elapsed_ms": 5});
279        assert_eq!(render("tap", &v), "✓  element=\"검색\"  5 ms");
280        let v = json!({"ok": false, "error": {"code": "x", "message": "m"}, "failed_step": {}, "failed_call": {}});
281        render("script", &v);
282    }
283}