Skip to main content

rust_anything/
drift.rs

1//! `app drift`: whether the recording still describes the original, and the port still matches
2//! it. Replays the original and the build against `rust/app-cases`, and lists the documented
3//! examples no case records.
4
5use std::collections::BTreeSet;
6use std::path::{Path, PathBuf};
7
8use anyhow::{Context, Result, bail};
9use serde::Serialize;
10
11use crate::app::{self, Config, Failure, ReplayOptions, ReplayOutcome};
12use crate::walk::Canonical;
13
14pub const REPORT_FILE: &str = "drift-report.md";
15
16pub struct DriftOptions<'a> {
17    pub repo: &'a Path,
18    /// Command line of the build to check; `rust/app`, built with cargo, when `None` and it exists.
19    pub build: Option<&'a str>,
20    pub timeout_secs: Option<u64>,
21}
22
23#[derive(Debug, Serialize)]
24pub struct Drifted {
25    pub case: String,
26    pub args: Vec<String>,
27    pub fields: Vec<String>,
28    pub verdict: String,
29}
30
31#[derive(Debug, Serialize)]
32pub struct DriftOutcome {
33    /// The build checked, if any.
34    pub build: Option<Vec<String>>,
35    pub cases: usize,
36    /// Cases the original no longer matches: it changed upstream.
37    pub changed: Vec<Drifted>,
38    /// Cases the build no longer matches.
39    pub failing: Vec<Drifted>,
40    /// Examples in the original's docs that no case records.
41    pub new: Vec<String>,
42    pub drifted: bool,
43    pub report: PathBuf,
44}
45
46fn fields(f: &Failure) -> Vec<String> {
47    f.problems.iter().map(|p| p.field.clone()).collect()
48}
49
50fn failed(outcome: &ReplayOutcome) -> BTreeSet<&str> {
51    outcome.failures.iter().map(|f| f.case.as_str()).collect()
52}
53
54pub fn drift(opts: &DriftOptions) -> Result<DriftOutcome> {
55    app::check_timeout(opts.timeout_secs)?;
56    let repo = opts
57        .repo
58        .canonical()
59        .with_context(|| format!("no folder {}", opts.repo.display()))?;
60    let dir = app::cases_dir(&repo);
61    let Some(config) = Config::load(&repo)? else {
62        if let Ok(state) = crate::front_door::State::load(&repo)
63            && state.kind == crate::front_door::AppKind::Library
64        {
65            bail!(
66                "{} is a library: `app drift` checks CLIs and servers; use `rust-anything map --check` to find units whose original changed",
67                state.name
68            );
69        }
70        bail!(
71            "no {} in {}: run `rust-anything app record` first",
72            app::CONFIG_FILE,
73            dir.display()
74        );
75    };
76    let build = match opts.build {
77        Some(b) => Some(b.to_string()),
78        None => {
79            let app_dir = repo.join(crate::front_door::APP_DIR);
80            if app_dir.join("Cargo.toml").is_file() {
81                let exe = crate::front_door::cargo_build(&app_dir, Some(&app_dir.join("target")))?;
82                Some(app::shell_quote(&exe.to_string_lossy()))
83            } else {
84                None
85            }
86        }
87    };
88    let original = app::replay_unwritten(&ReplayOptions {
89        repo: &repo,
90        build: None,
91        timeout_secs: opts.timeout_secs,
92        port: None,
93        case: None,
94    })?;
95    let port = match &build {
96        Some(b) => Some(app::replay_unwritten(&ReplayOptions {
97            repo: &repo,
98            build: Some(b),
99            timeout_secs: opts.timeout_secs,
100            port: None,
101            case: None,
102        })?),
103        None => None,
104    };
105    let new = app::unrecorded_examples(&repo, &config)?;
106
107    let original_failed = failed(&original);
108    let port_failed = port.as_ref().map(failed).unwrap_or_default();
109    let changed: Vec<Drifted> = original
110        .failures
111        .iter()
112        .map(|f| Drifted {
113            case: f.case.clone(),
114            args: f.args.clone(),
115            fields: fields(f),
116            verdict: match &port {
117                None => "original changed",
118                Some(_) if port_failed.contains(f.case.as_str()) => "original and port both differ",
119                Some(_) => "original changed, port still old",
120            }
121            .to_string(),
122        })
123        .collect();
124    let failing: Vec<Drifted> = port
125        .iter()
126        .flat_map(|p| &p.failures)
127        .map(|f| Drifted {
128            case: f.case.clone(),
129            args: f.args.clone(),
130            fields: fields(f),
131            verdict: if original_failed.contains(f.case.as_str()) {
132                "original and port both differ"
133            } else {
134                "port regression"
135            }
136            .to_string(),
137        })
138        .collect();
139    let outcome = DriftOutcome {
140        build: port.as_ref().map(|p| p.build.clone()),
141        cases: original.total,
142        drifted: !changed.is_empty() || !failing.is_empty() || !new.is_empty(),
143        changed,
144        failing,
145        new,
146        report: dir.join(REPORT_FILE),
147    };
148    let text = app::stable_paths(&report(&outcome, &original, port.as_ref()));
149    std::fs::write(&outcome.report, text)
150        .with_context(|| format!("writing {}", outcome.report.display()))?;
151    Ok(outcome)
152}
153
154fn quoted(words: &[String]) -> String {
155    words
156        .iter()
157        .map(|w| app::shell_quote(w))
158        .collect::<Vec<_>>()
159        .join(" ")
160}
161
162fn diffs(out: &mut String, drifted: &[Drifted], replay: &ReplayOutcome) {
163    for d in drifted {
164        *out += &format!(
165            "\n### {} ({})\n\nArguments: `{}`\n",
166            d.case,
167            d.verdict,
168            quoted(&d.args)
169        );
170        let Some(f) = replay.failures.iter().find(|f| f.case == d.case) else {
171            continue;
172        };
173        for p in &f.problems {
174            if let Some(at) = &p.at {
175                *out += &format!("\n{}\n", at.describe().replace("```", "`\u{200b}``"));
176            }
177            *out += &format!(
178                "\n{}:\n\n```diff\n{}```\n",
179                p.field,
180                p.detail.replace("```", "`\u{200b}``")
181            );
182        }
183    }
184}
185
186fn report(
187    outcome: &DriftOutcome,
188    original: &ReplayOutcome,
189    port: Option<&ReplayOutcome>,
190) -> String {
191    let mut out = String::from("# App drift\n\n");
192    out += &format!(
193        "Original: {}/{} cases match\n\n",
194        original.passed, original.total
195    );
196    match port {
197        Some(p) => {
198            out += &format!(
199                "Build: `{}`: {}/{} cases match\n\n",
200                quoted(&p.build),
201                p.passed,
202                p.total
203            )
204        }
205        None => out += "Build: none (pass --build, or create rust/app with `app front-door`)\n\n",
206    }
207    if !outcome.drifted {
208        out += "No drift: the recording still describes the original, and every documented example is recorded.\n";
209        return out;
210    }
211    if !outcome.changed.is_empty() {
212        out += "## Changed upstream\n\nThe original no longer gives what was recorded. If the change is intended, record again (`rust-anything app record`) and port it.\n";
213        diffs(&mut out, &outcome.changed, original);
214    }
215    if let Some(p) = port
216        && !outcome.failing.is_empty()
217    {
218        out += "\n## Port failures\n\nThe build no longer matches the recording.\n";
219        diffs(&mut out, &outcome.failing, p);
220    }
221    if !outcome.new.is_empty() {
222        out += "\n## New examples\n\nDocumented but not recorded; `rust-anything app record` adds them.\n\n";
223        for n in &outcome.new {
224            out += &format!("- `{n}`\n");
225        }
226    }
227    out
228}
229
230#[cfg(test)]
231mod tests {
232    use std::path::PathBuf;
233
234    use super::{DriftOutcome, Drifted, report};
235    use crate::app::{Failure, Problem, ReplayOutcome};
236
237    fn replay(build: &[&str], passed: usize, failures: Vec<Failure>) -> ReplayOutcome {
238        ReplayOutcome {
239            build: build.iter().map(|w| w.to_string()).collect(),
240            passed,
241            total: 3,
242            skipped: 0,
243            failures,
244            fallback: None,
245            report: PathBuf::new(),
246            groups: Vec::new(),
247        }
248    }
249
250    fn outcome(changed: Vec<Drifted>, failing: Vec<Drifted>, new: Vec<&str>) -> DriftOutcome {
251        DriftOutcome {
252            build: None,
253            cases: 3,
254            drifted: !changed.is_empty() || !failing.is_empty() || !new.is_empty(),
255            changed,
256            failing,
257            new: new.into_iter().map(String::from).collect(),
258            report: PathBuf::new(),
259        }
260    }
261
262    fn drifted(case: &str) -> Drifted {
263        Drifted {
264            case: case.into(),
265            args: vec!["--name".into(), "a b".into()],
266            fields: vec!["stdout".into()],
267            verdict: "changed".into(),
268        }
269    }
270
271    fn failure(case: &str, detail: &str) -> Failure {
272        Failure {
273            case: case.into(),
274            args: Vec::new(),
275            problems: vec![Problem::new("stdout", detail)],
276        }
277    }
278
279    #[test]
280    fn no_drift_and_no_build() {
281        let text = report(
282            &outcome(vec![], vec![], vec![]),
283            &replay(&["node", "cli.js"], 3, vec![]),
284            None,
285        );
286        assert!(
287            text.starts_with("# App drift\n\nOriginal: 3/3 cases match\n\n"),
288            "{text}"
289        );
290        assert!(
291            text.contains("Build: none (pass --build, or create rust/app with `app front-door`)\n"),
292            "{text}"
293        );
294        assert!(
295            text.contains("No drift: the recording still describes the original"),
296            "{text}"
297        );
298        assert!(!text.contains("## "), "{text}");
299    }
300
301    #[test]
302    fn a_build_reports_its_command_and_matches() {
303        let port = replay(&["target/app", "--flag"], 2, vec![]);
304        let text = report(
305            &outcome(vec![], vec![], vec![]),
306            &replay(&["node", "cli.js"], 3, vec![]),
307            Some(&port),
308        );
309        assert!(
310            text.contains("Build: `target/app --flag`: 2/3 cases match\n"),
311            "{text}"
312        );
313    }
314
315    #[test]
316    fn a_changed_case_lists_its_arguments_and_diff() {
317        let original = replay(
318            &["node", "cli.js"],
319            2,
320            vec![failure("greet", "-hello\n+hi\n")],
321        );
322        let text = report(
323            &outcome(vec![drifted("greet")], vec![], vec![]),
324            &original,
325            None,
326        );
327        assert!(text.contains("## Changed upstream\n"), "{text}");
328        assert!(
329            text.contains("\n### greet (changed)\n\nArguments: `--name 'a b'`\n"),
330            "{text}"
331        );
332        assert!(
333            text.contains("\nstdout:\n\n```diff\n-hello\n+hi\n```\n"),
334            "{text}"
335        );
336        assert!(!text.contains("No drift"), "{text}");
337        assert!(!text.contains("## Port failures"), "{text}");
338        assert!(!text.contains("## New examples"), "{text}");
339    }
340
341    #[test]
342    fn port_failures_use_the_builds_replay() {
343        let original = replay(&["node", "cli.js"], 3, vec![]);
344        let port = replay(
345            &["target/app"],
346            2,
347            vec![failure("greet", "-hello\n+hullo\n")],
348        );
349        let text = report(
350            &outcome(vec![], vec![drifted("greet")], vec![]),
351            &original,
352            Some(&port),
353        );
354        assert!(!text.contains("## Changed upstream"), "{text}");
355        assert!(text.contains("\n## Port failures\n"), "{text}");
356        assert!(text.contains("+hullo\n```\n"), "{text}");
357    }
358
359    #[test]
360    fn new_examples_get_one_line_each() {
361        let text = report(
362            &outcome(vec![], vec![], vec!["cli --help", "cli greet x"]),
363            &replay(&["node", "cli.js"], 3, vec![]),
364            None,
365        );
366        assert!(text.contains("\n## New examples\n"), "{text}");
367        assert!(
368            text.contains("\n- `cli --help`\n- `cli greet x`\n"),
369            "{text}"
370        );
371        assert!(!text.contains("No drift"), "{text}");
372    }
373
374    #[test]
375    fn triple_backticks_in_a_diff_cannot_close_the_fence() {
376        let original = replay(
377            &["node", "cli.js"],
378            2,
379            vec![failure("md", "-```js\n+```ts\n")],
380        );
381        let text = report(
382            &outcome(vec![drifted("md")], vec![], vec![]),
383            &original,
384            None,
385        );
386        let body = text.split("```diff\n").nth(1).unwrap();
387        let (inside, _) = body.split_once("```\n").unwrap();
388        assert_eq!(inside, "-`\u{200b}``js\n+`\u{200b}``ts\n");
389        assert_eq!(text.matches("```").count(), 2, "{text}");
390    }
391}