argenv_resolve/problems.rs
1//! Problem-handling policy: what to do when `lint` finds something.
2//!
3//! Rather than hand-rolling a loop every project, declare your policy once and
4//! pass it to [`handle_problems`] or [`Model::parse_and_lint`]:
5//!
6//! ```no_run
7//! # use argenv_resolve::*;
8//! # let model: Vec<Record> = vec![];
9//! # let resolved = argenv_resolve::parse(&model);
10//! let findings = lint(&model, &resolved);
11//! handle_problems(&findings, OnProblems::FailOnError);
12//! ```
13
14use crate::{Finding, Severity};
15
16/// What to do when [`crate::lint`] returns findings.
17///
18/// Pass to [`handle_problems`] or, more commonly, let [`crate::contract!`]'s
19/// generated `Model::parse_and_lint` handle both steps at once.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum OnProblems {
22 /// Print errors and warnings to stderr; exit with status 1 on any error.
23 /// Warnings alone are printed but do not stop the program.
24 ///
25 /// This is the right default for most programs: a misspelled flag is
26 /// an error (the intent is clear but wrong), an unknown env var is a
27 /// warning (it might just be a coincidence).
28 FailOnError,
29
30 /// Print all findings to stderr; exit with status 1 if there is anything
31 /// at all — errors or warnings.
32 ///
33 /// Use this when warnings are unacceptable: a strict tool, a CI step,
34 /// or a program where an unrecognised env var is never a coincidence.
35 FailOnAny,
36
37 /// Print all findings to stderr; never exit because of them.
38 ///
39 /// Use this for programs that want to surface problems without stopping,
40 /// or for a startup phase where the caller handles the exit itself.
41 WarnOnly,
42
43 /// Discard all findings silently.
44 ///
45 /// Use this only when you have already handled findings yourself, or
46 /// when the program genuinely cannot do anything useful with them.
47 Ignore,
48}
49
50/// Apply a problem-handling policy to a set of findings.
51///
52/// Prints findings to stderr and exits the process if the policy requires it.
53/// Returns normally when the policy allows the program to continue.
54///
55/// ```no_run
56/// # use argenv_resolve::*;
57/// # let model: Vec<Record> = vec![];
58/// # let resolved = argenv_resolve::parse(&model);
59/// handle_problems(&lint(&model, &resolved), OnProblems::FailOnError);
60/// ```
61pub fn handle_problems(findings: &[Finding], policy: OnProblems) {
62 if findings.is_empty() || policy == OnProblems::Ignore {
63 return;
64 }
65
66 for f in findings {
67 let label = match f.severity() {
68 Severity::Error => "error",
69 Severity::Warning => "warning",
70 };
71 eprintln!("{label}: {f}");
72 }
73
74 let should_exit = match policy {
75 OnProblems::FailOnError => findings.iter().any(|f| f.severity() == Severity::Error),
76 OnProblems::FailOnAny => !findings.is_empty(),
77 OnProblems::WarnOnly | OnProblems::Ignore => false,
78 };
79
80 if should_exit {
81 std::process::exit(1);
82 }
83}