release-kit 0.2.2

A canonical release workflow: a technology-agnostic method, per-technology bindings, and the rk CLI that lands and serves them.
Documentation
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! `rk upgrade`: a landed target takes a newer payload.
//!
//! Three digests decide each file: the baseline the record keeps — the
//! payload as it stood at landing — the bytes on disk now, and this
//! binary's candidate, rendered under the recorded parameters. A
//! `rendered` file nobody touched is rewritten; one the target edited is
//! a conflict, and every conflict is collected before the whole upgrade
//! refuses in one run. There is no merge: the two outcomes are a clean
//! write and a refusal, because a wrong guess in a release workflow is
//! discovered at the next release.

use serde::Serialize;

use crate::cli::upgrade::UpgradeArgs;
use crate::diagnostic::{Diagnostic, Reason};
use crate::digest::Digest;
use crate::error::RkError;
use crate::landing::manifest::{self, Alignment, FileRecord, Manifest};
use crate::landing::{self, Entry, Kind};
use crate::output::Output;
use crate::{embedded, registry};

/// One destination and what the upgrade decided for it.
#[derive(Debug, Serialize)]
struct FileEntry {
    /// The destination, relative to the target.
    path: String,
    /// The kind this payload declares for it.
    kind: &'static str,
    /// `updated`, `unchanged`, `added`, `drift`, `kept`, `dropped`,
    /// `state`, or `conflict`.
    action: &'static str,
}

/// The machine form of an upgrade report.
#[derive(Debug, Serialize)]
struct Report {
    /// The shape version of this document.
    schema: &'static str,
    /// `preview` or `apply`.
    mode: &'static str,
    /// The target directory.
    target: String,
    /// The recorded technology.
    tech: String,
    /// The recorded forge.
    forge: String,
    /// The version the record came from.
    from_version: String,
    /// This binary's version.
    to_version: &'static str,
    /// Every destination, with its action.
    files: Vec<FileEntry>,
    /// What plausibly follows.
    next: Vec<String>,
}

/// One decided destination, carried from the decision pass to the write
/// pass and the record rewrite.
struct Decision<'a> {
    entry: Option<&'a Entry>,
    action: &'static str,
    record: FileRecord,
}

/// Upgrade the landed target to this binary's payload.
///
/// # Errors
///
/// Returns a refusal for a missing record, an unknown record schema, a
/// record from a newer binary, a `rendered` destination that is not a
/// regular file, and — on apply — any collected conflict; and
/// [`RkError::Io`] on filesystem failure.
pub fn run(args: &UpgradeArgs) -> Result<(), RkError> {
    let out = Output::new(args.json);
    let mut recorded = load_upgradable(&args.target)?;
    resolve_scopes(&mut recorded, args.scopes.as_deref())?;
    let entries = landing::projection(
        &recorded.tech,
        &recorded.forge,
        &recorded.parameters.repo,
        &recorded.parameters.scopes,
    )?;
    refuse_non_regular(&args.target, &entries)?;

    let (decisions, conflicts) = decide_all(args, &recorded, &entries)?;
    // A file this payload stops shipping is a file the target owns from
    // that moment: left in place, named, and dropped from the record.
    let mut dropped: Vec<String> = Vec::new();
    for file in &recorded.files {
        if !entries
            .iter()
            .any(|entry| entry.destination == file.destination)
        {
            dropped.push(file.destination.clone());
        }
    }

    if args.apply && !conflicts.is_empty() {
        return Err(refuse_conflicts(&conflicts));
    }

    let mut sentinels: Vec<String> = Vec::new();
    for decision in &decisions {
        if args.apply && matches!(decision.action, "updated" | "added") {
            if let Some(entry) = decision.entry {
                landing::write_destination(&args.target, entry)?;
                collect_sentinels(entry, &mut sentinels);
            }
        }
        out.result_line(match decision.action {
            "drift" => format!(
                "drift {} (seeded, target-owned)",
                decision.record.destination
            ),
            "kept" => format!("kept {} (target-owned)", decision.record.destination),
            "conflict" => format!(
                "conflict {} (edited, release-kit-owned)",
                decision.record.destination
            ),
            action => format!("{action} {}", decision.record.destination),
        });
    }
    for path in &dropped {
        out.result_line(format!(
            "dropped {path} (no longer shipped; now target-owned)"
        ));
    }

    if args.apply {
        rewrite_record(&args.target, &recorded, &decisions)?;
        out.result_line(format!("rewrote {}", manifest::MANIFEST_PATH));
        for sentinel in &sentinels {
            out.result_line(format!("fill this sentinel: {sentinel}"));
        }
    }

    let next = next_lines(args, conflicts.is_empty());
    out.next(&next);
    out.emit(&Report {
        schema: "rk.upgrade/1",
        mode: if args.apply { "apply" } else { "preview" },
        target: args.target.to_string(),
        tech: recorded.tech.clone(),
        forge: recorded.forge.clone(),
        from_version: recorded.rk_version.clone(),
        to_version: env!("CARGO_PKG_VERSION"),
        files: decisions
            .iter()
            .map(|decision| FileEntry {
                path: decision.record.destination.clone(),
                kind: decision.record.kind.as_str(),
                action: decision.action,
            })
            .chain(dropped.iter().map(|path| FileEntry {
                path: path.clone(),
                kind: "dropped",
                action: "dropped",
            }))
            .collect(),
        next,
    })
}

/// The collect-then-refuse conflict answer: the whole list in one run, so
/// an operator resolves everything and re-runs once.
fn refuse_conflicts(conflicts: &[String]) -> RkError {
    RkError::refusal(
        Diagnostic::new(
            Reason::StateDrift,
            format!(
                "these files release-kit owns were edited, and nothing was written: {}",
                conflicts.join(", ")
            ),
        )
        .expected("every rendered file as the record left it")
        .action("resolve each, or re-land it, then run 'rk upgrade' again")
        .target_state("unchanged"),
    )
}

/// The `Next:` lines for each outcome.
fn next_lines(args: &UpgradeArgs, clean: bool) -> Vec<String> {
    if args.apply {
        vec![
            "commit the upgraded files, the record included".to_owned(),
            format!("rk status --target {} reports the result", args.target),
        ]
    } else if clean {
        vec![format!(
            "rk upgrade --target {} --apply writes",
            args.target
        )]
    } else {
        vec![format!(
            "resolve each conflict above; rk upgrade --target {} --apply refuses until then",
            args.target
        )]
    }
}

/// The record after a successful apply, rewritten whole: new version, new
/// digests, new pins; the first landing's instant, origin, and parameters
/// are preserved.
fn rewrite_record(
    target: &camino::Utf8Path,
    recorded: &Manifest,
    decisions: &[Decision],
) -> Result<(), RkError> {
    manifest::write(
        target,
        &Manifest {
            schema_version: manifest::SCHEMA_VERSION,
            rk_version: env!("CARGO_PKG_VERSION").to_owned(),
            payload_sha256: crate::commands::payload::report().payload_sha256,
            origin: recorded.origin.clone(),
            tech: recorded.tech.clone(),
            forge: recorded.forge.clone(),
            landed_at: recorded.landed_at.clone(),
            parameters: manifest::Parameters {
                repo: recorded.parameters.repo.clone(),
                scopes: recorded.parameters.scopes.clone(),
            },
            files: decisions
                .iter()
                .map(|decision| clone_record(&decision.record))
                .collect(),
            pins: registry::pins_for(&recorded.tech)
                .into_iter()
                .map(|pin| (pin.name, pin.version))
                .collect(),
        },
    )
}

/// The record an upgrade may act on: present, at a known schema, and not
/// from a newer binary than this one.
fn load_upgradable(target: &camino::Utf8Path) -> Result<Manifest, RkError> {
    let Some(recorded) = manifest::load(target)? else {
        return Err(RkError::refusal(
            Diagnostic::new(
                Reason::StateDrift,
                format!(
                    "no {} at {target}: there is no baseline to upgrade against",
                    manifest::MANIFEST_PATH
                ),
            )
            .expected("a recorded landing")
            .action(
                "rk init lands a first landing; rk adopt records one made before the record existed",
            )
            .target_state("unchanged"),
        ));
    };
    if manifest::alignment(&recorded.rk_version, env!("CARGO_PKG_VERSION"))
        == Alignment::TargetNewer
    {
        return Err(RkError::refusal(
            Diagnostic::new(
                Reason::StateDrift,
                format!(
                    "this landing came from rk {}, newer than this binary's {}; downgrading a target is not an upgrade",
                    recorded.rk_version,
                    env!("CARGO_PKG_VERSION")
                ),
            )
            .expected("a binary at or above the recorded rk_version")
            .action(format!("install release-kit {} or newer", recorded.rk_version))
            .target_state("unchanged"),
        ));
    }
    Ok(recorded)
}

/// Decide one candidate destination from the three digests.
/// Every entry decided in one pass, with the collected conflicts. An
/// ill-formed hook file is a conflict in preview and apply alike: its
/// first block may match while a duplicate still executes, so the
/// per-entry comparison cannot see it, and the refusal names each
/// conflict once.
fn decide_all<'a>(
    args: &UpgradeArgs,
    recorded: &'a Manifest,
    entries: &'a [Entry],
) -> Result<(Vec<Decision<'a>>, Vec<String>), RkError> {
    let mut conflicts: Vec<String> = Vec::new();
    let mut decisions: Vec<Decision<'a>> = Vec::new();
    if landing::hooks_file_defect(&args.target)?.is_some() {
        conflicts.push(landing::HOOKS_DESTINATION.to_owned());
    }
    for entry in entries {
        let disk = landing::read_recorded(&args.target, &entry.destination)?;
        let mut decision = decide(
            entry,
            recorded.file(&entry.destination),
            disk.as_deref(),
            &mut conflicts,
        );
        if entry.destination == landing::HOOKS_DESTINATION
            && conflicts.iter().any(|c| c == landing::HOOKS_DESTINATION)
        {
            decision.action = "conflict";
        }
        decisions.push(decision);
    }
    let mut seen = std::collections::HashSet::new();
    conflicts.retain(|conflict| seen.insert(conflict.clone()));
    Ok((decisions, conflicts))
}

fn decide<'a>(
    entry: &'a Entry,
    recorded: Option<&FileRecord>,
    disk: Option<&[u8]>,
    conflicts: &mut Vec<String>,
) -> Decision<'a> {
    let candidate_record = |sha256: Digest| FileRecord {
        destination: entry.destination.clone(),
        kind: entry.kind,
        sha256,
        baseline_sha256: match entry.kind {
            Kind::State => None,
            Kind::Rendered | Kind::Seeded => Some(Digest::of(&entry.baseline)),
        },
    };
    let Some(recorded) = recorded else {
        return decide_added(entry, disk, conflicts);
    };

    // A seeded file this payload reclassifies as rendered claims
    // ownership of a file the target may have tuned; only untouched bytes
    // — matching the recorded baseline — permit the claim.
    if recorded.kind == Kind::Seeded && entry.kind == Kind::Rendered {
        let untouched =
            disk.is_some_and(|bytes| Some(Digest::of(bytes)) == recorded.baseline_sha256);
        if !untouched {
            conflicts.push(entry.destination.clone());
            return Decision {
                entry: Some(entry),
                action: "conflict",
                record: candidate_record(Digest::of(&entry.rendered)),
            };
        }
        return Decision {
            entry: Some(entry),
            action: "updated",
            record: candidate_record(Digest::of(&entry.rendered)),
        };
    }

    match entry.kind {
        Kind::Rendered => match disk {
            Some(bytes) if Digest::of(bytes) == recorded.sha256 => Decision {
                entry: Some(entry),
                action: if bytes == entry.rendered {
                    "unchanged"
                } else {
                    "updated"
                },
                record: candidate_record(Digest::of(&entry.rendered)),
            },
            Some(bytes) if bytes == entry.rendered => Decision {
                entry: Some(entry),
                action: "unchanged",
                record: candidate_record(Digest::of(&entry.rendered)),
            },
            // Edited or deleted: either way the target changed a file
            // release-kit owns.
            _ => {
                conflicts.push(entry.destination.clone());
                Decision {
                    entry: Some(entry),
                    action: "conflict",
                    record: candidate_record(Digest::of(&entry.rendered)),
                }
            }
        },
        Kind::Seeded => {
            // Never written; the record keeps the target's current bytes
            // and the baseline it tunes away from. For a file this payload
            // reclassifies from rendered to seeded — safe and silent — that
            // baseline is the rendered bytes release-kit last wrote, not
            // the pre-substitution payload, so an untouched file is not
            // reported as drift.
            let baseline = if recorded.kind == Kind::Rendered {
                Some(recorded.sha256.clone())
            } else {
                recorded.baseline_sha256.clone()
            };
            let (action, sha256) = disk.map_or_else(
                || ("drift", recorded.sha256.clone()),
                |bytes| {
                    let digest = Digest::of(bytes);
                    if Some(&digest) == baseline.as_ref() {
                        ("unchanged", digest)
                    } else {
                        ("drift", digest)
                    }
                },
            );
            Decision {
                entry: None,
                action,
                record: FileRecord {
                    destination: entry.destination.clone(),
                    kind: entry.kind,
                    sha256,
                    baseline_sha256: baseline,
                },
            }
        }
        Kind::State => Decision {
            entry: None,
            action: "state",
            record: FileRecord {
                destination: entry.destination.clone(),
                kind: entry.kind,
                sha256: recorded.sha256.clone(),
                baseline_sha256: None,
            },
        },
    }
}

/// A destination the record does not name, added by this payload: it
/// lands exactly as `rk init` lands it — a differing `rendered`
/// destination is a conflict, a differing `seeded` or `state` one is the
/// target's and is kept.
fn decide_added<'a>(
    entry: &'a Entry,
    disk: Option<&[u8]>,
    conflicts: &mut Vec<String>,
) -> Decision<'a> {
    let (action, sha256) = match disk {
        None => ("added", Digest::of(&entry.rendered)),
        Some(bytes) if bytes == entry.rendered => ("unchanged", Digest::of(bytes)),
        Some(bytes) if entry.kind != Kind::Rendered => ("kept", Digest::of(bytes)),
        Some(_) => {
            conflicts.push(entry.destination.clone());
            ("conflict", Digest::of(&entry.rendered))
        }
    };
    Decision {
        entry: Some(entry),
        action,
        record: FileRecord {
            destination: entry.destination.clone(),
            kind: entry.kind,
            sha256,
            baseline_sha256: match entry.kind {
                Kind::State => None,
                Kind::Rendered | Kind::Seeded => Some(Digest::of(&entry.baseline)),
            },
        },
    }
}

/// A `rendered` destination that exists and is not a regular file refuses
/// before anything is read.
fn refuse_non_regular(target: &camino::Utf8Path, entries: &[Entry]) -> Result<(), RkError> {
    for entry in entries {
        if entry.kind != Kind::Rendered {
            continue;
        }
        let path = target.join(&entry.destination);
        if let Ok(meta) = std::fs::symlink_metadata(&path) {
            if !meta.is_file() {
                return Err(RkError::refusal(
                    Diagnostic::new(
                        Reason::StateDrift,
                        format!("{path} exists and is not a regular file; nothing was written"),
                    )
                    .expected("every rendered destination a regular file")
                    .target_state("unchanged"),
                ));
            }
        }
    }
    Ok(())
}

/// The judgment sentinels a newly written file carries.
fn collect_sentinels(entry: &Entry, found: &mut Vec<String>) {
    let text = String::from_utf8_lossy(&entry.rendered);
    for (idx, line) in text.lines().enumerate() {
        if line.contains(embedded::SENTINEL) {
            found.push(format!(
                "{}:{}: {}",
                entry.destination,
                idx + 1,
                line.trim()
            ));
        }
    }
}

/// [`FileRecord`] carries digests, which are cheap to clone by field.
fn clone_record(record: &FileRecord) -> FileRecord {
    FileRecord {
        destination: record.destination.clone(),
        kind: record.kind,
        sha256: record.sha256.clone(),
        baseline_sha256: record.baseline_sha256.clone(),
    }
}

/// The scope parameter comes from the record; a record from before the
/// parameter existed takes `--scopes` once, and the rewrite records it.
fn resolve_scopes(recorded: &mut Manifest, raw: Option<&str>) -> Result<(), RkError> {
    if let Some(raw) = raw {
        recorded.parameters.scopes = landing::parse_scopes(raw)?;
    }
    if recorded.parameters.scopes.is_empty() {
        return Err(RkError::Usage(
            "the record carries no scopes parameter; pass --scopes <list>, the Conventional Commit scopes this project accepts, and the upgrade records it".into(),
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]

    use super::{FileEntry, Report};

    /// The complete `rk.upgrade/1` shape, held by snapshot.
    #[test]
    fn the_upgrade_report_schema_snapshot_holds() {
        let report = Report {
            schema: "rk.upgrade/1",
            mode: "preview",
            target: "/tmp/t".into(),
            tech: "rust".into(),
            forge: "github".into(),
            from_version: "0.1.0".into(),
            to_version: "0.2.0",
            files: vec![FileEntry {
                path: "release-plz.toml".into(),
                kind: "seeded",
                action: "drift",
            }],
            next: vec!["rk upgrade --target /tmp/t --apply writes".into()],
        };
        assert_eq!(
            serde_json::to_string(&report).expect("a report serializes"),
            r#"{"schema":"rk.upgrade/1","mode":"preview","target":"/tmp/t","tech":"rust","forge":"github","from_version":"0.1.0","to_version":"0.2.0","files":[{"path":"release-plz.toml","kind":"seeded","action":"drift"}],"next":["rk upgrade --target /tmp/t --apply writes"]}"#
        );
    }
}