1use 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 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 pub build: Option<Vec<String>>,
35 pub cases: usize,
36 pub changed: Vec<Drifted>,
38 pub failing: Vec<Drifted>,
40 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}