1use std::fmt;
5
6#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct ZxError {
9 message: String,
10}
11
12impl ZxError {
13 pub fn new(message: impl Into<String>) -> Self {
15 Self {
16 message: message.into(),
17 }
18 }
19
20 pub fn message(&self) -> &str {
22 &self.message
23 }
24}
25
26impl fmt::Display for ZxError {
27 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28 f.write_str(&self.message)
29 }
30}
31
32impl std::error::Error for ZxError {}
33
34impl From<std::io::Error> for ZxError {
35 fn from(err: std::io::Error) -> Self {
36 ZxError::new(err.to_string())
37 }
38}
39
40pub const DOCS_URL: &str = "https://google.github.io/zx";
42
43pub const EXIT_CODES: &[(i32, &str)] = &[
45 (2, "Misuse of shell builtins"),
46 (126, "Invoked command cannot execute"),
47 (127, "Command not found"),
48 (128, "Invalid exit argument"),
49 (129, "Hangup"),
50 (130, "Interrupt"),
51 (131, "Quit and dump core"),
52 (132, "Illegal instruction"),
53 (133, "Trace/breakpoint trap"),
54 (134, "Process aborted"),
55 (
56 135,
57 "Bus error: \"access to undefined portion of memory object\"",
58 ),
59 (
60 136,
61 "Floating point exception: \"erroneous arithmetic operation\"",
62 ),
63 (137, "Kill (terminate immediately)"),
64 (138, "User-defined 1"),
65 (139, "Segmentation violation"),
66 (140, "User-defined 2"),
67 (141, "Write to pipe with no one reading"),
68 (142, "Signal raised by alarm"),
69 (143, "Termination (request to terminate)"),
70 (145, "Child process terminated, stopped (or continued*)"),
71 (146, "Continue if stopped"),
72 (147, "Stop executing temporarily"),
73 (148, "Terminal stop signal"),
74 (
75 149,
76 "Background process attempting to read from tty (\"in\")",
77 ),
78 (
79 150,
80 "Background process attempting to write to tty (\"out\")",
81 ),
82 (151, "Urgent data available on socket"),
83 (152, "CPU time limit exceeded"),
84 (153, "File size limit exceeded"),
85 (
86 154,
87 "Signal raised by timer counting virtual time: \"virtual timer expired\"",
88 ),
89 (155, "Profiling timer expired"),
90 (157, "Pollable event"),
91 (159, "Bad syscall"),
92];
93
94pub const ERRNO_CODES: &[(i64, &str)] = &[
96 (0, "Success"),
97 (1, "Not super-user"),
98 (2, "No such file or directory"),
99 (3, "No such process"),
100 (4, "Interrupted system call"),
101 (5, "I/O error"),
102 (6, "No such device or address"),
103 (7, "Arg list too long"),
104 (8, "Exec format error"),
105 (9, "Bad file number"),
106 (10, "No children"),
107 (11, "No more processes"),
108 (12, "Not enough core"),
109 (13, "Permission denied"),
110 (14, "Bad address"),
111 (15, "Block device required"),
112 (16, "Mount device busy"),
113 (17, "File exists"),
114 (18, "Cross-device link"),
115 (19, "No such device"),
116 (20, "Not a directory"),
117 (21, "Is a directory"),
118 (22, "Invalid argument"),
119 (23, "Too many open files in system"),
120 (24, "Too many open files"),
121 (25, "Not a typewriter"),
122 (26, "Text file busy"),
123 (27, "File too large"),
124 (28, "No space left on device"),
125 (29, "Illegal seek"),
126 (30, "Read only file system"),
127 (31, "Too many links"),
128 (32, "Broken pipe"),
129 (33, "Math arg out of domain of func"),
130 (34, "Math result not representable"),
131 (35, "File locking deadlock error"),
132 (36, "File or path name too long"),
133 (37, "No record locks available"),
134 (38, "Function not implemented"),
135 (39, "Directory not empty"),
136 (40, "Too many symbolic links"),
137 (42, "No message of desired type"),
138 (43, "Identifier removed"),
139 (44, "Channel number out of range"),
140 (45, "Level 2 not synchronized"),
141 (46, "Level 3 halted"),
142 (47, "Level 3 reset"),
143 (48, "Link number out of range"),
144 (49, "Protocol driver not attached"),
145 (50, "No CSI structure available"),
146 (51, "Level 2 halted"),
147 (52, "Invalid exchange"),
148 (53, "Invalid request descriptor"),
149 (54, "Exchange full"),
150 (55, "No anode"),
151 (56, "Invalid request code"),
152 (57, "Invalid slot"),
153 (59, "Bad font file fmt"),
154 (60, "Device not a stream"),
155 (61, "No data (for no delay io)"),
156 (62, "Timer expired"),
157 (63, "Out of streams resources"),
158 (64, "Machine is not on the network"),
159 (65, "Package not installed"),
160 (66, "The object is remote"),
161 (67, "The link has been severed"),
162 (68, "Advertise error"),
163 (69, "Srmount error"),
164 (70, "Communication error on send"),
165 (71, "Protocol error"),
166 (72, "Multihop attempted"),
167 (73, "Cross mount point (not really error)"),
168 (74, "Trying to read unreadable message"),
169 (75, "Value too large for defined data type"),
170 (76, "Given log. name not unique"),
171 (77, "f.d. invalid for this operation"),
172 (78, "Remote address changed"),
173 (79, "Can access a needed shared lib"),
174 (80, "Accessing a corrupted shared lib"),
175 (81, ".lib section in a.out corrupted"),
176 (82, "Attempting to link in too many libs"),
177 (83, "Attempting to exec a shared library"),
178 (84, "Illegal byte sequence"),
179 (86, "Streams pipe error"),
180 (87, "Too many users"),
181 (88, "Socket operation on non-socket"),
182 (89, "Destination address required"),
183 (90, "Message too long"),
184 (91, "Protocol wrong type for socket"),
185 (92, "Protocol not available"),
186 (93, "Unknown protocol"),
187 (94, "Socket type not supported"),
188 (95, "Not supported"),
189 (96, "Protocol family not supported"),
190 (97, "Address family not supported by protocol family"),
191 (98, "Address already in use"),
192 (99, "Address not available"),
193 (100, "Network interface is not configured"),
194 (101, "Network is unreachable"),
195 (102, "Connection reset by network"),
196 (103, "Connection aborted"),
197 (104, "Connection reset by peer"),
198 (105, "No buffer space available"),
199 (106, "Socket is already connected"),
200 (107, "Socket is not connected"),
201 (108, "Can't send after socket shutdown"),
202 (109, "Too many references"),
203 (110, "Connection timed out"),
204 (111, "Connection refused"),
205 (112, "Host is down"),
206 (113, "Host is unreachable"),
207 (114, "Socket already connected"),
208 (115, "Connection already in progress"),
209 (116, "Stale file handle"),
210 (122, "Quota exceeded"),
211 (123, "No medium (in tape drive)"),
212 (125, "Operation canceled"),
213 (130, "Previous owner died"),
214 (131, "State not recoverable"),
215];
216
217pub fn exit_code_info(code: i32) -> Option<&'static str> {
219 EXIT_CODES
220 .iter()
221 .find(|(c, _)| *c == code)
222 .map(|(_, text)| *text)
223}
224
225pub fn errno_message(errno: Option<i64>) -> &'static str {
229 errno
230 .and_then(|e| e.checked_neg())
231 .and_then(|e| ERRNO_CODES.iter().find(|(c, _)| *c == e))
232 .map(|(_, text)| *text)
233 .unwrap_or("Unknown error")
234}
235
236fn or_null<T: fmt::Display>(value: Option<T>) -> String {
237 value.map_or_else(|| "null".to_string(), |v| v.to_string())
238}
239
240pub fn format_exit_message(
244 code: Option<i32>,
245 signal: Option<&str>,
246 stderr: &str,
247 from: &str,
248 details: &str,
249) -> String {
250 if code == Some(0) && signal.is_none() {
251 return "exit code: 0".to_string();
252 }
253 let mut message = format!("{stderr}\n at {from}\n exit code: {}", or_null(code));
254 if let Some(info) = code.and_then(exit_code_info) {
255 message.push_str(&format!(" ({info})"));
256 }
257 if let Some(signal) = signal {
258 message.push_str(&format!("\n signal: {signal}"));
259 }
260 if !details.is_empty() {
261 message.push_str(&format!("\n details: \n{details}"));
262 }
263 message
264}
265
266pub fn format_error_message(
269 message: &str,
270 errno: Option<i64>,
271 code: Option<&str>,
272 from: &str,
273) -> String {
274 let errno_text = errno.map_or_else(|| "undefined".to_string(), |e| e.to_string());
275 [
276 message.to_string(),
277 format!(" errno: {errno_text} ({})", errno_message(errno)),
278 format!(" code: {}", code.unwrap_or("undefined")),
279 format!(" at {from}"),
280 ]
281 .join("\n")
282}
283
284fn is_error_line(line: &str) -> bool {
285 let lower = line.to_lowercase();
286 ["fail", "error", "not ok", "exception"]
287 .iter()
288 .any(|needle| lower.contains(needle))
289}
290
291pub fn format_error_details<S: AsRef<str>>(lines: &[S], limit: usize) -> String {
297 let all: Vec<&str> = lines.iter().map(|l| l.as_ref()).collect();
298 if all.len() < limit {
299 return all.join("\n");
300 }
301 let mut selected: Vec<&str> = all.iter().copied().filter(|l| is_error_line(l)).collect();
302 if selected.is_empty() {
303 selected = all;
304 }
305 let more = if selected.len() > limit { "\n..." } else { "" };
306 selected.truncate(limit);
307 format!("{}{more}", selected.join("\n"))
308}
309
310pub const ERROR_DETAILS_LIMIT: usize = 20;