nornir 0.4.54

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! `nornir release undo` (task #32) — reverse a release run's mutating steps.
//!
//! Every mutating release step records a [`ReleaseChange`] with its BEFORE-STATE
//! into the `release_changes` ledger (see [`crate::warehouse::release_changes`]).
//! This module owns:
//!
//!  * the RECORD wrappers — capture the before-state, apply the mutation, append
//!    the ledger row. The release path calls these instead of the bare
//!    `cargo`/`publish` engines so a run is reversible:
//!      - [`record_bump`]       wraps `apply_bump_plan`
//!      - [`record_skew_bumps`] wraps `apply_skew_bumps`
//!      - [`record_patch_strip`]wraps `strip_patch_crates_io`
//!      - [`record_branch`]     records a branch cut (capturing prev HEAD)
//!      - [`record_publish`]    records a publish (immutable = crates.io)
//!
//!  * the UNDO engine — read a run's records newest-first and reverse each:
//!    un-bump (restore the exact pre-bump manifest text), restore the stripped
//!    `[patch]` block, delete/restore the branch (back to `prev_head`); a
//!    crates.io `publish` can't be un-published, so it is YANKED and reported.
//!
//! Rides on the existing time-travel + `guard`/revert ethos: the ledger is the
//! durable, SHA-keyed source of truth, so undo works even across a fresh process.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result};

use crate::release::cargo::{
    apply_bump_plan, apply_skew_bumps, AppliedBump, VersionBumpPlan,
};
use crate::warehouse::iceberg::IcebergWarehouse;
use crate::warehouse::release_changes::{
    self, ChangeKind, ChangeRecorder, ReleaseChange,
};

// ─────────────────────── record wrappers ───────────────────────

/// Apply a version-bump plan, recording one reversible `Bump` row per touched
/// manifest WITH the exact pre-bump file text (so undo restores it byte-for-byte).
/// Returns the count of files modified (same as [`apply_bump_plan`]).
///
/// The before-text is captured per-file BEFORE the apply; the plan's `pkg` /
/// `old_version` / `new_version` describe the logical change. One record per file
/// is enough to fully reverse the bump (the whole manifest is restored).
pub fn record_bump(
    wh: &IcebergWarehouse,
    rec: &ChangeRecorder,
    repo: &str,
    plan: &VersionBumpPlan,
) -> Result<usize> {
    // Capture the before-text of every file the plan touches.
    let mut files: BTreeMap<PathBuf, String> = BTreeMap::new();
    for e in &plan.edits {
        if let std::collections::btree_map::Entry::Vacant(slot) =
            files.entry(e.cargo_toml.clone())
        {
            let text = std::fs::read_to_string(&e.cargo_toml)
                .with_context(|| format!("read before-state {}", e.cargo_toml.display()))?;
            slot.insert(text);
        }
    }
    // Apply.
    let n = apply_bump_plan(plan)?;
    // Record one row per file (carrying a representative crate/version from that
    // file's edits + the full before-text).
    for (path, before) in &files {
        let edit = plan.edits.iter().find(|e| &e.cargo_toml == path);
        let (crate_name, old_v, new_v) = edit
            .map(|e| (e.pkg.clone(), e.old_version.clone(), e.new_version.clone()))
            .unwrap_or_default();
        rec.record(
            wh,
            repo,
            ChangeKind::Bump {
                crate_name,
                old_version: old_v,
                new_version: new_v,
                file: path.to_string_lossy().into_owned(),
                old_file_text: before.clone(),
            },
        )?;
    }
    Ok(n)
}

/// Apply the doctor's skew bumps, recording a reversible `Bump` row per touched
/// manifest. Reuses [`apply_skew_bumps`] under the hood but captures before-state
/// per (repo, crate) plan so undo can restore each file.
pub fn record_skew_bumps(
    wh: &IcebergWarehouse,
    rec: &ChangeRecorder,
    skew: &[crate::release::doctor::CrateSkew],
    repo_paths: &BTreeMap<String, PathBuf>,
) -> Result<Vec<AppliedBump>> {
    // Re-plan per (repo, crate) so we can capture before-text; mirror the loop in
    // `apply_skew_bumps` but route each plan through `record_bump`.
    let mut applied = Vec::new();
    for c in skew {
        for repo in c.bump_repos() {
            let Some(root) = repo_paths.get(repo) else { continue };
            let plan = crate::release::cargo::plan_version_bump(root, &c.crate_name, &c.target, false)
                .with_context(|| format!("plan bump {}{} in {repo}", c.crate_name, c.target))?;
            if plan.edits.is_empty() {
                continue;
            }
            let files = record_bump(wh, rec, repo, &plan)
                .with_context(|| format!("apply+record bump {}{} in {repo}", c.crate_name, c.target))?;
            applied.push(AppliedBump {
                repo: repo.to_string(),
                crate_name: c.crate_name.clone(),
                target: c.target.clone(),
                files,
            });
        }
    }
    Ok(applied)
}

/// Record an ALREADY-APPLIED version bump for undo — captures the pre-bump file text
/// directly, WITHOUT re-applying a plan. Used by the unified-workspace bump
/// ([`crate::release::cargo::bump_workspace_version`]), whose edit (the virtual root's
/// `[workspace.package].version`) the generic plan-replay path can't reconstruct (no
/// `[package].version`). `edits` is `(manifest, before_text)`.
pub fn record_applied_bump(
    wh: &IcebergWarehouse,
    rec: &ChangeRecorder,
    repo: &str,
    crate_name: &str,
    old_version: &str,
    new_version: &str,
    edits: &[(PathBuf, String)],
) -> Result<()> {
    for (path, before) in edits {
        rec.record(
            wh,
            repo,
            ChangeKind::Bump {
                crate_name: crate_name.to_string(),
                old_version: old_version.to_string(),
                new_version: new_version.to_string(),
                file: path.to_string_lossy().into_owned(),
                old_file_text: before.clone(),
            },
        )?;
    }
    Ok(())
}

/// Strip the `[patch.crates-io]` block(s) from one manifest, recording the removed
/// text so undo can re-append it. Returns the number of blocks stripped. Captures
/// the before-text, computes the diff (the lost lines) as `removed_block`.
pub fn record_patch_strip(
    wh: &IcebergWarehouse,
    rec: &ChangeRecorder,
    repo: &str,
    cargo_toml: &Path,
) -> Result<usize> {
    let before = std::fs::read_to_string(cargo_toml)
        .with_context(|| format!("read before-state {}", cargo_toml.display()))?;
    let n = crate::release::cargo::strip_patch_crates_io(cargo_toml)?;
    if n == 0 {
        return Ok(0);
    }
    let after = std::fs::read_to_string(cargo_toml).unwrap_or_default();
    // The removed block = the lines present in `before` but not in `after`. A
    // strip only ever removes lines (formatting outside the block is preserved),
    // so the suffix-difference is exactly the patch text we must restore. We store
    // the WHOLE before-text under `removed_block` so undo is a verbatim restore —
    // simplest and guaranteed byte-correct.
    let _ = after;
    rec.record(
        wh,
        repo,
        ChangeKind::PatchStrip {
            file: cargo_toml.to_string_lossy().into_owned(),
            removed_block: before,
        },
    )?;
    Ok(n)
}

/// Record a release-branch cut (the branch is created by the caller). `prev_head`
/// is the SHA HEAD pointed at before the cut (empty when the branch is brand new
/// → undo deletes it; otherwise undo resets it back).
pub fn record_branch(
    wh: &IcebergWarehouse,
    rec: &ChangeRecorder,
    repo: &str,
    branch: &str,
    prev_head: &str,
) -> Result<()> {
    rec.record(
        wh,
        repo,
        ChangeKind::Branch {
            repo: repo.to_string(),
            branch: branch.to_string(),
            prev_head: prev_head.to_string(),
        },
    )
}

/// Record a publish. `immutable` must be true for crates.io (undo → yank, never
/// un-publish) and false for a /sparring rehearsal (a no-op to undo).
pub fn record_publish(
    wh: &IcebergWarehouse,
    rec: &ChangeRecorder,
    repo: &str,
    crate_name: &str,
    version: &str,
    registry: &str,
    immutable: bool,
) -> Result<()> {
    rec.record(
        wh,
        repo,
        ChangeKind::Publish {
            crate_name: crate_name.to_string(),
            version: version.to_string(),
            registry: registry.to_string(),
            immutable,
        },
    )
}

// ─────────────────────── undo engine ───────────────────────

/// One reversed step, for the report.
#[derive(Debug, Clone)]
pub struct UndoStep {
    pub seq: i64,
    pub kind: String,
    /// What undo did, human-readable.
    pub action: String,
    /// `true` when undo could not fully reverse it (e.g. an immutable publish →
    /// yanked instead).
    pub partial: bool,
}

/// Reverse `release_id`'s records newest-first. `repo_paths` maps a record's
/// `repo` to its on-disk checkout (for the file/branch operations); records whose
/// repo isn't on disk are skipped with a note. `dry_run` reports without acting.
/// `yank` actually runs `cargo yank` for immutable publishes (off → report only).
///
/// Pass `None` for `release_id` to undo the most recent run in the ledger.
pub fn undo_release(
    wh: &IcebergWarehouse,
    release_id: Option<&str>,
    repo_paths: &BTreeMap<String, PathBuf>,
    dry_run: bool,
    yank: bool,
) -> Result<Vec<UndoStep>> {
    let id = match release_id {
        Some(id) => id.to_string(),
        None => wh
            .block_on(release_changes::latest_release_id(wh))?
            .context("release undo: the release_changes ledger is empty (nothing to undo)")?,
    };
    let mut records: Vec<ReleaseChange> =
        wh.block_on(release_changes::query_release_changes(wh, Some(&id)))?;
    if records.is_empty() {
        anyhow::bail!("release undo: no records for release id `{id}`");
    }
    // Reverse newest-first.
    records.sort_by_key(|r| std::cmp::Reverse(r.seq));

    let mut steps = Vec::new();
    for r in &records {
        let step = reverse_one(r, repo_paths, dry_run, yank)?;
        steps.push(step);
    }
    Ok(steps)
}

fn reverse_one(
    r: &ReleaseChange,
    repo_paths: &BTreeMap<String, PathBuf>,
    dry_run: bool,
    yank: bool,
) -> Result<UndoStep> {
    match &r.change {
        ChangeKind::Bump { file, old_file_text, crate_name, new_version, old_version } => {
            let action = format!(
                "un-bump {crate_name} {new_version}{old_version} (restore {file})"
            );
            if !dry_run {
                std::fs::write(file, old_file_text)
                    .with_context(|| format!("restore {file}"))?;
            }
            Ok(UndoStep { seq: r.seq, kind: "bump".into(), action, partial: false })
        }
        ChangeKind::PatchStrip { file, removed_block } => {
            let action = format!("restore [patch.crates-io] in {file}");
            if !dry_run {
                // We stored the whole before-text → a verbatim restore.
                std::fs::write(file, removed_block)
                    .with_context(|| format!("restore patch in {file}"))?;
            }
            Ok(UndoStep { seq: r.seq, kind: "patch_strip".into(), action, partial: false })
        }
        ChangeKind::Branch { repo, branch, prev_head } => {
            let path = repo_paths.get(repo);
            let action = if prev_head.is_empty() {
                format!("delete branch {branch} in {repo} (was freshly created)")
            } else {
                format!("reset branch {branch} in {repo}{prev_head}")
            };
            if !dry_run {
                if let Some(p) = path {
                    if prev_head.is_empty() {
                        // Delete the branch (best-effort; ignore if checked out).
                        let _ = Command::new("git").arg("-C").arg(p)
                            .args(["branch", "-D", branch]).status();
                    } else {
                        let _ = Command::new("git").arg("-C").arg(p)
                            .args(["update-ref", &format!("refs/heads/{branch}"), prev_head])
                            .status();
                    }
                }
            }
            Ok(UndoStep { seq: r.seq, kind: "branch".into(), action, partial: path.is_none() })
        }
        ChangeKind::Publish { crate_name, version, registry, immutable } => {
            if *immutable {
                // crates.io is immutable — can't un-publish. Yank instead.
                let action = format!(
                    "YANK {crate_name}@{version} from {registry} (immutable — cannot un-publish)"
                );
                if !dry_run && yank {
                    let out = Command::new("cargo")
                        .args(["yank", "--version", version, crate_name])
                        .output()
                        .context("spawn cargo yank")?;
                    if !out.status.success() {
                        let stderr = String::from_utf8_lossy(&out.stderr);
                        // Already-yanked is fine.
                        if !stderr.contains("already yanked") {
                            anyhow::bail!("cargo yank {crate_name}@{version} failed: {stderr}");
                        }
                    }
                }
                Ok(UndoStep { seq: r.seq, kind: "publish".into(), action, partial: true })
            } else {
                // A /sparring rehearsal publish is ephemeral — nothing to reverse.
                Ok(UndoStep {
                    seq: r.seq,
                    kind: "publish".into(),
                    action: format!("{crate_name}@{version} was a {registry} rehearsal (no-op)"),
                    partial: false,
                })
            }
        }
    }
}

/// Human-readable undo report.
pub fn format_undo(release_id: &str, steps: &[UndoStep], dry_run: bool) -> String {
    let mut s = String::new();
    let mode = if dry_run { " (dry-run)" } else { "" };
    s.push_str(&format!("nornir release undo{mode} — release {release_id}\n\n"));
    if steps.is_empty() {
        s.push_str("  (nothing to reverse)\n");
        return s;
    }
    for st in steps {
        let mark = if st.partial { "" } else { "" };
        s.push_str(&format!("  {mark} [{:>3}] {}: {}\n", st.seq, st.kind, st.action));
    }
    s
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::release::cargo::plan_version_bump;

    #[test]
    fn bump_record_undo_restores_file_byte_for_byte() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let manifest = root.join("Cargo.toml");
        let original = "[package]\nname = \"x\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\narrow = \"57\"\n";
        std::fs::write(&manifest, original).unwrap();

        let wh = IcebergWarehouse::open(&root.join("wh")).unwrap();
        let rec = ChangeRecorder::new("run-1");

        let plan = plan_version_bump(root, "arrow", "58.3.0", false).unwrap();
        assert!(!plan.edits.is_empty());
        record_bump(&wh, &rec, "x", &plan).unwrap();

        let after = std::fs::read_to_string(&manifest).unwrap();
        assert!(after.contains("arrow = \"58.3.0\""), "bump applied: {after}");
        assert_ne!(after, original);

        let paths: BTreeMap<String, PathBuf> = [("x".to_string(), root.to_path_buf())].into();
        let steps = undo_release(&wh, Some("run-1"), &paths, false, false).unwrap();
        assert!(steps.iter().any(|s| s.kind == "bump"));

        let restored = std::fs::read_to_string(&manifest).unwrap();
        assert_eq!(restored, original, "undo restored the manifest byte-for-byte");
    }

    #[test]
    fn patch_strip_record_undo_restores_block() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let manifest = root.join("Cargo.toml");
        let original = "[package]\nname = \"x\"\nversion = \"0.1.0\"\n\n[dependencies]\niceberg = \"0.9\"\n\n[patch.crates-io]\niceberg = { path = \"../iceberg-arrow58\" }\n";
        std::fs::write(&manifest, original).unwrap();

        let wh = IcebergWarehouse::open(&root.join("wh")).unwrap();
        let rec = ChangeRecorder::new("run-2");

        let n = record_patch_strip(&wh, &rec, "x", &manifest).unwrap();
        assert_eq!(n, 1);
        let stripped = std::fs::read_to_string(&manifest).unwrap();
        assert!(!stripped.contains("[patch.crates-io]"), "patch stripped: {stripped}");

        let paths: BTreeMap<String, PathBuf> = [("x".to_string(), root.to_path_buf())].into();
        let steps = undo_release(&wh, Some("run-2"), &paths, false, false).unwrap();
        assert!(steps.iter().any(|s| s.kind == "patch_strip"));

        let restored = std::fs::read_to_string(&manifest).unwrap();
        assert_eq!(restored, original, "undo restored the [patch] block");
    }

    #[test]
    fn undo_reverses_newest_first_and_immutable_publish_is_partial() {
        let dir = tempfile::tempdir().unwrap();
        let wh = IcebergWarehouse::open(dir.path()).unwrap();
        let rec = ChangeRecorder::new("run-3");
        record_branch(&wh, &rec, "nornir", "release/staging", "abc123").unwrap();
        record_publish(&wh, &rec, "nornir", "nornir", "0.2.0", "crates.io", true).unwrap();

        let paths: BTreeMap<String, PathBuf> = BTreeMap::new();
        let steps = undo_release(&wh, Some("run-3"), &paths, true, false).unwrap();
        // Newest first: publish (seq 1) reversed before branch (seq 0).
        assert_eq!(steps[0].kind, "publish");
        assert!(steps[0].partial, "immutable publish → yank (partial)");
        assert_eq!(steps[1].kind, "branch");
    }

    #[test]
    fn undo_defaults_to_most_recent_run() {
        let dir = tempfile::tempdir().unwrap();
        let wh = IcebergWarehouse::open(dir.path()).unwrap();
        let rec = ChangeRecorder::new("only-run");
        record_branch(&wh, &rec, "r", "b", "").unwrap();
        let paths: BTreeMap<String, PathBuf> = BTreeMap::new();
        // No id → resolves to the latest run.
        let steps = undo_release(&wh, None, &paths, true, false).unwrap();
        assert_eq!(steps.len(), 1);
        assert_eq!(steps[0].kind, "branch");
    }
}