diff options
Diffstat (limited to 'src/review')
| -rw-r--r-- | src/review/approve.rs | 267 | ||||
| -rw-r--r-- | src/review/candidates.rs | 293 | ||||
| -rw-r--r-- | src/review/diff.rs | 156 | ||||
| -rw-r--r-- | src/review/mod.rs | 8 |
4 files changed, 724 insertions, 0 deletions
diff --git a/src/review/approve.rs b/src/review/approve.rs new file mode 100644 index 0000000..b62adec --- /dev/null +++ b/src/review/approve.rs @@ -0,0 +1,267 @@ +//! Approval semantics (§7.1, §7.1a, §7.2, §7.4). +//! +//! Rule of the system: **we build exactly what was displayed, or nothing.** +//! The approve POST carries the `identity_hash` and `diff_digest` that were +//! rendered; if either has moved under the reviewer, the approval is refused +//! with a conflict (HTTP 409) and a re-render, never silently retargeted. + +use rusqlite::OptionalExtension; + +use crate::db::{self, *}; +use crate::error::{Error, Result}; +use crate::time; + +/// Why an approval was refused (§7.1a). Rendered as HTTP 409 with the current +/// diff, plus a CLI message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Stale { + NotPending { state: String }, + Identity { expected: String, actual: String }, + Diff { expected: String, actual: String }, + Base { expected: Option<i64>, actual: Option<i64> }, +} + +impl std::fmt::Display for Stale { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Stale::NotPending { state } => write!(f, "review is no longer pending (state: {state})"), + Stale::Identity { expected, actual } => write!( + f, + "the candidate changed while you were looking: you were shown {expected}, it is now {actual}" + ), + Stale::Diff { expected, actual } => write!( + f, + "the diff changed while you were looking (shown {expected}, now {actual})" + ), + Stale::Base { .. } => write!( + f, + "a newer version was accepted since this review was opened" + ), + } + } +} + +#[derive(Debug, Clone)] +pub struct Approval { + pub id: i64, + pub candidate_id: i64, + pub base_release_id: Option<i64>, + pub decision: String, + pub diff_digest: String, + pub identity_hash: String, +} + +/// Approve a candidate. Returns the approval row on success, or the reason the +/// approval was refused. +pub fn approve( + db: &Db, + actor: &str, + candidate_id: i64, + identity_hash: &str, + diff_digest: &str, + note: Option<&str>, +) -> std::result::Result<Approval, Stale> { + let actor = actor.to_string(); + let ih = identity_hash.to_string(); + let dd = diff_digest.to_string(); + let note = note.map(|s| s.to_string()); + let at = time::now(); + + db.writer.tx(move |tx| -> Result<std::result::Result<Approval, Stale>> { + type CandidateState = (i64, String, String, Option<i64>, Option<i64>, String, String); + let row: Option<CandidateState> = tx + .query_row( + "SELECT c.id, c.state, c.identity_hash, c.base_release_id, p.current_accepted_release_id, + c.risk_level, b.name + FROM candidate c JOIN pkgbase p ON p.id = c.pkgbase_id + WHERE c.id = ?1", + rusqlite::params![candidate_id], + |r| { + Ok(( + r.get(0)?, + r.get(1)?, + r.get(2)?, + r.get(3)?, + r.get(4)?, + r.get(5)?, + r.get(6)?, + )) + }, + ) + .optional()?; + let (id, state, actual_identity, base, current_base, risk, _pkgbase) = + row.ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; + + // 1. still open + if state != candidate_state::PENDING { + return Ok(Err(Stale::NotPending { state })); + } + // 2. same candidate bytes + if actual_identity != ih { + return Ok(Err(Stale::Identity { expected: ih.clone(), actual: actual_identity })); + } + // 3. same rendered diff + let stored_diff: String = tx.query_row( + "SELECT diff_digest FROM candidate WHERE id=?1", + rusqlite::params![id], + |r| r.get(0), + )?; + if stored_diff != dd { + return Ok(Err(Stale::Diff { expected: dd.clone(), actual: stored_diff })); + } + // 4. base is still the accepted release (I2, end to end) + if base != current_base { + return Ok(Err(Stale::Base { expected: base, actual: current_base })); + } + + tx.execute( + "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level, + diff_digest, identity_hash, note) + VALUES (?1,?2,?3,'approved',?4,?5,?6,?7)", + rusqlite::params![id, base, at, risk, dd, ih, note], + )?; + let approval_id = tx.last_insert_rowid(); + tx.execute( + "UPDATE candidate SET state='approved', resolved_at=?1 WHERE id=?2", + rusqlite::params![at, id], + )?; + let pkgbase_id: i64 = tx.query_row( + "SELECT pkgbase_id FROM candidate WHERE id=?1", + rusqlite::params![id], + |r| r.get(0), + )?; + tx.execute( + "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) + VALUES (?1,'human',?2,'approve','candidate',?3,?4)", + rusqlite::params![ + at, + actor, + id.to_string(), + serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": pkgbase_id}) + .to_string() + ], + )?; + Ok(Ok(Approval { + id: approval_id, + candidate_id: id, + base_release_id: base, + decision: "approved".into(), + diff_digest: dd, + identity_hash: ih, + })) + }) + .map_err(|e| Stale::NotPending { state: e.to_string() })? +} + +/// Reject a candidate. Rejection is remembered per identity so the watcher stops +/// nagging about the same version (§7.1), and can be re-opened later. +pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> { + let actor = actor.to_string(); + let note = note.to_string(); + let at = time::now(); + db.writer.tx(move |tx| { + let state: String = tx + .query_row("SELECT state FROM candidate WHERE id=?1", rusqlite::params![candidate_id], |r| r.get(0)) + .optional()? + .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; + if state != candidate_state::PENDING { + return Err(Error::conflict(format!("candidate is {state}, not pending"))); + } + let identity: String = tx.query_row( + "SELECT identity_hash FROM candidate WHERE id=?1", + rusqlite::params![candidate_id], + |r| r.get(0), + )?; + tx.execute( + "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level, + diff_digest, identity_hash, note) + SELECT id, base_release_id, ?1, 'rejected', risk_level, diff_digest, ?2, ?3 + FROM candidate WHERE id=?4", + rusqlite::params![at, identity, note, candidate_id], + )?; + tx.execute( + "UPDATE candidate SET state='rejected', resolved_at=?1 WHERE id=?2", + rusqlite::params![at, candidate_id], + )?; + tx.execute( + "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) + VALUES (?1,'human',?2,'reject','candidate',?3,?4)", + rusqlite::params![at, actor, candidate_id.to_string(), serde_json::json!({"note": note}).to_string()], + )?; + Ok(()) + }) +} + +/// §7.4 bulk decision. High-risk items are refused unless confirmed individually. +pub fn bulk( + db: &Db, + actor: &str, + items: &[(i64, String, String)], // (candidate_id, identity_hash, diff_digest) + decision: &str, + confirm_high_risk: bool, +) -> Result<Vec<std::result::Result<Approval, Stale>>> { + let mut out = Vec::new(); + for (id, ih, dd) in items { + let risk: String = db.read(|c| { + Ok(c.query_row( + "SELECT risk_level FROM candidate WHERE id=?1", + rusqlite::params![id], + |r| r.get(0), + ) + .optional()?) + })? + .unwrap_or_default(); + if decision == "approve" && risk == "high" && !confirm_high_risk { + out.push(Err(Stale::NotPending { + state: "high-risk: needs individual confirmation".into(), + })); + continue; + } + out.push(match decision { + "approve" => approve(db, actor, *id, ih, dd, Some("bulk")), + "reject" => reject(db, actor, *id, "bulk") + .map(|_| Approval { id: 0, candidate_id: *id, base_release_id: None, decision: "rejected".into(), diff_digest: dd.clone(), identity_hash: ih.clone() }) + .map_err(|e| Stale::NotPending { state: e.to_string() }), + other => Err(Stale::NotPending { state: format!("unknown decision {other}") }), + }); + } + Ok(out) +} + +/// The approval behind a candidate, if any. +pub fn approval_for(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> { + db.read(|c| { + Ok(c.query_row( + "SELECT id, decision FROM approval WHERE candidate_id=?1", + rusqlite::params![candidate_id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?) + }) +} + +/// Withdraw a published release (§9 `repo-remove` path, decision 23: warns, +/// does not block). +pub fn withdraw(db: &Db, actor: &str, release_id: i64, reason: &str) -> Result<()> { + let actor = actor.to_string(); + let reason = reason.to_string(); + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute("UPDATE release SET state='withdrawn' WHERE id=?1", rusqlite::params![release_id])?; + tx.execute( + "UPDATE package SET state='removed' WHERE release_id=?1", + rusqlite::params![release_id], + )?; + tx.execute( + "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) + VALUES (?1,'human',?2,'withdraw','release',?3,?4)", + rusqlite::params![at, actor, release_id.to_string(), serde_json::json!({"reason": reason}).to_string()], + )?; + Ok(()) + }) +} + +/// The pkgbase's accepted release pointer, exposed for callers that need it. +pub fn current_accepted(db: &Db, pkgbase: &str) -> Result<Option<ReleaseRow>> { + db::accepted_release(db, pkgbase) +} diff --git a/src/review/candidates.rs b/src/review/candidates.rs new file mode 100644 index 0000000..4dc6c4f --- /dev/null +++ b/src/review/candidates.rs @@ -0,0 +1,293 @@ +//! Candidate creation and the collapse-in-place rule (§7.1). +//! +//! One review object per pkgbase at a time. A newer detection **collapses into** +//! the open review rather than queueing beside it, and the review's `base` is +//! fixed at creation to the pkgbase's `current_accepted_release` — that is what +//! makes "diff against the last accepted version, never the last seen one" (I2) +//! true no matter how many detections arrive while nobody is looking. + +use rusqlite::OptionalExtension; + +use crate::db::{self, *}; +use crate::error::Result; +use crate::time; + +#[derive(Debug, Clone)] +pub struct NewCandidate { + pub snapshot_id: i64, + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub upstream_pins_json: String, + pub source_digests_json: String, + pub identity_hash: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Upsert { + /// A new review row was opened. + Created { id: i64, kind: String }, + /// The open review was updated in place; no new row, `base` untouched (I7). + Collapsed { id: i64, revision: i64 }, + /// A human had already seen the old diff, so it was frozen as `superseded` + /// and a fresh review opened (decision 8). + Superseded { old: i64, new: i64 }, + /// This exact identity was rejected before; do not nag (§7.1). + PreviouslyRejected, + /// Nothing changed relative to what is already recorded. + Unchanged, +} + +/// Insert-or-collapse a candidate for `pb`. +/// +/// `accepted` is the pkgbase's current accepted release, or `None` when this is +/// a first introduction (§7.1b). +pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc: &NewCandidate) -> Result<Upsert> { + let kind = if accepted.is_some() { candidate_kind::NEW_VERSION } else { candidate_kind::FIRST_INTRODUCTION }; + let base = accepted.map(|a| a.id); + let pkgbase_id = pb.id; + let nc = nc.clone(); + + db.writer.tx(move |tx| { + let existing: Option<(i64, String, Option<String>, i64)> = tx + .query_row( + "SELECT id, identity_hash, viewed_at, revision FROM candidate + WHERE pkgbase_id=?1 AND state='pending_review'", + rusqlite::params![pkgbase_id], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), + ) + .optional()?; + + if let Some((id, identity, viewed, revision)) = existing { + if identity == nc.identity_hash { + return Ok(Upsert::Unchanged); + } + if viewed.is_none() { + // Collapse in place: same base, no new row, revision bumped. + tx.execute( + "UPDATE candidate SET snapshot_id=?1, epoch=?2, pkgver=?3, pkgrel=?4, + upstream_pins_json=?5, source_digests_json=?6, identity_hash=?7, + revision=?8, detected_at=?9, diff_digest='' + WHERE id=?10", + rusqlite::params![ + nc.snapshot_id, nc.epoch, nc.pkgver, nc.pkgrel, + nc.upstream_pins_json, nc.source_digests_json, nc.identity_hash, + revision + 1, time::now(), id + ], + )?; + return Ok(Upsert::Collapsed { id, revision: revision + 1 }); + } + // A human saw the old diff: freeze it for the audit trail and open a + // fresh review against the same base. + tx.execute( + "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2", + rusqlite::params![time::now(), id], + )?; + let new_id = insert(tx, pkgbase_id, base, kind, &nc)?; + return Ok(Upsert::Superseded { old: id, new: new_id }); + } + + // No open review. A previously rejected identity must not be re-raised. + let rejected: Option<i64> = tx + .query_row( + "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 AND state='rejected' + ORDER BY id DESC LIMIT 1", + rusqlite::params![pkgbase_id, nc.identity_hash], + |r| r.get(0), + ) + .optional()?; + if rejected.is_some() { + return Ok(Upsert::PreviouslyRejected); + } + // Same identity already approved/recorded: nothing to do. + let same: Option<i64> = tx + .query_row( + "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 + ORDER BY id DESC LIMIT 1", + rusqlite::params![pkgbase_id, nc.identity_hash], + |r| r.get(0), + ) + .optional()?; + if same.is_some() { + return Ok(Upsert::Unchanged); + } + let id = insert(tx, pkgbase_id, base, kind, &nc)?; + Ok(Upsert::Created { id, kind: kind.to_string() }) + }) +} + +fn insert( + tx: &mut rusqlite::Transaction<'_>, + pkgbase_id: i64, + base: Option<i64>, + kind: &str, + nc: &NewCandidate, +) -> Result<i64> { + tx.execute( + "INSERT INTO candidate (pkgbase_id, base_release_id, kind, snapshot_id, epoch, pkgver, pkgrel, + upstream_pins_json, source_digests_json, identity_hash, state, detected_at) + VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'pending_review',?11)", + rusqlite::params![ + pkgbase_id, base, kind, nc.snapshot_id, nc.epoch, nc.pkgver, nc.pkgrel, + nc.upstream_pins_json, nc.source_digests_json, nc.identity_hash, time::now() + ], + )?; + Ok(tx.last_insert_rowid()) +} + +impl NewCandidate { + /// The `epoch:pkgver-pkgrel` this candidate would publish. + pub fn version(&self) -> String { + crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) + } +} + +/// Mark a candidate `viewed` the first time a human opens it. That timestamp is +/// what decides whether a later detection collapses or supersedes (§7.1). +pub fn mark_viewed(db: &Db, id: i64) -> Result<()> { + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL", + rusqlite::params![at, id], + )?; + Ok(()) + }) +} + +pub fn pending_candidates(db: &Db) -> Result<Vec<CandidateRow>> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, + c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, + c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, + c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name + FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id + WHERE c.state='pending_review' + ORDER BY (c.risk_level='high') DESC, c.detected_at", + )?; + let rows = stmt.query_map([], row_to_candidate)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +pub fn candidate_by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> { + db.read(|c| { + Ok(c.query_row( + "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, + c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, + c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, + c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name + FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?1", + rusqlite::params![id], + row_to_candidate, + ) + .optional()?) + }) +} + +fn row_to_candidate(r: &rusqlite::Row<'_>) -> rusqlite::Result<CandidateRow> { + Ok(CandidateRow { + id: r.get(0)?, + pkgbase_id: r.get(1)?, + base_release_id: r.get(2)?, + kind: r.get(3)?, + snapshot_id: r.get(4)?, + epoch: r.get(5)?, + pkgver: r.get(6)?, + pkgrel: r.get(7)?, + upstream_pins_json: r.get(8)?, + source_digests_json: r.get(9)?, + identity_hash: r.get(10)?, + diff_digest: r.get(11)?, + revision: r.get(12)?, + viewed_at: r.get(13)?, + risk_level: r.get(14)?, + risk_signals_json: r.get(15)?, + missing_deps_json: r.get(16)?, + state: r.get(17)?, + detected_at: r.get(18)?, + resolved_at: r.get(19)?, + pkgbase: r.get(20)?, + }) +} + +/// Open reviews for a pkgbase (usually zero or one, by I7). +pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result<Vec<CandidateRow>> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, + c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, + c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, + c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name + FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id + WHERE c.pkgbase_id=?1 AND c.state='pending_review'", + )?; + let rows = stmt.query_map(rusqlite::params![pkgbase_id], row_to_candidate)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +/// §7.1: a rejection can be re-opened. We retire the rejected row so it stops +/// suppressing the identity, and the next detection opens a fresh review. +pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> { + let at = time::now(); + db.writer.tx(move |tx| { + let n = tx.execute( + "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2 AND state='rejected'", + rusqlite::params![at, id], + )?; + if n == 0 { + return Err(crate::error::Error::conflict("candidate is not rejected")); + } + Ok(()) + }) +} + +/// Record the risk assessment computed at review time. +pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()> { + let lvl = level.to_string(); + let sig = serde_json::to_string(signals)?; + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3", + rusqlite::params![lvl, sig, id], + )?; + Ok(()) + }) +} + +pub fn set_missing_deps(db: &Db, id: i64, missing: &[String]) -> Result<()> { + let m = serde_json::to_string(missing)?; + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET missing_deps_json=?1 WHERE id=?2", + rusqlite::params![m, id], + )?; + Ok(()) + }) +} + +pub fn set_diff_digest(db: &Db, id: i64, digest: &str) -> Result<()> { + let d = digest.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE candidate SET diff_digest=?1 WHERE id=?2", rusqlite::params![d, id])?; + Ok(()) + }) +} + +/// Convenience used by the watcher: the accepted release of a pkgbase row. +pub fn accepted_for(db: &Db, pb: &Pkgbase) -> Result<Option<ReleaseRow>> { + match pb.current_accepted_release_id { + Some(id) => db::release_by_id(db, id), + None => Ok(None), + } +} diff --git a/src/review/diff.rs b/src/review/diff.rs new file mode 100644 index 0000000..cfce3fe --- /dev/null +++ b/src/review/diff.rs @@ -0,0 +1,156 @@ +//! 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)); + } 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) +} + +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")); + let ord = crate::pkgver::vercmp(&bv, &cv); + 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"); + } + let _ = ord; + } + 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 { ", sha256sums=SKIP" } 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) +} diff --git a/src/review/mod.rs b/src/review/mod.rs new file mode 100644 index 0000000..25abca8 --- /dev/null +++ b/src/review/mod.rs @@ -0,0 +1,8 @@ +//! Review lifecycle: candidate creation and collapse-in-place (§7.1), the +//! approval record (§7.2), diffing (§6) and risk scoring (§6). + +pub mod approve; +pub mod candidates; +pub mod diff; + +pub use candidates::{upsert_candidate, NewCandidate, Upsert}; |
