summaryrefslogtreecommitdiffstats
path: root/src/review/diff.rs
blob: 3eecc4ee94c7c88684cdaf411dae7f1884ec8c79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
//! Diff rendering (§6).
//!
//! A review is not one diff, it is a panel set, and **every** panel compares what
//! the accepted release recorded against what the candidate records now — never
//! "last seen". The rendered text is hashed into `diff_digest`, which is what
//! makes "we build exactly what was displayed, or nothing" (§7.1a) provable.

use crate::config::Config;
use crate::db::{self, *};
use crate::error::Result;
use crate::git;

#[derive(Debug, Clone)]
pub struct Panel {
    pub name: &'static str,
    pub title: &'static str,
    /// Unified-diff text, or a readable rendering for panels that are not diffs.
    pub body: String,
}

/// Everything a reviewer needs for one candidate.
pub fn panels(cfg: &Config, db: &Db, c: &CandidateRow, base: Option<&ReleaseRow>) -> Result<Vec<Panel>> {
    let mut out = Vec::new();
    let snap = db::snapshot_by_id(db, c.snapshot_id)?;
    let mirror = std::path::PathBuf::from(
        db::get_pkgbase_by_id(db, c.pkgbase_id)?
            .and_then(|p| p.mirror_path)
            .unwrap_or_else(|| cfg.mirror_path(&c.pkgbase).display().to_string()),
    );

    out.push(version_delta(base, c));

    if let Some(base) = base {
        if let Some(s) = &snap {
            let range = format!("{}..{}", base.aur_commit, s.aur_commit);
            let body = git::diff(&mirror, &range, &[]).unwrap_or_else(|e| {
                format!("(diff unavailable: {e})\n\n--- base {}\n+++ candidate {}", base.aur_commit, s.aur_commit)
            });
            out.push(Panel { name: "recipe", title: "Recipe diff", body });
        }
        out.push(digest_delta(base, c));
        out.push(pin_delta(base, c));
        let old_recipe = recipe_of(db, base.candidate_id.and_then(|cid| {
            candidate_snapshot_id(db, cid)
        }));
        let new_recipe = recipe_of(db, Some(c.snapshot_id));
        if let (Some(old), Some(new)) = (&old_recipe, &new_recipe) {
            out.push(source_delta(old, new));
            out.push(dependency_delta(old, new));
            out.push(build_env_delta(old, new));
            out.push(install_delta(old, new));
        }
    } else {
        // §7.1b first_introduction: no diff pane. The full recipe is rendered
        // readably instead, by the template.
        out.push(Panel {
            name: "recipe_full",
            title: "Full recipe",
            body: snap
                .map(|s| s.srcinfo_json.clone())
                .unwrap_or_else(|| "(no snapshot)".into()),
        });
    }
    Ok(out)
}

/// The recipe a candidate recorded, if we kept the snapshot.
fn recipe_of(db: &Db, snapshot_id: Option<i64>) -> Option<Recipe> {
    let id = snapshot_id?;
    let snap = db::snapshot_by_id(db, id).ok().flatten()?;
    serde_json::from_str(&snap.srcinfo_json).ok()
}

fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Option<i64> {
    db::candidate_snapshot_id(db, candidate_id).ok().flatten()
}

/// `source=()` entries added, removed, or moved to a different host (§6). A new
/// host is the classic supply-chain shape and must be impossible to miss.
fn source_delta(old: &Recipe, new: &Recipe) -> Panel {
    let mut body = String::new();
    for s in &new.source {
        if !old.source.contains(s) {
            body.push_str(&format!("+ {s}\n"));
        }
    }
    for s in &old.source {
        if !new.source.contains(s) {
            body.push_str(&format!("- {s}\n"));
        }
    }
    let old_hosts = crate::urlutil::hosts(&old.source);
    let new_hosts = crate::urlutil::hosts(&new.source);
    for h in new_hosts.difference(&old_hosts) {
        body.push_str(&format!("! new source host: {h}\n"));
    }
    for h in old_hosts.difference(&new_hosts) {
        body.push_str(&format!("! source host gone: {h}\n"));
    }
    // A declared checksum that became SKIP is a weakening, not a change.
    for (i, sum) in new.sha256sums.iter().enumerate() {
        if sum.eq_ignore_ascii_case("SKIP") {
            match old.sha256sums.get(i) {
                Some(prev) if prev != "SKIP" && !prev.is_empty() => {
                    body.push_str(&format!("! [{i}] checksum removed (was {prev}, now SKIP)\n"))
                }
                _ => {}
            }
        }
    }
    if !old.validpgpkeys.is_empty() && new.validpgpkeys.is_empty() {
        body.push_str("! validpgpkeys removed\n");
    }
    if new.skipgpcheck && !old.skipgpcheck {
        body.push_str("! --skippgpcheck added\n");
    }
    Panel { name: "sources", title: "Source delta", body }
}

/// Dependency changes, resolved against our own index where we can say what it
/// means: "this will pull in a package we have never published".
fn dependency_delta(old: &Recipe, new: &Recipe) -> Panel {
    let mut body = String::new();
    for (label, o, n) in [
        ("depends", &old.depends, &new.depends),
        ("makedepends", &old.makedepends, &new.makedepends),
        ("checkdepends", &old.checkdepends, &new.checkdepends),
        ("optdepends", &old.optdepends, &new.optdepends),
        ("provides", &old.provides, &new.provides),
        ("conflicts", &old.conflicts, &new.conflicts),
    ] {
        let oset: std::collections::BTreeSet<String> = crate::pkgver::dep_names(o).into_iter().collect();
        let nset: std::collections::BTreeSet<String> = crate::pkgver::dep_names(n).into_iter().collect();
        for d in nset.difference(&oset) {
            body.push_str(&format!("+ {label}: {d}\n"));
        }
        for d in oset.difference(&nset) {
            body.push_str(&format!("- {label}: {d}\n"));
        }
    }
    if !old.checkdepends.is_empty() && new.checkdepends.is_empty() {
        body.push_str("! tests will no longer run\n");
    }
    Panel { name: "deps", title: "Dependency delta", body }
}

/// Everything that changes *how* it is built rather than what is built.
fn build_env_delta(old: &Recipe, new: &Recipe) -> Panel {
    let mut body = String::new();
    for o in &new.options {
        if !old.options.contains(o) {
            body.push_str(&format!("+ options: {o}\n"));
        }
    }
    for o in &old.options {
        if !new.options.contains(o) {
            body.push_str(&format!("- options: {o}\n"));
        }
    }
    for a in &new.arch {
        if !old.arch.contains(a) {
            body.push_str(&format!("+ arch: {a}\n"));
        }
    }
    for a in &old.arch {
        if !new.arch.contains(a) {
            body.push_str(&format!("- arch: {a}\n"));
        }
    }
    if old.pkgbase != new.pkgbase {
        body.push_str(&format!("! pkgbase renamed: {} -> {}\n", old.pkgbase, new.pkgbase));
    }
    let old_set: std::collections::BTreeSet<String> = old.pkgnames.iter().cloned().collect();
    let new_set: std::collections::BTreeSet<String> = new.pkgnames.iter().cloned().collect();
    for p in new_set.difference(&old_set) {
        body.push_str(&format!("+ split package: {p}\n"));
    }
    for p in old_set.difference(&new_set) {
        body.push_str(&format!("- split package: {p}\n"));
    }
    Panel { name: "buildenv", title: "Build-env delta", body }
}

/// `.install` hooks are arbitrary code that runs on every consumer machine.
fn install_delta(old: &Recipe, new: &Recipe) -> Panel {
    let mut body = String::new();
    match (&old.install, &new.install) {
        (None, Some(f)) => body.push_str(&format!("+ install script added: {f}\n")),
        (Some(f), None) => body.push_str(&format!("- install script removed: {f}\n")),
        (Some(a), Some(b)) if a != b => body.push_str(&format!("! install script changed: {a} -> {b}\n")),
        _ => {}
    }
    if crate::recipe::bodies_changed(&old.pkgbuild, &new.pkgbuild) {
        // The recipe diff shows the text; this panel calls out that the
        // executable part moved, which is what actually runs — on this machine
        // and on every machine that installs the result.
        body.push_str("! build()/package() bodies changed — this is code that runs here and on every installer\n");
    }
    Panel { name: "install", title: "Install-script delta", body }
}

fn version_delta(base: Option<&ReleaseRow>, c: &CandidateRow) -> Panel {
    let mut body = String::new();
    match base {
        Some(b) => {
            let (bv, cv) = (b.version(), c.version());
            body.push_str(&format!("{bv} -> {cv}\n"));
            if b.epoch != c.epoch {
                body.push_str(&format!("epoch bump: {} -> {}\n", b.epoch, c.epoch));
            }
            if b.pkgrel != c.pkgrel && b.pkgver == c.pkgver {
                body.push_str(&format!("pkgrel change: {} -> {}\n", b.pkgrel, c.pkgrel));
            }
            if crate::pkgver::is_downgrade(&bv, &cv) {
                body.push_str("DOWNGRADE: AUR now offers a lower version than we serve\n");
            }
        }
        None => body.push_str(&format!("first introduction: {}\n", c.version())),
    }
    Panel { name: "version", title: "Version delta", body }
}

fn digest_delta(base: &ReleaseRow, c: &CandidateRow) -> Panel {
    let mut body = String::new();
    let old: Vec<SourceDigest> = base.digests();
    let new: Vec<SourceDigest> = c.digests();
    for n in &new {
        match old.iter().find(|o| o.index == n.index) {
            Some(o) if o.digest != n.digest => {
                body.push_str(&format!(
                    "! [{}] {} {} -> {}\n",
                    n.index, n.url, short(&o.digest), short(&n.digest)
                ));
            }
            Some(_) => body.push_str(&format!("  [{}] {} unchanged\n", n.index, n.url)),
            None => body.push_str(&format!(
                "+ [{}] {} NEW ({}{})\n",
                n.index,
                n.url,
                n.kind,
                if n.skip_declared && !n.is_vcs() { ", sha256sums=SKIP" } else if n.is_vcs() { ", pinned commit" } else { "" }
            )),
        }
    }
    for o in &old {
        if !new.iter().any(|n| n.index == o.index) {
            body.push_str(&format!("- [{}] {} REMOVED\n", o.index, o.url));
        }
    }
    Panel { name: "digests", title: "Source digest delta", body }
}

fn pin_delta(base: &ReleaseRow, c: &CandidateRow) -> Panel {
    let mut body = String::new();
    let old: Vec<UpstreamPin> = base.pins();
    let new: Vec<UpstreamPin> = c.pins();
    if old.is_empty() && new.is_empty() {
        body.push_str("no VCS sources\n");
    }
    for n in &new {
        match old.iter().find(|o| o.index == n.index) {
            Some(o) if o.commit != n.commit => {
                body.push_str(&format!(
                    "! [{}] {} {} -> {} (branch {})\n",
                    n.index, n.url, short(&o.commit), short(&n.commit), n.branch.as_deref().unwrap_or("?")
                ));
            }
            Some(_) => body.push_str(&format!("  [{}] {} unchanged\n", n.index, n.url)),
            None => body.push_str(&format!("+ [{}] {} at {}\n", n.index, n.url, short(&n.commit))),
        }
    }
    Panel { name: "upstream", title: "Upstream delta", body }
}

fn short(s: &str) -> String {
    if s.len() > 12 { s[..12].to_string() } else { s.to_string() }
}

/// Flatten the rendered panels into one canonical string.
pub fn render_text(ps: &[Panel]) -> String {
    let mut s = String::new();
    for p in ps {
        s.push_str(&format!("### {}\n{}\n", p.title, p.body));
    }
    s
}

/// `diff_digest`: hash of the exact rendered diff the human was shown (§7.2).
pub fn diff_digest(ps: &[Panel]) -> String {
    crate::hash::hex_str(&render_text(ps))
}

/// The recipe text a reviewer reads for a first introduction (§7.1b).
pub fn full_recipe_text(db: &Db, c: &CandidateRow) -> Result<String> {
    let snap = db::snapshot_by_id(db, c.snapshot_id)?;
    let snap = snap.ok_or_else(|| crate::error::Error::not_found("snapshot missing"))?;
    let r: Recipe = serde_json::from_str(&snap.srcinfo_json).unwrap_or_default();
    Ok(r.pkgbuild)
}

/// Render the panels, store the resulting `diff_digest` on the candidate, and
/// hand it back. The approve POST must echo this value, which is what makes
/// "we build exactly what was displayed" checkable (§7.1a).
pub fn render_and_store(db: &Db, cfg: &Config, c: &CandidateRow) -> Result<String> {
    let base = match c.base_release_id {
        Some(id) => db::release_by_id(db, id)?,
        None => None,
    };
    let ps = panels(cfg, db, c, base.as_ref())?;
    let digest = diff_digest(&ps);
    crate::review::candidates::set_diff_digest(db, c.id, &digest)?;
    Ok(digest)
}

/// Re-render for a 409 response: show the reviewer what the candidate is now.
pub fn render_current(db: &Db, cfg: &Config, c: &CandidateRow) -> Result<(String, String)> {
    let base = match c.base_release_id {
        Some(id) => db::release_by_id(db, id)?,
        None => None,
    };
    let ps = panels(cfg, db, c, base.as_ref())?;
    Ok((render_text(&ps), diff_digest(&ps)))
}