xcrs 0.4.13

Rust abstraction for Xcode command line tools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::time::Duration;

pub mod mcp;

const IOS_SIMULATOR_DESTINATION_PREFIX: &str = "platform=iOS Simulator,id=";

pub fn encode_base64(data: impl AsRef<[u8]>) -> String {
    use base64::{engine::general_purpose::STANDARD, Engine};

    STANDARD.encode(data)
}

pub fn extract_controlkit_elements(root: &serde_json::Value) -> Vec<serde_json::Value> {
    let mut elements = Vec::new();
    collect_controlkit_elements(root, &mut elements);
    elements
}

fn collect_controlkit_elements(element: &serde_json::Value, elements: &mut Vec<serde_json::Value>) {
    let object = match element.as_object() {
        Some(object) => object,
        None => return,
    };

    let rect = object.get("rect").and_then(serde_json::Value::as_object);
    let has_visible_rect = rect
        .and_then(|rect| {
            Some((
                rect.get("x")?.as_f64()?,
                rect.get("y")?.as_f64()?,
                rect.get("width")?.as_f64()?,
                rect.get("height")?.as_f64()?,
            ))
        })
        .is_some_and(|(x, y, width, height)| x >= 0.0 && y >= 0.0 && width > 0.0 && height > 0.0);
    let has_identity = ["label", "name", "value", "rawIdentifier"]
        .iter()
        .any(|key| {
            object
                .get(*key)
                .and_then(serde_json::Value::as_str)
                .is_some()
        });

    if has_visible_rect && has_identity {
        let keys = [
            "type",
            "label",
            "name",
            "value",
            "placeholderValue",
            "rawIdentifier",
            "rect",
        ];
        let element = keys
            .iter()
            .filter_map(|key| {
                object
                    .get(*key)
                    .map(|value| ((*key).to_string(), value.clone()))
            })
            .collect();
        elements.push(serde_json::Value::Object(element));
    }

    if let Some(children) = object.get("children").and_then(serde_json::Value::as_array) {
        for child in children {
            collect_controlkit_elements(child, elements);
        }
    }
}

#[derive(Debug, Clone)]
pub struct ControlKit {
    client: reqwest::Client,
    base_url: String,
}

impl Default for ControlKit {
    fn default() -> Self {
        Self::new(12004)
    }
}

impl ControlKit {
    pub fn new(port: u16) -> Self {
        Self::with_host("127.0.0.1", port)
    }

    pub fn with_host(host: &str, port: u16) -> Self {
        let host = if host.contains(':') && !host.starts_with('[') {
            format!("[{host}]")
        } else {
            host.to_string()
        };
        Self {
            client: reqwest::Client::new(),
            base_url: format!("http://{host}:{port}"),
        }
    }

    pub async fn health(&self) -> Result<()> {
        let response = self
            .client
            .get(format!("{}/health", self.base_url))
            .timeout(Duration::from_secs(5))
            .send()
            .await
            .with_context(|| format!("failed to connect to ControlKit at {}", self.base_url))?;

        if !response.status().is_success() {
            return Err(anyhow!(
                "ControlKit health check returned HTTP {}",
                response.status()
            ));
        }

        Ok(())
    }

    pub async fn call(&self, method: &str, params: serde_json::Value) -> Result<serde_json::Value> {
        let response = self
            .client
            .post(format!("{}/rpc", self.base_url))
            .timeout(Duration::from_secs(30))
            .json(&serde_json::json!({
                "jsonrpc": "2.0",
                "method": method,
                "params": params,
                "id": 1,
            }))
            .send()
            .await
            .with_context(|| format!("failed to connect to ControlKit at {}", self.base_url))?;

        let status = response.status();
        let body: serde_json::Value = response
            .json()
            .await
            .context("failed to decode ControlKit JSON-RPC response")?;

        if !status.is_success() {
            return Err(anyhow!("ControlKit returned HTTP {}: {}", status, body));
        }

        if let Some(error) = body.get("error") {
            return Err(anyhow!("ControlKit method '{method}' failed: {error}"));
        }

        body.get("result")
            .cloned()
            .ok_or_else(|| anyhow!("ControlKit response for '{method}' did not contain a result"))
    }
}

#[derive(Debug, Clone)]
pub struct XcodeCommandLineTools {
    xcrun_path: PathBuf,
    xcodebuild_path: PathBuf,
}

impl Default for XcodeCommandLineTools {
    fn default() -> Self {
        Self {
            xcrun_path: PathBuf::from("xcrun"),
            xcodebuild_path: PathBuf::from("xcodebuild"),
        }
    }
}

impl XcodeCommandLineTools {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_paths(xcrun_path: impl Into<PathBuf>, xcodebuild_path: impl Into<PathBuf>) -> Self {
        Self {
            xcrun_path: xcrun_path.into(),
            xcodebuild_path: xcodebuild_path.into(),
        }
    }

    pub fn simctl(&self) -> Simctl<'_> {
        Simctl { tools: self }
    }

    pub fn xcodebuild(&self) -> Xcodebuild<'_> {
        Xcodebuild { tools: self }
    }

    pub fn devicectl(&self) -> Devicectl<'_> {
        Devicectl { tools: self }
    }

    fn run_xcrun<I, S>(&self, args: I) -> Result<String>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        run_command(&self.xcrun_path, args)
    }

    fn run_xcodebuild<I, S>(&self, args: I) -> Result<String>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        run_command(&self.xcodebuild_path, args)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum ApplePlatform {
    #[serde(rename = "iOS")]
    Ios,
    #[serde(rename = "tvOS")]
    Tvos,
    #[serde(rename = "macOS")]
    Macos,
    #[serde(rename = "watchOS")]
    Watchos,
    #[serde(rename = "visionOS")]
    Visionos,
    #[serde(rename = "unknown")]
    Unknown,
}

impl ApplePlatform {
    fn from_runtime_identifier(runtime_identifier: &str) -> Self {
        if runtime_identifier.contains(".iOS-") {
            Self::Ios
        } else if runtime_identifier.contains(".tvOS-") {
            Self::Tvos
        } else if runtime_identifier.contains(".macOS-") {
            Self::Macos
        } else if runtime_identifier.contains(".watchOS-") {
            Self::Watchos
        } else if runtime_identifier.contains(".visionOS-") || runtime_identifier.contains(".xrOS-")
        {
            Self::Visionos
        } else {
            Self::Unknown
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Simulator {
    pub platform: ApplePlatform,
    pub runtime_identifier: String,
    pub name: String,
    pub udid: String,
    pub state: String,
    pub is_available: bool,
}

impl Simulator {
    pub fn is_booted(&self) -> bool {
        self.state == "Booted"
    }
}

#[derive(Debug, Deserialize)]
struct SimctlDeviceList {
    devices: BTreeMap<String, Vec<SimctlDevice>>,
}

#[derive(Debug, Deserialize)]
struct SimctlDevice {
    name: String,
    udid: String,
    state: String,
    #[serde(rename = "isAvailable")]
    is_available: Option<bool>,
}

pub struct Simctl<'a> {
    tools: &'a XcodeCommandLineTools,
}

impl Simctl<'_> {
    pub fn list_simulators(&self) -> Result<Vec<Simulator>> {
        let output = self
            .tools
            .run_xcrun(["simctl", "list", "devices", "--json"])?;
        parse_simctl_devices(&output)
    }

    pub fn find_simulator_by_name(&self, name: &str) -> Result<Simulator> {
        self.list_simulators()?
            .into_iter()
            .find(|simulator| simulator.name == name)
            .ok_or_else(|| anyhow!("iOS simulator named '{name}' was not found"))
    }

    pub fn find_simulator_by_udid(&self, udid: &str) -> Result<Simulator> {
        self.list_simulators()?
            .into_iter()
            .find(|simulator| simulator.udid == udid)
            .ok_or_else(|| anyhow!("iOS simulator with UDID '{udid}' was not found"))
    }

    pub fn boot(&self, udid: &str) -> Result<()> {
        if self.find_simulator_by_udid(udid)?.is_booted() {
            return Ok(());
        }

        self.tools.run_xcrun(["simctl", "boot", udid])?;
        Ok(())
    }

    pub fn shutdown(&self, udid: &str) -> Result<()> {
        if !self.find_simulator_by_udid(udid)?.is_booted() {
            return Ok(());
        }

        self.tools.run_xcrun(["simctl", "shutdown", udid])?;
        Ok(())
    }

    pub fn install_app(&self, udid: &str, app_path: impl AsRef<Path>) -> Result<()> {
        let app_path = app_path.as_ref();
        ensure_path_exists(app_path)?;

        let path = app_path
            .to_str()
            .ok_or_else(|| anyhow!("app path is not valid UTF-8: {}", app_path.display()))?;

        self.tools.run_xcrun(["simctl", "install", udid, path])?;
        Ok(())
    }

    pub fn uninstall_app(&self, udid: &str, bundle_id: &str) -> Result<()> {
        self.tools
            .run_xcrun(["simctl", "uninstall", udid, bundle_id])?;
        Ok(())
    }

    pub fn launch_app(&self, udid: &str, bundle_id: &str) -> Result<()> {
        self.tools
            .run_xcrun(["simctl", "launch", udid, bundle_id])?;
        Ok(())
    }

    pub fn terminate_app(&self, udid: &str, bundle_id: &str) -> Result<()> {
        self.tools
            .run_xcrun(["simctl", "terminate", udid, bundle_id])?;
        Ok(())
    }

    pub fn open_url(&self, udid: &str, url: &str) -> Result<()> {
        self.tools.run_xcrun(["simctl", "openurl", udid, url])?;
        Ok(())
    }

    pub fn screenshot(&self, udid: &str) -> Result<Vec<u8>> {
        let temporary_directory = tempfile::tempdir()?;
        let screenshot_path = temporary_directory.path().join("screenshot.png");
        let screenshot_path_string = screenshot_path
            .to_str()
            .ok_or_else(|| anyhow!("screenshot path is not valid UTF-8"))?;

        self.tools
            .run_xcrun(["simctl", "io", udid, "screenshot", screenshot_path_string])?;

        std::fs::read(&screenshot_path)
            .with_context(|| format!("failed to read {}", screenshot_path.display()))
    }

    pub fn app_container_path(&self, udid: &str, bundle_id: &str) -> Result<PathBuf> {
        let output =
            self.tools
                .run_xcrun(["simctl", "get_app_container", udid, bundle_id, "app"])?;
        let path = output.trim();
        if path.is_empty() {
            return Err(anyhow!(
                "simctl returned an empty app container path for '{bundle_id}'"
            ));
        }

        Ok(PathBuf::from(path))
    }
}

pub struct Devicectl<'a> {
    tools: &'a XcodeCommandLineTools,
}

impl Devicectl<'_> {
    /// Captures a PNG screenshot from a physical device known to CoreDevice.
    /// `device` accepts anything `devicectl --device` does: UDID, ECID,
    /// serial number, user-provided name, or DNS name.
    pub fn screenshot(&self, device: &str) -> Result<Vec<u8>> {
        let temporary_directory = tempfile::tempdir()?;
        let screenshot_path = temporary_directory.path().join("screenshot.png");
        let screenshot_path_string = screenshot_path
            .to_str()
            .ok_or_else(|| anyhow!("screenshot path is not valid UTF-8"))?;

        self.tools.run_xcrun([
            "devicectl",
            "device",
            "capture",
            "screenshot",
            "--device",
            device,
            "--destination",
            screenshot_path_string,
        ])?;

        std::fs::read(&screenshot_path)
            .with_context(|| format!("failed to read {}", screenshot_path.display()))
    }
}

#[derive(Debug, Clone)]
pub enum XcodeProject {
    Project(PathBuf),
    Workspace(PathBuf),
}

#[derive(Debug, Clone)]
pub struct BuildIosApp {
    pub project: XcodeProject,
    pub scheme: String,
    pub simulator_udid: String,
    pub derived_data_path: PathBuf,
    pub configuration: Option<String>,
}

pub struct Xcodebuild<'a> {
    tools: &'a XcodeCommandLineTools,
}

impl Xcodebuild<'_> {
    pub fn build_ios_app(&self, request: &BuildIosApp) -> Result<()> {
        let mut args = Vec::new();
        match &request.project {
            XcodeProject::Project(project_path) => {
                ensure_path_exists(project_path)?;
                args.push("-project".to_string());
                args.push(path_to_string(project_path)?);
            }
            XcodeProject::Workspace(workspace_path) => {
                ensure_path_exists(workspace_path)?;
                args.push("-workspace".to_string());
                args.push(path_to_string(workspace_path)?);
            }
        }

        args.push("-scheme".to_string());
        args.push(request.scheme.clone());
        args.push("-destination".to_string());
        args.push(format!(
            "{IOS_SIMULATOR_DESTINATION_PREFIX}{}",
            request.simulator_udid
        ));
        args.push("-derivedDataPath".to_string());
        args.push(path_to_string(&request.derived_data_path)?);

        if let Some(configuration) = &request.configuration {
            args.push("-configuration".to_string());
            args.push(configuration.clone());
        }

        args.push("build".to_string());

        self.tools.run_xcodebuild(args)?;
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct IosAppTestResult {
    pub simulator: Simulator,
    pub bundle_id: String,
    pub app_container_path: PathBuf,
}

#[derive(Debug, Clone)]
pub struct IosAppTest {
    pub simulator_name: Option<String>,
    pub simulator_udid: Option<String>,
    pub app_path: PathBuf,
    pub bundle_id: String,
    pub terminate_before_launch: bool,
}

impl XcodeCommandLineTools {
    pub fn run_ios_app_test(&self, request: &IosAppTest) -> Result<IosAppTestResult> {
        if request.simulator_name.is_none() && request.simulator_udid.is_none() {
            return Err(anyhow!(
                "either simulator_name or simulator_udid must be provided"
            ));
        }

        let simctl = self.simctl();
        let simulator = match (&request.simulator_udid, &request.simulator_name) {
            (Some(udid), _) => simctl.find_simulator_by_udid(udid)?,
            (None, Some(name)) => simctl.find_simulator_by_name(name)?,
            (None, None) => unreachable!("validated above"),
        };

        simctl.boot(&simulator.udid)?;
        simctl.install_app(&simulator.udid, &request.app_path)?;

        if request.terminate_before_launch {
            simctl.terminate_app(&simulator.udid, &request.bundle_id)?;
        }

        simctl.launch_app(&simulator.udid, &request.bundle_id)?;
        let app_container_path = simctl.app_container_path(&simulator.udid, &request.bundle_id)?;

        Ok(IosAppTestResult {
            simulator: simctl.find_simulator_by_udid(&simulator.udid)?,
            bundle_id: request.bundle_id.clone(),
            app_container_path,
        })
    }

    pub fn device_tunnel_address(&self, device_udid: &str) -> Result<String> {
        let output = self.run_xcrun([
            "devicectl",
            "device",
            "info",
            "details",
            "--device",
            device_udid,
        ])?;

        parse_device_tunnel_address(&output)
            .ok_or_else(|| anyhow!("device {device_udid} did not report a tunnel IP address"))
    }

    pub fn build_controlkit_device_runner(
        &self,
        request: &BuildControlKitDeviceRunner,
    ) -> Result<PathBuf> {
        ensure_path_exists(&request.project_path)?;
        let args = [
            "build-for-testing".to_string(),
            "-project".to_string(),
            path_to_string(&request.project_path)?,
            "-scheme".to_string(),
            request.scheme.clone(),
            "-configuration".to_string(),
            request.configuration.clone(),
            "-destination".to_string(),
            format!("id={}", request.device_udid),
            "-derivedDataPath".to_string(),
            path_to_string(&request.derived_data_path)?,
        ];
        self.run_xcodebuild(args)?;

        let products_path = request.derived_data_path.join("Build/Products");
        let entries = std::fs::read_dir(&products_path)
            .with_context(|| format!("failed to read {}", products_path.display()))?;
        let mut test_run_paths = entries
            .filter_map(|entry| entry.ok().map(|entry| entry.path()))
            .filter(|path| {
                path.extension()
                    .is_some_and(|extension| extension == "xctestrun")
            })
            .collect::<Vec<_>>();
        test_run_paths.sort();

        test_run_paths.into_iter().next().ok_or_else(|| {
            anyhow!(
                "Xcode did not create an .xctestrun file in {}",
                products_path.display()
            )
        })
    }

    pub fn start_controlkit_device_runner(
        &self,
        request: &StartControlKitDeviceRunner,
    ) -> Result<RunningControlKitDeviceRunner> {
        ensure_path_exists(&request.xctestrun_path)?;
        set_xctestrun_environment(
            &request.xctestrun_path,
            "CONTROLKIT_LISTEN_HOST",
            &request.listen_host,
        )?;
        set_xctestrun_environment(
            &request.xctestrun_path,
            "CONTROLKIT_LISTEN_PORT",
            &request.listen_port.to_string(),
        )?;

        let tunnel_host = self.device_tunnel_address(&request.device_udid)?;
        let log_file = std::fs::OpenOptions::new()
            .create(true)
            .truncate(true)
            .write(true)
            .open(&request.log_path)
            .with_context(|| format!("failed to open {}", request.log_path.display()))?;
        let error_log_file = log_file
            .try_clone()
            .with_context(|| format!("failed to clone {}", request.log_path.display()))?;

        let child = Command::new(&self.xcodebuild_path)
            .arg("test-without-building")
            .arg("-xctestrun")
            .arg(&request.xctestrun_path)
            .arg("-destination")
            .arg(format!("id={}", request.device_udid))
            .stdin(Stdio::null())
            .stdout(Stdio::from(log_file))
            .stderr(Stdio::from(error_log_file))
            .spawn()
            .with_context(|| {
                format!(
                    "failed to start ControlKit runner for device {}",
                    request.device_udid
                )
            })?;

        Ok(RunningControlKitDeviceRunner {
            process: child,
            tunnel_host,
            listen_port: request.listen_port,
            log_path: request.log_path.clone(),
        })
    }
}

#[derive(Debug, Clone)]
pub struct BuildControlKitDeviceRunner {
    pub project_path: PathBuf,
    pub scheme: String,
    pub configuration: String,
    pub device_udid: String,
    pub derived_data_path: PathBuf,
}

#[derive(Debug, Clone)]
pub struct StartControlKitDeviceRunner {
    pub device_udid: String,
    pub xctestrun_path: PathBuf,
    pub listen_host: String,
    pub listen_port: u16,
    pub log_path: PathBuf,
}

#[derive(Debug)]
pub struct RunningControlKitDeviceRunner {
    pub process: Child,
    pub tunnel_host: String,
    pub listen_port: u16,
    pub log_path: PathBuf,
}

fn set_xctestrun_environment(path: &Path, name: &str, value: &str) -> Result<()> {
    let key = format!(":TestConfigurations:0:TestTargets:0:EnvironmentVariables:{name}");
    let set_status = Command::new("/usr/libexec/PlistBuddy")
        .arg("-c")
        .arg(format!("Set {key} {value}"))
        .arg(path)
        .status()
        .with_context(|| format!("failed to update {}", path.display()))?;

    if set_status.success() {
        return Ok(());
    }

    let add_status = Command::new("/usr/libexec/PlistBuddy")
        .arg("-c")
        .arg(format!("Add {key} string {value}"))
        .arg(path)
        .status()
        .with_context(|| format!("failed to update {}", path.display()))?;

    if add_status.success() {
        return Ok(());
    }

    Err(anyhow!(
        "failed to set {name} in XCTest plan {}",
        path.display()
    ))
}

fn parse_device_tunnel_address(output: &str) -> Option<String> {
    output
        .lines()
        .find_map(|line| line.split_once("Tunnel IP Address:"))
        .map(|(_, address)| address.trim().to_string())
        .filter(|address| !address.is_empty())
}

pub fn parse_simctl_devices(output: &str) -> Result<Vec<Simulator>> {
    let list: SimctlDeviceList =
        serde_json::from_str(output).context("failed to parse simctl device list JSON")?;

    let mut simulators = Vec::new();
    for (runtime_identifier, devices) in list.devices {
        for device in devices {
            simulators.push(Simulator {
                platform: ApplePlatform::from_runtime_identifier(&runtime_identifier),
                runtime_identifier: runtime_identifier.clone(),
                name: device.name,
                udid: device.udid,
                state: device.state,
                is_available: device.is_available.unwrap_or(true),
            });
        }
    }

    Ok(simulators)
}

fn ensure_path_exists(path: &Path) -> Result<()> {
    if !path.exists() {
        return Err(anyhow!("path does not exist: {}", path.display()));
    }

    Ok(())
}

fn path_to_string(path: &Path) -> Result<String> {
    path.to_str()
        .map(ToOwned::to_owned)
        .ok_or_else(|| anyhow!("path is not valid UTF-8: {}", path.display()))
}

fn run_command<I, S>(program: &Path, args: I) -> Result<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let output = Command::new(program)
        .args(args)
        .output()
        .with_context(|| format!("failed to run {}", program.display()))?;

    command_output_to_result(program, output)
}

fn command_output_to_result(program: &Path, output: Output) -> Result<String> {
    if output.status.success() {
        return String::from_utf8(output.stdout)
            .with_context(|| format!("{} wrote invalid UTF-8 to stdout", program.display()));
    }

    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    let message = [stderr.trim(), stdout.trim()]
        .into_iter()
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join("\n");

    if message.is_empty() {
        return Err(anyhow!(
            "{} exited with status {}",
            program.display(),
            output.status
        ));
    }

    Err(anyhow!(
        "{} exited with status {}: {}",
        program.display(),
        output.status,
        message
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_simctl_devices() {
        let output = r#"{
          "devices": {
            "com.apple.CoreSimulator.SimRuntime.iOS-26-0": [
              {
                "lastBootedAt": "2026-07-30T08:00:00Z",
                "dataPath": "/tmp/device",
                "dataPathSize": 1,
                "logPath": "/tmp/logs",
                "udid": "00000000-0000-0000-0000-000000000000",
                "isAvailable": true,
                "deviceTypeIdentifier": "com.apple.CoreSimulator.SimDeviceType.iPhone-16",
                "state": "Booted",
                "name": "Test-iOS-26"
              }
            ]
          }
        }"#;

        let devices = parse_simctl_devices(output).expect("devices should parse");

        assert_eq!(devices.len(), 1);
        assert_eq!(devices[0].platform, ApplePlatform::Ios);
        assert_eq!(devices[0].name, "Test-iOS-26");
        assert_eq!(devices[0].state, "Booted");
        assert!(devices[0].is_booted());
    }

    #[test]
    fn parses_xros_simulator_runtime() {
        let output = r#"{
          "devices": {
            "com.apple.CoreSimulator.SimRuntime.xrOS-26-5": [
              {
                "udid": "00000000-0000-0000-0000-000000000001",
                "isAvailable": true,
                "state": "Shutdown",
                "name": "Apple Vision Pro"
              }
            ]
          }
        }"#;

        let devices = parse_simctl_devices(output).expect("devices should parse");

        assert_eq!(devices.len(), 1);
        assert_eq!(devices[0].platform, ApplePlatform::Visionos);
        assert_eq!(devices[0].name, "Apple Vision Pro");
    }

    #[test]
    fn parses_macos_runtime() {
        let output = r#"{
          "devices": {
            "com.apple.CoreSimulator.SimRuntime.macOS-26-0": [
              {
                "udid": "00000000-0000-0000-0000-000000000002",
                "isAvailable": true,
                "state": "Booted",
                "name": "Mac"
              }
            ]
          }
        }"#;

        let devices = parse_simctl_devices(output).expect("devices should parse");

        assert_eq!(devices.len(), 1);
        assert_eq!(devices[0].platform, ApplePlatform::Macos);
    }

    #[test]
    fn formats_ipv6_controlkit_url() {
        let controlkit = ControlKit::with_host("fdb4:e020:7377::1", 12006);
        assert_eq!(controlkit.base_url, "http://[fdb4:e020:7377::1]:12006");
    }

    #[test]
    fn parses_device_tunnel_address() {
        let output = "• Device Name: iPhone\n• Tunnel IP Address: fd55:33ce:ad87::1\n";
        assert_eq!(
            parse_device_tunnel_address(output).as_deref(),
            Some("fd55:33ce:ad87::1")
        );
    }
}