1use std::fmt::{Display, Formatter, Result as FmtResult};
8use std::sync::Arc;
9
10use oxdock_diagnostics::Diagnostic;
11use oxdock_parser::KEYWORD_EXIT;
12
13#[derive(Debug, Clone)]
22pub struct ExitRequest {
23 code: i64,
24 source: Option<Arc<dyn std::error::Error + Send + Sync>>,
25}
26
27impl ExitRequest {
28 pub fn new(code: i64) -> Self {
30 Self { code, source: None }
31 }
32
33 pub fn with_source(code: i64, source: Arc<dyn std::error::Error + Send + Sync>) -> Self {
37 Self {
38 code,
39 source: Some(source),
40 }
41 }
42
43 pub fn code(&self) -> i64 {
45 self.code
46 }
47}
48
49impl PartialEq for ExitRequest {
50 fn eq(&self, other: &Self) -> bool {
51 self.code == other.code
52 }
53}
54
55impl Eq for ExitRequest {}
56
57impl Display for ExitRequest {
58 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
59 write!(f, "{KEYWORD_EXIT} requested with code {}", self.code)
60 }
61}
62
63impl std::error::Error for ExitRequest {
64 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
65 self.source
66 .as_deref()
67 .map(|cause| cause as &(dyn std::error::Error + 'static))
68 }
69}
70
71pub fn exit_code_of(err: &anyhow::Error) -> Option<i64> {
77 err.chain().find_map(|cause| {
78 if let Some(exit) = cause.downcast_ref::<ExitRequest>() {
79 return Some(exit.code());
80 }
81 if let Some(diag) = cause.downcast_ref::<Diagnostic>() {
82 return super::diagnostics::eval_exit_requested_code(diag);
83 }
84 None
85 })
86}
87
88pub fn exit_code_of_diag(err: &Diagnostic) -> Option<i64> {
95 let mut current: Option<&(dyn std::error::Error + 'static)> =
96 Some(err as &(dyn std::error::Error + 'static));
97 while let Some(node) = current {
98 if let Some(exit) = node.downcast_ref::<ExitRequest>() {
99 return Some(exit.code());
100 }
101 if let Some(diag) = node.downcast_ref::<Diagnostic>()
102 && let Some(code) = super::diagnostics::eval_exit_requested_code(diag)
103 {
104 return Some(code);
105 }
106 current = node.source();
107 }
108 None
109}
110
111pub fn exit_status_code(status: &std::process::ExitStatus) -> Option<i32> {
116 status.code()
117}
118
119pub fn describe_exit_status(status: &std::process::ExitStatus) -> String {
124 match exit_status_code(status) {
125 Some(code) => code.to_string(),
126 None => status.to_string(),
127 }
128}
129
130#[cfg(test)]
131mod tests {
132 use super::{ExitRequest, exit_code_of, exit_code_of_diag};
133 use oxdock_diagnostics::Diagnostic;
134 use std::sync::Arc;
135
136 #[test]
137 fn display_matches_historic_message() {
138 assert_eq!(
139 ExitRequest::new(3).to_string(),
140 "EXIT requested with code 3"
141 );
142 }
143
144 #[test]
145 fn finds_code_through_context_wrappers() {
146 let err = anyhow::Error::new(ExitRequest::new(3)).context("REMOTE 'prod' failed");
147 assert_eq!(exit_code_of(&err), Some(3));
148 }
149
150 #[test]
151 fn none_without_exit() {
152 let err = anyhow::anyhow!("boom").context("wrapped");
153 assert_eq!(exit_code_of(&err), None);
154 }
155
156 #[test]
157 fn diag_finds_code_through_source_chain() {
158 let inner = Diagnostic::new(
159 "dsl.eval.async_cancelled",
160 "ASYNC task cancelled".to_string(),
161 Diagnostic::make_fields(&[]),
162 )
163 .with_source(Arc::new(ExitRequest::new(7)));
164 assert_eq!(exit_code_of_diag(&inner), Some(7));
165 }
166
167 #[test]
168 fn chained_exit_keeps_code_and_prior_cause() {
169 use std::error::Error as _;
170 let cause = Arc::new(std::io::Error::new(std::io::ErrorKind::NotFound, "gone"));
171 let exit = ExitRequest::with_source(7, cause);
172 assert_eq!(exit.code(), 7);
173 let prior = exit
174 .source()
175 .expect("prior cause rides behind the request")
176 .downcast_ref::<std::io::Error>()
177 .expect("prior cause keeps its type");
178 assert_eq!(prior.kind(), std::io::ErrorKind::NotFound);
179 let diag = Diagnostic::new(
180 "dsl.eval.async_cancelled",
181 "ASYNC task cancelled".to_string(),
182 Diagnostic::make_fields(&[]),
183 )
184 .with_source(Arc::new(exit));
185 assert_eq!(exit_code_of_diag(&diag), Some(7));
186 assert!(
187 diag.source()
188 .and_then(|cause| cause.downcast_ref::<ExitRequest>())
189 .is_some()
190 );
191 let carried = exit_code_of(&anyhow::Error::new(diag));
192 assert_eq!(carried, Some(7));
193 assert_eq!(
194 ExitRequest::new(7),
195 ExitRequest::with_source(
196 7,
197 Arc::new(std::io::Error::new(std::io::ErrorKind::NotFound, "gone"))
198 )
199 );
200 }
201
202 #[test]
203 fn diag_none_without_exit() {
204 let diag = Diagnostic::new(
205 "dsl.eval.async_cancelled",
206 "ASYNC task cancelled".to_string(),
207 Diagnostic::make_fields(&[]),
208 );
209 assert_eq!(exit_code_of_diag(&diag), None);
210 }
211
212 #[test]
213 fn keyed_exit_requested_carries_code_without_source() {
214 use std::error::Error as _;
215 let diag = crate::exec::diagnostics::eval_exit_requested(7);
216 assert_eq!(diag.key(), "dsl.eval.exit_requested");
217 assert_eq!(diag.message(), "EXIT requested with code 7");
218 assert_eq!(diag.fields().get("code"), Some(&"7".to_string()));
219 assert!(
220 diag.source().is_none(),
221 "no identical source to duplicate rendering"
222 );
223 assert_eq!(exit_code_of_diag(&diag), Some(7));
224 let carried = exit_code_of(&anyhow::Error::new(diag).context("step 2"));
225 assert_eq!(carried, Some(7));
226 }
227
228 #[test]
229 fn describe_prefers_numeric_code() {
230 let status = oxdock_sys_test_utils::exit_status_from_code(3);
231 assert_eq!(super::describe_exit_status(&status), "3");
232 assert_eq!(super::exit_status_code(&status), Some(3));
233 }
234}