homeassistant_cli/
output.rs1use std::io::IsTerminal;
2
3use owo_colors::OwoColorize;
4
5use crate::api::HaError;
6
7#[derive(Clone, Copy, Debug, PartialEq, clap::ValueEnum)]
8pub enum OutputFormat {
9 Json,
10 Table,
11 Plain,
12}
13
14#[derive(Clone, Copy)]
15pub struct OutputConfig {
16 pub format: OutputFormat,
17 pub quiet: bool,
18}
19
20impl OutputConfig {
21 pub fn new(format_arg: Option<OutputFormat>, quiet: bool) -> Self {
22 let format = format_arg.unwrap_or_else(|| {
23 if std::io::stdout().is_terminal() {
24 OutputFormat::Table
25 } else {
26 OutputFormat::Json
27 }
28 });
29 Self { format, quiet }
30 }
31
32 pub fn is_json(&self) -> bool {
33 matches!(self.format, OutputFormat::Json)
34 }
35
36 pub fn print_data(&self, data: &str) {
38 println!("{data}");
39 }
40
41 pub fn print_message(&self, msg: &str) {
43 if !self.quiet {
44 eprintln!("{msg}");
45 }
46 }
47
48 pub fn print_error(&self, e: &HaError) {
51 if self.is_json() {
52 let envelope = serde_json::json!({
53 "ok": false,
54 "error": {
55 "code": e.error_code(),
56 "message": e.to_string()
57 }
58 });
59 println!(
60 "{}",
61 serde_json::to_string_pretty(&envelope).expect("serialize")
62 );
63 } else {
64 eprintln!("{e}");
65 }
66 }
67
68 pub fn print_result(&self, json_value: &serde_json::Value, human_message: &str) {
70 if self.is_json() {
71 println!(
72 "{}",
73 serde_json::to_string_pretty(json_value).expect("serialize")
74 );
75 } else {
76 println!("{human_message}");
77 }
78 }
79}
80
81pub fn colored_state(state: &str) -> String {
83 match state {
84 "on" | "open" | "home" | "active" | "playing" => state.green().to_string(),
85 "off" | "closed" | "not_home" | "idle" | "paused" => state.dimmed().to_string(),
86 "unavailable" | "unknown" => state.yellow().to_string(),
87 _ => state.to_owned(),
88 }
89}
90
91pub fn colored_entity_id(entity_id: &str) -> String {
94 match entity_id.split_once('.') {
95 Some((domain, name)) => format!("{}.{}", domain.dimmed(), name),
96 None => entity_id.to_owned(),
97 }
98}
99
100pub fn relative_time(iso: &str) -> String {
103 use std::time::{SystemTime, UNIX_EPOCH};
104
105 let now = SystemTime::now()
106 .duration_since(UNIX_EPOCH)
107 .map(|d| d.as_secs())
108 .unwrap_or(0);
109
110 match parse_unix_secs(iso) {
111 Some(ts) => {
112 let secs = now.saturating_sub(ts);
113 let s = if secs < 60 {
114 format!("{secs}s ago")
115 } else if secs < 3600 {
116 format!("{}m ago", secs / 60)
117 } else if secs < 86400 {
118 format!("{}h ago", secs / 3600)
119 } else {
120 format!("{}d ago", secs / 86400)
121 };
122 if secs >= 300 {
124 s.dimmed().to_string()
125 } else {
126 s
127 }
128 }
129 None => iso.to_owned(),
130 }
131}
132
133fn parse_unix_secs(s: &str) -> Option<u64> {
136 if s.len() < 19 {
137 return None;
138 }
139 let year: i64 = s.get(0..4)?.parse().ok()?;
140 let month: i64 = s.get(5..7)?.parse().ok()?;
141 let day: i64 = s.get(8..10)?.parse().ok()?;
142 let hour: i64 = s.get(11..13)?.parse().ok()?;
143 let min: i64 = s.get(14..16)?.parse().ok()?;
144 let sec: i64 = s.get(17..19)?.parse().ok()?;
145
146 let rest = s.get(19..)?;
148 let rest = if rest.starts_with('.') {
149 let end = rest.find(['+', '-', 'Z']).unwrap_or(rest.len());
150 &rest[end..]
151 } else {
152 rest
153 };
154 let tz_secs: i64 = if rest.is_empty() || rest == "Z" {
155 0
156 } else {
157 let sign: i64 = if rest.starts_with('-') { -1 } else { 1 };
158 let tz = rest.get(1..)?;
159 let h: i64 = tz.get(0..2)?.parse().ok()?;
160 let m: i64 = tz.get(3..5)?.parse().ok()?;
161 sign * (h * 3600 + m * 60)
162 };
163
164 let y = year - i64::from(month <= 2);
166 let era = y.div_euclid(400);
167 let yoe = y - era * 400;
168 let doy = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + day - 1;
169 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
170 let days = era * 146_097 + doe - 719_468;
171
172 let unix = days * 86_400 + hour * 3_600 + min * 60 + sec - tz_secs;
173 u64::try_from(unix).ok()
174}
175
176pub mod exit_codes {
177 use super::HaError;
178
179 pub const SUCCESS: i32 = 0;
180 pub const GENERAL_ERROR: i32 = 1;
181 pub const CONFIG_ERROR: i32 = 2;
182 pub const NOT_FOUND: i32 = 3;
183 pub const CONNECTION_ERROR: i32 = 4;
184
185 pub fn for_error(e: &HaError) -> i32 {
186 match e {
187 HaError::Auth(_) | HaError::InvalidInput(_) => CONFIG_ERROR,
188 HaError::NotFound(_) => NOT_FOUND,
189 HaError::Connection(_) => CONNECTION_ERROR,
190 _ => GENERAL_ERROR,
191 }
192 }
193}
194
195pub fn mask_credential(s: &str) -> String {
198 if s.len() <= 10 {
199 return "•".repeat(s.len());
200 }
201 format!("{}…{}", &s[..6], &s[s.len() - 4..])
202}
203
204pub fn kv_block(pairs: &[(&str, String)]) -> String {
206 let max_key = pairs.iter().map(|(k, _)| k.len()).max().unwrap_or(0);
207 pairs
208 .iter()
209 .map(|(k, v)| format!("{:width$} {}", k, v, width = max_key))
210 .collect::<Vec<_>>()
211 .join("\n")
212}
213
214fn visible_len(s: &str) -> usize {
216 let mut len = 0;
217 let mut in_escape = false;
218 for c in s.chars() {
219 if c == '\x1b' {
220 in_escape = true;
221 } else if in_escape {
222 if c == 'm' {
223 in_escape = false;
224 }
225 } else {
226 len += 1;
227 }
228 }
229 len
230}
231
232fn pad_cell(s: &str, width: usize) -> String {
234 let vlen = visible_len(s);
235 let padding = width.saturating_sub(vlen);
236 format!("{}{}", s, " ".repeat(padding))
237}
238
239pub fn table(headers: &[&str], rows: &[Vec<String>]) -> String {
242 let col_count = headers.len();
243 let mut widths: Vec<usize> = headers.iter().map(|h| h.len()).collect();
245 for row in rows {
246 for (i, cell) in row.iter().enumerate() {
247 if i < col_count {
248 widths[i] = widths[i].max(visible_len(cell));
249 }
250 }
251 }
252
253 let header_line: String = headers
254 .iter()
255 .enumerate()
256 .map(|(i, h)| pad_cell(&h.bold().to_string(), widths[i]))
257 .collect::<Vec<_>>()
258 .join(" ");
259
260 let sep: String = widths
261 .iter()
262 .map(|w| "─".repeat(*w).dimmed().to_string())
263 .collect::<Vec<_>>()
264 .join(" ");
265
266 let data_lines: Vec<String> = rows
267 .iter()
268 .map(|row| {
269 row.iter()
270 .enumerate()
271 .take(col_count)
272 .map(|(i, cell)| pad_cell(cell, widths[i]))
273 .collect::<Vec<_>>()
274 .join(" ")
275 })
276 .collect();
277
278 let mut out = vec![header_line, sep];
279 out.extend(data_lines);
280 out.join("\n")
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 #[test]
288 fn parse_unix_secs_handles_utc_z() {
289 assert_eq!(parse_unix_secs("1970-01-01T00:00:00Z"), Some(0));
291 }
292
293 #[test]
294 fn parse_unix_secs_handles_offset() {
295 assert_eq!(parse_unix_secs("1970-01-01T01:00:00+01:00"), Some(0));
297 }
298
299 #[test]
300 fn parse_unix_secs_handles_fractional_seconds() {
301 assert_eq!(parse_unix_secs("1970-01-01T00:00:01.999999+00:00"), Some(1));
302 }
303
304 #[test]
305 fn parse_unix_secs_rejects_short_input() {
306 assert_eq!(parse_unix_secs("2026-01"), None);
307 }
308
309 #[test]
310 fn relative_time_falls_back_on_invalid_input() {
311 assert_eq!(relative_time("not-a-date"), "not-a-date");
312 }
313
314 #[test]
315 fn mask_credential_masks_long_values() {
316 assert_eq!(mask_credential("abcdefghijklmnop"), "abcdef…mnop");
317 }
318
319 #[test]
320 fn mask_credential_dots_short_values() {
321 assert_eq!(mask_credential("short"), "•••••");
322 assert_eq!(mask_credential(""), "");
323 }
324
325 #[test]
326 fn kv_block_aligns_values() {
327 let pairs = [("entity_id", "light.x".into()), ("state", "on".into())];
328 let out = kv_block(&pairs);
329 let lines: Vec<&str> = out.lines().collect();
330 let v1_pos = lines[0].find("light.x").unwrap();
331 let v2_pos = lines[1].find("on").unwrap();
332 assert_eq!(v1_pos, v2_pos);
333 }
334
335 #[test]
336 fn table_renders_header_separator_and_rows() {
337 let headers = ["ENTITY", "STATE"];
338 let rows = vec![
339 vec!["light.living_room".into(), "on".into()],
340 vec!["switch.fan".into(), "off".into()],
341 ];
342 let out = table(&headers, &rows);
343 let lines: Vec<&str> = out.lines().collect();
344 assert!(lines[0].contains("ENTITY") && lines[0].contains("STATE"));
345 assert!(lines[1].contains("─"));
346 assert!(lines[2].contains("light.living_room"));
347 assert!(lines[3].contains("switch.fan"));
348 }
349
350 #[test]
351 fn print_error_json_mode_emits_envelope_to_stdout() {
352 let e = crate::api::HaError::NotFound("light.missing".into());
354 let envelope = serde_json::json!({
355 "ok": false,
356 "error": {
357 "code": e.error_code(),
358 "message": e.to_string()
359 }
360 });
361 assert_eq!(envelope["ok"], false);
362 assert_eq!(envelope["error"]["code"], "HA_NOT_FOUND");
363 assert!(
364 envelope["error"]["message"]
365 .as_str()
366 .unwrap()
367 .contains("light.missing")
368 );
369 }
370
371 #[test]
372 fn exit_code_for_auth_error_is_2() {
373 assert_eq!(
374 exit_codes::for_error(&crate::api::HaError::Auth("x".into())),
375 2
376 );
377 }
378
379 #[test]
380 fn exit_code_for_not_found_is_3() {
381 assert_eq!(
382 exit_codes::for_error(&crate::api::HaError::NotFound("x".into())),
383 3
384 );
385 }
386
387 #[test]
388 fn exit_code_for_connection_error_is_4() {
389 assert_eq!(
390 exit_codes::for_error(&crate::api::HaError::Connection("x".into())),
391 4
392 );
393 }
394}