1use std::fmt;
19
20pub use astrs_graph::Severity;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
24#[serde(rename_all = "snake_case")]
25pub enum Source {
26 Io,
28 Parse,
30 Structural,
33 Expand,
35 Graph,
38 Prove,
41}
42
43impl fmt::Display for Source {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 f.write_str(match self {
46 Self::Io => "io",
47 Self::Parse => "parse",
48 Self::Structural => "structural",
49 Self::Expand => "expand",
50 Self::Graph => "graph",
51 Self::Prove => "prove",
52 })
53 }
54}
55
56#[derive(Debug, Clone, serde::Serialize)]
58pub struct CliDiagnostic {
59 pub severity: Severity,
61 pub source: Source,
63 #[serde(skip_serializing_if = "Option::is_none")]
72 pub path: Option<String>,
73 pub message: String,
75}
76
77impl CliDiagnostic {
78 #[must_use]
80 pub fn io(message: impl Into<String>) -> Self {
81 Self {
82 severity: Severity::Error,
83 source: Source::Io,
84 path: None,
85 message: message.into(),
86 }
87 }
88
89 #[must_use]
91 pub fn parse(err: &astrs_manifest::ManifestError) -> Self {
92 let path = match (err.line(), err.column()) {
93 (Some(line), Some(column)) => Some(format!("line {line}, column {column}")),
94 _ => None,
95 };
96 Self {
97 severity: Severity::Error,
98 source: Source::Parse,
99 path,
100 message: err.to_string(),
101 }
102 }
103
104 #[must_use]
106 pub fn structural(err: &astrs_manifest::ValidationError) -> Self {
107 Self {
108 severity: Severity::Error,
109 source: Source::Structural,
110 path: Some(err.path.clone()),
111 message: err.kind.to_string(),
112 }
113 }
114
115 #[must_use]
117 pub fn expand(err: &astrs_manifest::expand::ExpandError) -> Self {
118 Self {
119 severity: Severity::Error,
120 source: Source::Expand,
121 path: None,
122 message: err.to_string(),
123 }
124 }
125
126 #[must_use]
136 pub fn graph_build_error(err: &astrs_graph::GraphBuildError) -> Self {
137 Self {
138 severity: Severity::Error,
139 source: Source::Graph,
140 path: None,
141 message: err.to_string(),
142 }
143 }
144
145 #[must_use]
148 pub fn graph(diag: &astrs_graph::Diagnostic) -> Self {
149 Self {
150 severity: diag.severity,
151 source: Source::Graph,
152 path: None,
153 message: diag.to_string(),
154 }
155 }
156
157 #[must_use]
164 pub fn prove_unavailable() -> Self {
165 Self {
166 severity: Severity::Warning,
167 source: Source::Prove,
168 path: None,
169 message: "--prove encoded every obligation but this build has no solver; \
170 rebuild with `--features verify` to discharge them"
171 .to_string(),
172 }
173 }
174
175 #[must_use]
177 pub fn prove_violation(heading: &str, headline: &str) -> Self {
178 Self {
179 severity: Severity::Error,
180 source: Source::Prove,
181 path: None,
182 message: format!("{heading}: {headline}"),
183 }
184 }
185
186 #[must_use]
195 pub fn prove_incomplete(missing_declaration: usize, inconclusive: usize) -> Self {
196 Self {
197 severity: Severity::Warning,
198 source: Source::Prove,
199 path: None,
200 message: format!(
201 "{missing_declaration} obligation(s) lack a declaration to decide them and \
202 {inconclusive} were left undecided; this proof rules out what it lists, and no more"
203 ),
204 }
205 }
206
207 #[must_use]
209 pub fn prove_error(message: impl Into<String>) -> Self {
210 Self {
211 severity: Severity::Error,
212 source: Source::Prove,
213 path: None,
214 message: message.into(),
215 }
216 }
217}
218
219#[must_use]
222pub fn max_severity(diagnostics: &[CliDiagnostic]) -> Option<Severity> {
223 diagnostics.iter().map(|d| d.severity).max()
224}
225
226#[must_use]
229pub fn exit_code_for(diagnostics: &[CliDiagnostic]) -> i32 {
230 match max_severity(diagnostics) {
231 None | Some(Severity::Info) => 0,
232 Some(Severity::Warning) => 1,
233 Some(Severity::Error) => 2,
234 }
235}
236
237const RED: &str = "\x1b[31m";
238const YELLOW: &str = "\x1b[33m";
239const CYAN: &str = "\x1b[36m";
240const BOLD: &str = "\x1b[1m";
241const RESET: &str = "\x1b[0m";
242
243fn severity_color(severity: Severity) -> &'static str {
244 match severity {
245 Severity::Error => RED,
246 Severity::Warning => YELLOW,
247 Severity::Info => CYAN,
248 }
249}
250
251#[must_use]
256pub fn render_line(diagnostic: &CliDiagnostic, use_color: bool) -> String {
257 let severity_str = diagnostic.severity.to_string();
258 let tag = if use_color {
259 format!(
260 "{BOLD}{}[{severity_str}]{RESET}",
261 severity_color(diagnostic.severity)
262 )
263 } else {
264 format!("[{severity_str}]")
265 };
266 let mut line = format!("{tag} ({}) ", diagnostic.source);
267 if let Some(path) = &diagnostic.path {
268 line.push_str(path);
269 line.push_str(": ");
270 }
271 line.push_str(&diagnostic.message);
272 line
273}
274
275#[must_use]
277pub fn render_human(diagnostics: &[CliDiagnostic], use_color: bool) -> String {
278 diagnostics
279 .iter()
280 .map(|d| render_line(d, use_color))
281 .collect::<Vec<_>>()
282 .join("\n")
283}
284
285#[cfg(test)]
286mod tests {
287 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
288 use super::*;
289
290 #[test]
291 fn max_severity_is_none_for_an_empty_list() {
292 assert_eq!(max_severity(&[]), None);
293 assert_eq!(exit_code_for(&[]), 0);
294 }
295
296 #[test]
297 fn exit_code_reflects_the_worst_severity() {
298 let info = vec![CliDiagnostic {
299 severity: Severity::Info,
300 source: Source::Graph,
301 path: None,
302 message: "m".to_string(),
303 }];
304 assert_eq!(exit_code_for(&info), 0);
305
306 let warning = vec![CliDiagnostic {
307 severity: Severity::Warning,
308 source: Source::Graph,
309 path: None,
310 message: "m".to_string(),
311 }];
312 assert_eq!(exit_code_for(&warning), 1);
313
314 let error = vec![CliDiagnostic {
315 severity: Severity::Error,
316 source: Source::Io,
317 path: None,
318 message: "m".to_string(),
319 }];
320 assert_eq!(exit_code_for(&error), 2);
321 }
322
323 #[test]
324 fn exit_code_takes_the_worst_across_a_mixed_list() {
325 let mixed = vec![
326 CliDiagnostic {
327 severity: Severity::Info,
328 source: Source::Graph,
329 path: None,
330 message: "info".to_string(),
331 },
332 CliDiagnostic {
333 severity: Severity::Warning,
334 source: Source::Graph,
335 path: None,
336 message: "warning".to_string(),
337 },
338 ];
339 assert_eq!(exit_code_for(&mixed), 1);
340 }
341
342 #[test]
343 fn render_line_without_color_has_no_escape_codes() {
344 let d = CliDiagnostic::io("cannot read file");
345 let line = render_line(&d, false);
346 assert!(!line.contains('\x1b'));
347 assert!(line.contains("[error]"));
348 assert!(line.contains("(io)"));
349 assert!(line.contains("cannot read file"));
350 }
351
352 #[test]
353 fn render_line_with_color_wraps_the_severity_tag() {
354 let d = CliDiagnostic::io("cannot read file");
355 let line = render_line(&d, true);
356 assert!(line.contains('\x1b'));
357 assert!(line.contains(RESET));
358 }
359
360 #[test]
361 fn render_line_includes_path_when_present() {
362 let d = CliDiagnostic {
363 severity: Severity::Error,
364 source: Source::Structural,
365 path: Some("nodes[2].id".to_string()),
366 message: "bad".to_string(),
367 };
368 let line = render_line(&d, false);
369 assert!(line.contains("nodes[2].id: bad"));
370 }
371
372 #[test]
373 fn structural_diagnostic_carries_the_validation_error_path() {
374 let err = astrs_manifest::ValidationError {
375 path: "nodes[0].id".to_string(),
376 kind: astrs_manifest::ValidationErrorKind::InvalidIdCharset {
377 id: "bad id".to_string(),
378 },
379 };
380 let d = CliDiagnostic::structural(&err);
381 assert_eq!(d.path.as_deref(), Some("nodes[0].id"));
382 assert_eq!(d.severity, Severity::Error);
383 }
384
385 #[test]
386 fn parse_diagnostic_captures_line_and_column_when_available() {
387 let err = astrs_manifest::Manifest::from_yaml_str("nodes: [").unwrap_err();
388 let d = CliDiagnostic::parse(&err);
389 assert!(d.path.is_some(), "path was: {:?}", d.path);
390 }
391
392 #[test]
393 fn graph_diagnostic_preserves_its_severity() {
394 let diag = astrs_graph::Diagnostic::new(
395 Severity::Warning,
396 astrs_graph::DiagnosticKind::UnconsumedOutput {
397 node: astrs_graph::NodeId::new("camera"),
398 output: astrs_graph::PortName::new("frames"),
399 },
400 );
401 let d = CliDiagnostic::graph(&diag);
402 assert_eq!(d.severity, Severity::Warning);
403 assert!(d.message.contains("camera"));
404 }
405
406 #[test]
407 fn prove_unavailable_points_at_the_rebuild() {
408 let d = CliDiagnostic::prove_unavailable();
409 assert_eq!(d.severity, Severity::Warning);
410 assert_eq!(d.source, Source::Prove);
411 assert!(d.message.contains("--features verify"), "{}", d.message);
412 }
413
414 #[test]
415 fn prove_violation_is_an_error_naming_both_halves() {
416 let d = CliDiagnostic::prove_violation("deadlock freedom", "`a` can never fire");
417 assert_eq!(d.severity, Severity::Error);
418 assert_eq!(d.source, Source::Prove);
419 assert!(d.message.contains("deadlock freedom"));
420 assert!(d.message.contains("can never fire"));
421 }
422
423 #[test]
424 fn prove_incomplete_is_a_warning_counting_both_gaps() {
425 let d = CliDiagnostic::prove_incomplete(2, 1);
426 assert_eq!(d.severity, Severity::Warning);
427 assert!(d.message.contains('2') && d.message.contains('1'));
428 }
429
430 #[test]
431 fn prove_error_is_an_error() {
432 let d = CliDiagnostic::prove_error("profile is inconsistent");
433 assert_eq!(d.severity, Severity::Error);
434 assert_eq!(d.source, Source::Prove);
435 }
436
437 #[test]
438 fn json_serialization_omits_absent_path() {
439 let d = CliDiagnostic::io("nope");
440 let json = serde_json::to_string(&d).unwrap();
441 assert!(!json.contains("\"path\""));
442 assert!(json.contains("\"severity\":\"error\""));
443 }
444
445 #[test]
446 fn json_serialization_includes_present_path() {
447 let d = CliDiagnostic {
448 severity: Severity::Error,
449 source: Source::Structural,
450 path: Some("nodes[0]".to_string()),
451 message: "m".to_string(),
452 };
453 let json = serde_json::to_string(&d).unwrap();
454 assert!(json.contains("\"path\":\"nodes[0]\""));
455 }
456}