Skip to main content

visdom_cli/
fixes.rs

1//! Deciding which fixes to apply, and applying them.
2
3use crate::finding::{Finding, Fix, FixAction};
4
5/// Whether offered fixes are applied.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum FixPolicy {
8    /// Nothing is changed and nobody is asked.
9    Never,
10    /// Each fix is shown and applied on a yes.
11    Ask,
12    /// Every fix is applied.
13    All,
14}
15
16/// The policy for one run. `doctor` changes nothing unless `--fix` is given;
17/// `--yes` applies everything; without a terminal on stdin there is nobody to
18/// ask, so nothing is applied.
19pub fn policy_for(fix_flag: bool, yes: bool, is_doctor: bool, stdin_is_tty: bool) -> FixPolicy {
20    if is_doctor && !fix_flag {
21        FixPolicy::Never
22    } else if yes {
23        FixPolicy::All
24    } else if !stdin_is_tty {
25        FixPolicy::Never
26    } else {
27        FixPolicy::Ask
28    }
29}
30
31/// Carries out a [`FixAction`].
32pub trait FixExecutor {
33    fn execute(&mut self, action: &FixAction) -> Result<(), String>;
34}
35
36/// What happened to one finding's fix.
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct FixOutcome {
39    pub id: &'static str,
40    pub applied: bool,
41    pub error: Option<String>,
42}
43
44/// Offer every finding's fix under `policy`. An action identical to one
45/// already handled in this run (several findings can share one fix) is neither
46/// asked about nor executed again: the later finding gets the same outcome.
47pub fn apply_fixes(
48    findings: &[Finding],
49    policy: FixPolicy,
50    ask: &mut dyn FnMut(&Fix) -> bool,
51    exec: &mut dyn FixExecutor,
52) -> Vec<FixOutcome> {
53    let mut outcomes = Vec::new();
54    if policy == FixPolicy::Never {
55        return outcomes;
56    }
57    // Every distinct action handled so far, with how it went.
58    let mut handled: Vec<(&FixAction, bool, Option<String>)> = Vec::new();
59    for finding in findings {
60        let Some(fix) = &finding.fix else { continue };
61        let (applied, error) = match handled.iter().find(|(action, ..)| *action == &fix.action) {
62            Some((_, applied, error)) => (*applied, error.clone()),
63            None => {
64                let result = if policy == FixPolicy::Ask && !ask(fix) {
65                    (false, None)
66                } else {
67                    match exec.execute(&fix.action) {
68                        Ok(()) => (true, None),
69                        Err(e) => (false, Some(e)),
70                    }
71                };
72                handled.push((&fix.action, result.0, result.1.clone()));
73                result
74            }
75        };
76        outcomes.push(FixOutcome {
77            id: finding.id,
78            applied,
79            error,
80        });
81    }
82    outcomes
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88    use crate::finding::Severity;
89
90    #[derive(Default)]
91    struct Recorder {
92        calls: Vec<FixAction>,
93        fail: bool,
94    }
95
96    impl FixExecutor for Recorder {
97        fn execute(&mut self, action: &FixAction) -> Result<(), String> {
98            self.calls.push(action.clone());
99            if self.fail {
100                Err("boom".to_string())
101            } else {
102                Ok(())
103            }
104        }
105    }
106
107    fn action(name: &str) -> FixAction {
108        FixAction::RunCommand {
109            program: name.to_string(),
110            args: vec![],
111            cwd: None,
112        }
113    }
114
115    fn finding(id: &'static str, action: FixAction) -> Finding {
116        Finding::new("tracing", id, Severity::Error, "broken").with_fix(Fix {
117            description: "do it".to_string(),
118            action,
119        })
120    }
121
122    #[test]
123    fn policy_table() {
124        use FixPolicy::*;
125        for fix in [false, true] {
126            for yes in [false, true] {
127                for doctor in [false, true] {
128                    for tty in [false, true] {
129                        let expected = if doctor && !fix {
130                            Never
131                        } else if yes {
132                            All
133                        } else if tty {
134                            Ask
135                        } else {
136                            Never
137                        };
138                        assert_eq!(
139                            policy_for(fix, yes, doctor, tty),
140                            expected,
141                            "fix={fix} yes={yes} doctor={doctor} tty={tty}"
142                        );
143                    }
144                }
145            }
146        }
147        // The cases that matter most, spelled out.
148        assert_eq!(policy_for(false, true, true, true), Never); // doctor --yes
149        assert_eq!(policy_for(true, false, true, false), Never); // doctor --fix, piped
150        assert_eq!(policy_for(false, false, false, true), Ask); // visdom, terminal
151        assert_eq!(policy_for(false, true, false, false), All); // visdom --yes, piped
152    }
153
154    #[test]
155    fn same_action_applied_once() {
156        let findings = [
157            finding("a", action("init")),
158            finding("b", action("init")),
159            finding("c", action("other")),
160        ];
161        let mut exec = Recorder::default();
162        let mut asked = 0;
163        let outcomes = apply_fixes(
164            &findings,
165            FixPolicy::Ask,
166            &mut |_| {
167                asked += 1;
168                true
169            },
170            &mut exec,
171        );
172        assert_eq!(exec.calls, [action("init"), action("other")]);
173        assert_eq!(asked, 2);
174        assert!(outcomes.iter().all(|o| o.applied && o.error.is_none()));
175        assert_eq!(outcomes.len(), 3);
176    }
177
178    #[test]
179    fn non_tty_without_yes_never_applies() {
180        let policy = policy_for(false, false, false, false);
181        assert_eq!(policy, FixPolicy::Never);
182        let mut exec = Recorder::default();
183        let outcomes = apply_fixes(
184            &[finding("a", action("init"))],
185            policy,
186            &mut |_| panic!("nobody to ask"),
187            &mut exec,
188        );
189        assert!(exec.calls.is_empty());
190        assert!(outcomes.is_empty());
191    }
192
193    #[test]
194    fn ask_declined_is_not_applied() {
195        let findings = [finding("a", action("init")), finding("b", action("init"))];
196        let mut exec = Recorder::default();
197        let mut asked = 0;
198        let outcomes = apply_fixes(
199            &findings,
200            FixPolicy::Ask,
201            &mut |_| {
202                asked += 1;
203                false
204            },
205            &mut exec,
206        );
207        assert!(exec.calls.is_empty());
208        assert_eq!(asked, 1, "a declined fix is not offered twice");
209        assert!(outcomes.iter().all(|o| !o.applied && o.error.is_none()));
210    }
211
212    #[test]
213    fn all_applies_without_asking() {
214        let mut exec = Recorder::default();
215        let outcomes = apply_fixes(
216            &[finding("a", action("init"))],
217            FixPolicy::All,
218            &mut |_| panic!("--yes must not ask"),
219            &mut exec,
220        );
221        assert_eq!(exec.calls.len(), 1);
222        assert!(outcomes[0].applied);
223    }
224
225    #[test]
226    fn executor_error_is_reported_not_panicked() {
227        let mut exec = Recorder {
228            fail: true,
229            ..Default::default()
230        };
231        let outcomes = apply_fixes(
232            &[finding("a", action("init")), finding("b", action("init"))],
233            FixPolicy::All,
234            &mut |_| true,
235            &mut exec,
236        );
237        assert_eq!(exec.calls.len(), 1, "a failed fix is not retried");
238        for outcome in &outcomes {
239            assert!(!outcome.applied);
240            assert_eq!(outcome.error.as_deref(), Some("boom"));
241        }
242    }
243
244    #[test]
245    fn findings_without_a_fix_are_skipped() {
246        let mut exec = Recorder::default();
247        let outcomes = apply_fixes(
248            &[Finding::new("tracing", "a", Severity::Warn, "m")],
249            FixPolicy::All,
250            &mut |_| true,
251            &mut exec,
252        );
253        assert!(outcomes.is_empty() && exec.calls.is_empty());
254    }
255}