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
use crate::prelude::*;
use crate::shared::identifiers::IPadVariant;
use crate::shared::identifiers::{DeviceName, IPhoneVariant, RuntimeIdentifier};

#[derive(Debug, Serialize)]
#[non_exhaustive]
#[must_use = include_doc!(must_use_cmd_output)]
pub enum ListOutput {
	/// Contains the actual output of the command, parsed
	SuccessJson(ListJson),

	#[doc = include_doc!(cmd_success)]
	SuccessUnImplemented { stdout: String },

	#[doc = include_doc!(cmd_error)]
	ErrorUnImplemented { stderr: String },
}

impl ListOutput {
	/// Returns [Error::OutputErrored] if it didn't succeed.
	/// Used to make error handling of non-successful commands explicit
	pub fn success(&self) -> Result<&ListJson> {
		match self {
			ListOutput::SuccessJson(output) => Ok(output),
			_ => Err(Error::output_errored(self)),
		}
	}

	pub fn unwrap_success(&self) -> &ListJson {
		match self {
			ListOutput::SuccessJson(output) => output,
			_ => {
				error!(?self, "Tried to unwrap a non-successful ListOutput");
				panic!("Tried to unwrap a non-successful ListOutput")
			}
		}
	}

	pub fn get_success(&self) -> Option<&ListJson> {
		match self {
			ListOutput::SuccessJson(output) => Some(output),
			_ => None,
		}
	}

	/// Only used in CLI
	/// prefer [Self::get_success]
	#[cfg(feature = "cli")]
	pub fn get_success_reported(&self) -> std::result::Result<&ListJson, color_eyre::Report> {
		match self {
			Self::SuccessJson(output) => Ok(output),
			Self::ErrorUnImplemented { stderr } => Err(eyre!(
				"xcrun simctl list output didn't exist successfully: {:?}",
				stderr
			)),
			Self::SuccessUnImplemented { stdout } => Err(eyre!(
				"xcrun simctl list output didn't produce valid output: {:?}",
				stdout
			)),
		}
	}
}

impl CommandNomParsable for ListOutput {
	fn success_unimplemented(stdout: String) -> Self {
		Self::SuccessUnImplemented { stdout }
	}

	fn error_unimplemented(stderr: String) -> Self {
		Self::ErrorUnImplemented { stderr }
	}

	fn success_from_str(input: &str) -> Self {
		match serde_json::from_str(input) {
			Ok(output) => Self::SuccessJson(output),
			Err(e) => {
				error!(?e, "Failed to parse JSON");
				Self::success_unimplemented(input.to_owned())
			}
		}
	}
}

impl PublicCommandOutput for ListOutput {
	type PrimarySuccess = ListJson;

	fn success(&self) -> Result<&Self::PrimarySuccess> {
		match self {
			ListOutput::SuccessJson(output) => Ok(output),
			_ => Err(Error::output_errored(self)),
		}
	}
}

impl ListJson {
	/// Returns an iterator over the returned devices
	pub fn devices(&self) -> impl Iterator<Item = &ListDevice> + '_ {
		self.devices.values().flatten()
	}
}

#[derive(Deserialize, Debug, Serialize)]
pub struct ListJson {
	devices: HashMap<RuntimeIdentifier, Vec<ListDevice>>,
}

/// Allows for easier extraction of semantic information from
/// an iterator over [ListDevice]s.
#[extension_traits::extension(pub trait ListDevicesExt)]
impl<'src, T> T
where
	T: Iterator<Item = &'src ListDevice>,
{
	/// Consumes self,
	fn names(self) -> impl Iterator<Item = &'src DeviceName> {
		self.map(|device| &device.name)
	}

	fn a_device(mut self) -> Option<&'src ListDevice> {
		self.next()
	}
}

#[extension_traits::extension(pub trait ListDeviceNamesExt)]
impl<'src, T> T
where
	T: Iterator<Item = &'src DeviceName>,
{
	/// Tries to find the latest iPad in the list of devices
	/// Not necessarily booted already
	fn an_ipad(self) -> Option<&'src IPadVariant> {
		self.ipads().max()
	}

	/// Tries to find the latest iPhone in the list of devices
	/// Not necessarily booted already
	fn an_iphone(self) -> Option<&'src IPhoneVariant> {
		self.iphones().max()
	}

	fn iphones(self) -> impl Iterator<Item = &'src IPhoneVariant> {
		self.filter_map(|names| match names {
			DeviceName::IPhone(ref variant) => Some(variant),
			_ => None,
		})
	}

	fn ipads(self) -> impl Iterator<Item = &'src IPadVariant> {
		self.filter_map(|names| match names {
			DeviceName::IPad(ref variant) => Some(variant),
			_ => None,
		})
	}
}

#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all(deserialize = "camelCase"))]
pub struct ListDevice {
	pub availability_error: Option<String>,
	pub data_path: Utf8PathBuf,
	pub log_path: Utf8PathBuf,
	pub udid: String,
	pub is_available: bool,
	pub device_type_identifier: String,
	pub state: State,

	pub name: DeviceName,
}

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub enum State {
	Shutdown,
	Booted,
}

impl State {
	pub fn ready(&self) -> bool {
		matches!(self, State::Booted)
	}
}

impl ListDevice {
	pub fn ready(&self) -> bool {
		self.state.ready() && self.is_available
	}
}

#[cfg(test)]
mod tests {
	use tracing::debug;

	use super::*;

	#[test]
	fn test_simctl_list() {
		let example = include_str!(concat!(
			env!("CARGO_MANIFEST_DIR"),
			"/tests/simctl-list-full.json"
		));
		let output = serde_json::from_str::<ListJson>(example);
		match output {
			Ok(output) => {
				debug!("Output: {:?}", output);
			}
			Err(e) => {
				panic!("Error parsing: {:?}", e)
			}
		}
	}
}