1use 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
49pub fn render(cmd: &str, v: &Value) -> String {
50 let mut out = Vec::new();
51 if v["ok"] != true {
52 out.push(format!(
53 "✗ {} ({}): {}",
54 s(&v["error"]["code"]),
55 s(&v["outcome"]),
56 s(&v["error"]["message"])
57 ));
58 if let Some(h) = v["error"]["hint"].as_str() {
59 out.push(format!(" → {h}"));
60 }
61 if let Some(c) = v["candidates"].as_array() {
62 for e in c {
63 out.push(format!(" · {}", element_line(e)));
64 }
65 }
66 if let step @ Value::Object(_) = &v["failed_step"] {
67 out.push(format!(" step {} ({})", s(&step["index"]), s(&step["kind"])));
68 }
69 if let call @ Value::Object(_) = &v["failed_call"] {
70 out.push(match call["line"].as_u64() {
71 Some(line) => format!(" line {line}: {}", s(&call["cmd"])),
72 None => format!(" in {}", s(&call["cmd"])),
73 });
74 }
75 if let Some(line) = v["line"].as_u64() {
76 out.push(format!(" line {line}"));
77 }
78 if let Some(sent) = v["inputs_sent"].as_u64().filter(|n| *n > 0) {
79 out.push(format!(" {sent} calls had already sent input"));
80 }
81 if let Some(labels) = v["screen_summary"]["labels"].as_array() {
82 let l: Vec<String> = labels.iter().map(s).collect();
83 out.push(format!(" on screen: {}", l.join(" · ")));
84 }
85 out.push(format!(" {} ms", s(&v["elapsed_ms"])));
86 return out.join("\n");
87 }
88 match cmd {
89 "read" | "find" => {
90 if cmd == "read" {
91 let apps: Vec<String> = v["apps"]
92 .as_array()
93 .map(|a| a.iter().map(|x| s(&x["name"])).collect())
94 .unwrap_or_default();
95 out.push(format!(
96 "{} {}x{} {} elements",
97 apps.join(", "),
98 s(&v["screen"]["width"]),
99 s(&v["screen"]["height"]),
100 s(&v["count"])
101 ));
102 } else {
103 out.push(format!("{} match(es) for {}", s(&v["count"]), s(&v["selector"])));
104 }
105 for e in v["elements"].as_array().into_iter().flatten() {
106 let indent = " ".repeat(e["depth"].as_u64().unwrap_or(0) as usize);
107 out.push(format!("{indent}{}", element_line(e)));
108 }
109 }
110 "doctor" => {
111 for c in v["checks"].as_array().into_iter().flatten() {
112 let mark = match c["status"].as_str() {
113 Some("ok") => "✓",
114 Some("fail") => "✗",
115 Some("warn") => "!",
116 Some("skipped") => "-",
117 _ => "·",
118 };
119 let req = if c["required"] == true { "required" } else { "recommended" };
120 let mut line = format!("{mark} {:<22} {req}", s(&c["check"]));
121 if let Some(d) = c["detail"].as_str() {
122 line.push_str(&format!(" ({d})"));
123 }
124 out.push(line);
125 if c["status"] != "ok"
126 && let Some(a) = c["user_action"].as_str() {
127 out.push(format!(" → {a}"));
128 }
129 }
130 out.push(if v["ready"] == true { "ready".into() } else { "not ready".to_string() });
131 }
132 "devices" => {
133 for d in v["devices"].as_array().into_iter().flatten() {
134 out.push(format!(
135 "{} {} iOS {} {} {}",
136 s(&d["udid"]),
137 s(&d["connection"]),
138 s(&d["ios_version"]),
139 s(&d["model"]),
140 s(&d["state"])
141 ));
142 }
143 if out.is_empty() {
144 out.push("no devices".into());
145 }
146 }
147 "apps" => {
148 for a in v["apps"].as_array().into_iter().flatten() {
149 out.push(format!("{:<44} {}", s(&a["bundle_id"]), s(&a["name"])));
150 }
151 }
152 "scripts" => {
153 for r in v["scripts"].as_array().into_iter().flatten() {
154 out.push(format!("{:<24} {} [{}]", s(&r["name"]), s(&r["description"]), s(&r["source"])));
155 }
156 }
157 "script" | "batch" => {
158 for line in v["logs"].as_array().into_iter().flatten() {
159 out.push(format!(" {}", s(line)));
160 }
161 for st in v["steps"].as_array().into_iter().flatten() {
162 out.push(format!(
163 "✓ {:>2} {:<13} {:>5} ms",
164 s(&st["index"]),
165 s(&st["kind"]),
166 s(&st["elapsed_ms"])
167 ));
168 }
169 if let Some(o) = v["outputs"].as_object() {
170 for (k, val) in o {
171 out.push(format!("{k} = {}", match val {
172 Value::String(x) => x.clone(),
173 other => serde_json::to_string_pretty(other).unwrap_or_default(),
174 }));
175 }
176 }
177 out.push(format!("{} ms", s(&v["elapsed_ms"])));
178 }
179 _ => {
180 let mut parts = vec!["✓".to_string()];
181 for key in ["screen_changed", "foreground", "found", "scrolls", "value", "clipboard_restored", "path", "state", "stopped", "on", "focus", "set_by_iph"] {
182 if !v[key].is_null() {
183 parts.push(format!("{key}={}", s(&v[key])));
184 }
185 }
186 let e = &v["element"];
187 if e.is_object() {
188 let name = ["label", "value", "role"].iter().map(|k| s(&e[*k])).find(|n| !n.is_empty()).unwrap_or_default();
189 parts.push(format!("element=\"{name}\""));
190 }
191 parts.push(format!("{} ms", s(&v["elapsed_ms"])));
192 out.push(parts.join(" "));
193 }
194 }
195 out.join("\n")
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201 use serde_json::json;
202
203 #[test]
204 fn element_without_label() {
205 let v = json!({"ok": true, "element": {"role": "search_field", "value": "검색"}, "elapsed_ms": 5});
206 assert_eq!(render("tap", &v), "✓ element=\"검색\" 5 ms");
207 let v = json!({"ok": false, "error": {"code": "x", "message": "m"}, "failed_step": {}, "failed_call": {}});
208 render("script", &v);
209 }
210}