1use serde::Serialize;
4use std::io::Write;
5
6const FALLBACK_TERMINAL_WIDTH: usize = 120;
7
8pub fn terminal_width() -> usize {
10 if let Some(width) = terminal_width_from_env() {
11 return width;
12 }
13 terminal_width_from_stdout().unwrap_or(FALLBACK_TERMINAL_WIDTH)
14}
15
16fn terminal_width_from_env() -> Option<usize> {
17 std::env::var("COLUMNS")
18 .ok()
19 .and_then(|s| s.parse::<usize>().ok())
20 .filter(|w| *w > 0)
21}
22
23#[cfg(unix)]
24fn terminal_width_from_stdout() -> Option<usize> {
25 let mut size = libc::winsize {
26 ws_row: 0,
27 ws_col: 0,
28 ws_xpixel: 0,
29 ws_ypixel: 0,
30 };
31 let rc = unsafe { libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &mut size) };
32 if rc == 0 && size.ws_col > 0 {
33 Some(size.ws_col as usize)
34 } else {
35 None
36 }
37}
38
39#[cfg(not(unix))]
40fn terminal_width_from_stdout() -> Option<usize> {
41 None
42}
43
44pub fn print_table<W: Write>(
50 out: &mut W,
51 headers: &[&str],
52 rows: &[Vec<String>],
53) -> std::io::Result<()> {
54 let ncols = headers.len();
55 let mut widths: Vec<usize> = headers.iter().map(|h| h.len()).collect();
56 for row in rows {
57 for (i, cell) in row.iter().enumerate().take(ncols) {
58 if cell.len() > widths[i] {
59 widths[i] = cell.len();
60 }
61 }
62 }
63
64 write_row(out, headers.iter().copied(), &widths)?;
65 let sep: Vec<String> = widths.iter().map(|w| "-".repeat(*w)).collect();
66 write_row(out, sep.iter().map(|s| s.as_str()), &widths)?;
67 for row in rows {
68 write_row(
69 out,
70 (0..ncols).map(|i| row.get(i).map(|s| s.as_str()).unwrap_or("")),
71 &widths,
72 )?;
73 }
74 Ok(())
75}
76
77fn write_row<'a, W: Write, I: Iterator<Item = &'a str>>(
78 out: &mut W,
79 cells: I,
80 widths: &[usize],
81) -> std::io::Result<()> {
82 let cells: Vec<&str> = cells.collect();
83 let last = cells.len().saturating_sub(1);
84 for (i, cell) in cells.iter().enumerate() {
85 if i == last {
86 write!(out, "{}", cell)?;
88 } else {
89 write!(out, "{:<width$} ", cell, width = widths[i])?;
90 }
91 }
92 writeln!(out)
93}
94
95pub fn write_private_file(path: &std::path::Path, bytes: &[u8]) -> anyhow::Result<()> {
99 use anyhow::Context as _;
100 std::fs::write(path, bytes).with_context(|| format!("failed to write {}", path.display()))?;
101 #[cfg(unix)]
102 {
103 use std::os::unix::fs::PermissionsExt;
104 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
105 .with_context(|| format!("failed to chmod 600 {}", path.display()))?;
106 }
107 Ok(())
108}
109
110pub fn image_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
113 if bytes.len() >= 24 && bytes.starts_with(b"\x89PNG\r\n\x1a\n") && &bytes[12..16] == b"IHDR" {
115 let w = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);
116 let h = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]);
117 return Some((w, h));
118 }
119 if bytes.len() >= 4 && bytes[0] == 0xFF && bytes[1] == 0xD8 {
121 let mut i = 2;
122 while i + 9 < bytes.len() {
123 if bytes[i] != 0xFF {
124 i += 1;
125 continue;
126 }
127 let marker = bytes[i + 1];
128 if marker == 0xFF {
129 i += 1;
130 continue;
131 }
132 let is_sof = (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC);
133 if is_sof {
134 let h = u16::from_be_bytes([bytes[i + 5], bytes[i + 6]]) as u32;
135 let w = u16::from_be_bytes([bytes[i + 7], bytes[i + 8]]) as u32;
136 return Some((w, h));
137 }
138 let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize;
139 i += 2 + len;
140 }
141 }
142 None
143}
144
145pub fn print_json<W: Write, T: Serialize>(out: &mut W, value: &T) -> anyhow::Result<()> {
147 let s = serde_json::to_string_pretty(value)?;
148 out.write_all(s.as_bytes())?;
149 out.write_all(b"\n")?;
150 Ok(())
151}
152
153#[cfg(test)]
154mod tests {
155 use super::*;
156
157 #[test]
158 fn empty_rows_produces_headers_and_separator() {
159 let mut buf: Vec<u8> = Vec::new();
160 print_table(&mut buf, &["A", "BB"], &[]).unwrap();
161 let s = String::from_utf8(buf).unwrap();
162 let lines: Vec<&str> = s.lines().collect();
163 assert_eq!(lines.len(), 2, "got: {:?}", lines);
164 assert!(lines[0].starts_with("A "));
165 assert!(lines[0].contains("BB"));
166 assert!(lines[1].starts_with("-"));
167 assert!(lines[1].contains("--"));
168 }
169
170 #[test]
171 fn column_widths_grow_to_longest_cell() {
172 let mut buf: Vec<u8> = Vec::new();
173 let rows = vec![
174 vec!["short".to_string(), "x".to_string()],
175 vec!["a-very-long-cell".to_string(), "y".to_string()],
176 ];
177 print_table(&mut buf, &["K", "V"], &rows).unwrap();
178 let s = String::from_utf8(buf).unwrap();
179 let lines: Vec<&str> = s.lines().collect();
180 assert!(
183 lines[0].starts_with("K "),
184 "header pad wrong: {:?}",
185 lines[0]
186 );
187 assert!(
189 lines[1].starts_with(&"-".repeat(16)),
190 "sep wrong: {:?}",
191 lines[1]
192 );
193 assert!(lines[2].starts_with("short "));
195 assert!(lines[3].starts_with("a-very-long-cell y"));
196 }
197
198 #[test]
199 fn image_dimensions_parse_png_and_jpeg_headers() {
200 let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
201 png.extend_from_slice(&[0, 0, 0, 13]);
202 png.extend_from_slice(b"IHDR");
203 png.extend_from_slice(&1280u32.to_be_bytes());
204 png.extend_from_slice(&720u32.to_be_bytes());
205 assert_eq!(image_dimensions(&png), Some((1280, 720)));
206
207 let mut jpg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00];
209 jpg.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0x32, 0x00, 0x64, 0x03]);
210 assert_eq!(image_dimensions(&jpg), Some((100, 50)));
211
212 assert_eq!(image_dimensions(b"nope"), None);
213 }
214
215 #[test]
216 fn json_output_is_valid_json() {
217 #[derive(Serialize)]
218 struct X {
219 a: u32,
220 b: Vec<String>,
221 }
222 let mut buf: Vec<u8> = Vec::new();
223 let x = X {
224 a: 7,
225 b: vec!["hi".into(), "there".into()],
226 };
227 print_json(&mut buf, &x).unwrap();
228 let s = String::from_utf8(buf).unwrap();
229 let v: serde_json::Value = serde_json::from_str(&s).unwrap();
230 assert_eq!(v["a"], 7);
231 assert_eq!(v["b"][1], "there");
232 }
233}