Skip to main content

release_kit/commands/
migrate.rs

1//! `rk migrate`: carry a target off another release tool through an
2//! archive and a greenfield landing.
3//!
4//! `inventory` lists what the archive moves. `archive` moves every
5//! predecessor file into a workspace under the state root, snapshots what
6//! no Git holds, writes the registry, and names the open migration in the
7//! committed configuration; `--rebuild` recreates the archived files from
8//! Git on a clone whose workspace is gone. `mark` records the map and the
9//! loop, `status` reads the registry back, and `close` ends the migration
10//! once nothing is unfinished and the setup proof is current. Every verb
11//! that writes the target previews by default.
12//!
13//! SATISFIES migration:an-archive-moves-only-committed-files
14//! SATISFIES migration:the-configuration-names-the-open-migration
15
16use std::path::{Path, PathBuf};
17
18use camino::{Utf8Path, Utf8PathBuf};
19use serde::Serialize;
20
21use crate::cli::migrate::{MigrateAction, MigrateArgs};
22use crate::commands::setup::{self as setup_cmd, ForgeSnapshot};
23use crate::diagnostic::{Diagnostic, Reason};
24use crate::digest::Digest;
25use crate::error::RkError;
26use crate::landing::manifest;
27use crate::migrate::inventory::{self, Entry, Placement};
28use crate::migrate::registry::{
29    self, HistoryEntry, Integrity, Mark, Marked, Registry, Snapshot, Source, Status,
30};
31use crate::migrate::{self, git};
32use crate::output::Output;
33use crate::snapshot::Snapshot as Saved;
34
35/// Route one `rk migrate` invocation.
36///
37/// # Errors
38///
39/// Each verb's own refusals; every failure is typed.
40pub fn run(args: &MigrateArgs) -> Result<(), RkError> {
41    crate::requirements::require("rk migrate", &[crate::requirements::Tool::Git])?;
42    match &args.action {
43        MigrateAction::Inventory { target, json } => inventory(target, Output::new(*json)),
44        MigrateAction::Archive {
45            target,
46            apply,
47            rebuild,
48            json,
49        } => {
50            if *rebuild {
51                rebuild_sources(target, *apply, Output::new(*json))
52            } else {
53                archive(target, *apply, Output::new(*json))
54            }
55        }
56        MigrateAction::Mark {
57            name,
58            status,
59            group,
60            tags,
61            destinations,
62            reason,
63            target,
64            json,
65        } => mark(
66            target,
67            &Mark {
68                name,
69                status: Some(Status::parse(status)?),
70                group: group.as_deref(),
71                tags,
72                destinations,
73                reason: reason.as_deref(),
74            },
75            Output::new(*json),
76        ),
77        MigrateAction::Status { target, json } => status(target, Output::new(*json)),
78        MigrateAction::Close {
79            target,
80            apply,
81            json,
82        } => close(target, *apply, Output::new(*json)),
83    }
84}
85
86/// The target's canonical path, or the refusal for one that is not a
87/// directory.
88fn canonical(target: &Utf8Path) -> Result<PathBuf, RkError> {
89    if !target.is_dir() {
90        return Err(RkError::missing(
91            Diagnostic::new(
92                Reason::TargetNotFound,
93                format!("{target} is not a directory"),
94            )
95            .expected("an existing repository"),
96        ));
97    }
98    Ok(std::fs::canonicalize(target.as_std_path())?)
99}
100
101/// The workspace path of migration `id`, or the refusal where no state
102/// root resolves.
103fn workspace_of(canonical: &Path, id: &str) -> Result<Utf8PathBuf, RkError> {
104    Ok(runs_of(canonical)?.join(id))
105}
106
107/// The directory of every workspace at this target, or the refusal where
108/// no state root resolves.
109fn runs_of(canonical: &Path) -> Result<Utf8PathBuf, RkError> {
110    migrate::runs(canonical)
111        .and_then(|path| Utf8PathBuf::from_path_buf(path).ok())
112        .ok_or_else(|| {
113            RkError::refusal(
114                Diagnostic::new(
115                    Reason::PrerequisiteUnmet,
116                    "no state root resolves, so the migration has no workspace, and nothing was written",
117                )
118                .expected("a state root under XDG_STATE_HOME or HOME")
119                .target_state("unchanged"),
120            )
121        })
122}
123
124/// The open migration's id and workspace, and its registry.
125fn open(target: &Utf8Path) -> Result<(String, Utf8PathBuf, Registry), RkError> {
126    let canonical = canonical(target)?;
127    let id = migrate::open_id(target)?.ok_or_else(migrate::none_open)?;
128    let workspace = workspace_of(&canonical, &id)?;
129    if !workspace.join(migrate::REGISTRY_FILE).is_file() {
130        return Err(migrate::workspace_missing(&id, &workspace));
131    }
132    let registry = registry::load(&workspace)?;
133    Ok((id, workspace, registry))
134}
135
136/// The inventory report.
137#[derive(Debug, Serialize)]
138struct InventoryReport {
139    schema: &'static str,
140    target: String,
141    files: Vec<Entry>,
142    next: Vec<String>,
143}
144
145fn inventory(target: &Utf8PathBuf, out: Output) -> Result<(), RkError> {
146    canonical(target)?;
147    let files = inventory::scan(target)?;
148    for entry in &files {
149        match entry.placement {
150            Placement::Archived => out.result_line(format!(
151                "archive {} ({}, {})",
152                entry.path,
153                entry.tool,
154                entry.kind.as_str()
155            )),
156            Placement::InPlace => out.result_line(format!("in place {}", entry.path)),
157        }
158    }
159    if !files
160        .iter()
161        .any(|entry| entry.placement == Placement::Archived)
162    {
163        out.result_line("no predecessor file is listed here");
164    }
165    let next = vec![format!(
166        "rk migrate archive --target {target} previews the move"
167    )];
168    out.next(&next);
169    out.emit(&InventoryReport {
170        schema: migrate::SCHEMA,
171        target: target.to_string(),
172        files,
173        next,
174    })
175}
176
177/// One destructive step's forge snapshot, in a report.
178#[derive(Debug, Serialize)]
179struct ForgeRow {
180    step: String,
181    /// `taken` or `unknown`.
182    state: &'static str,
183    #[serde(skip_serializing_if = "Option::is_none")]
184    file: Option<String>,
185    #[serde(skip_serializing_if = "Option::is_none")]
186    detail: Option<String>,
187}
188
189/// The archive report.
190#[derive(Debug, Serialize)]
191struct ArchiveReport {
192    schema: &'static str,
193    /// `preview` for an archive or a rebuild that writes nothing, else
194    /// `apply`, `resume`, or `rebuild`.
195    mode: &'static str,
196    target: String,
197    id: String,
198    workspace: String,
199    base_commit: String,
200    archived: Vec<String>,
201    in_place: Vec<String>,
202    snapshots: Vec<String>,
203    forge: Vec<ForgeRow>,
204    next: Vec<String>,
205}
206
207/// The kind of a forge snapshot in the registry.
208const FORGE_STATE: &str = "forge-state";
209
210/// A refusal that leaves the target unchanged.
211fn refused(reason: Reason, message: String, expected: &str, action: Option<String>) -> RkError {
212    let mut diagnostic = Diagnostic::new(reason, message)
213        .expected(expected)
214        .target_state("unchanged");
215    if let Some(action) = action {
216        diagnostic = diagnostic.action(action);
217    }
218    RkError::refusal(diagnostic)
219}
220
221#[allow(
222    clippy::too_many_lines,
223    reason = "the archive is one ordered sequence of checks and writes, and splitting it would separate a write from the check that licensed it"
224)]
225fn archive(target: &Utf8PathBuf, apply: bool, out: Output) -> Result<(), RkError> {
226    let canonical = canonical(target)?;
227    if let Some(id) = migrate::open_id(target)? {
228        if apply {
229            return resume(target, &canonical, &id, out);
230        }
231        return Err(refused(
232            Reason::PrerequisiteUnmet,
233            format!(
234                "the migration {id} is already open; read it with rk migrate status (migration:the-configuration-names-the-open-migration)"
235            ),
236            "one open migration per target",
237            Some(format!(
238                "rk migrate archive --apply --target {target} takes the forge snapshots it still misses"
239            )),
240        ));
241    }
242    if manifest::load(target)?.is_some() {
243        return Err(refused(
244            Reason::PrerequisiteUnmet,
245            "this target carries a landing record, so it is upgraded or adopted rather than migrated (migration:an-archive-moves-only-committed-files)".to_owned(),
246            "a target another release tool drives, with no landing record",
247            Some(format!("rk status --target {target} names its classification")),
248        ));
249    }
250    let trunk = crate::config::trunk_of(target.as_std_path())?;
251    let trunk_ref = format!("refs/heads/{trunk}^{{commit}}");
252    let head = git::run(
253        target,
254        &["rev-parse", "--verify", "--quiet", trunk_ref.as_str()],
255    )?;
256    if !head.status.success() {
257        return Err(refused(
258            Reason::PrerequisiteUnmet,
259            format!(
260                "{target} has no local branch {trunk} with a commit, and the archive reads every listed file from the trunk (migration:an-archive-moves-only-committed-files)"
261            ),
262            "the trunk git.trunk names, as a local branch with at least one commit",
263            Some(format!(
264                "set git.trunk in {} to the trunk's branch name",
265                crate::config::CONFIG_PATH
266            )),
267        ));
268    }
269    let base_commit = String::from_utf8_lossy(&head.stdout).trim().to_owned();
270    let entries = inventory::scan(target)?;
271    let archived: Vec<&Entry> = entries
272        .iter()
273        .filter(|entry| entry.placement == Placement::Archived)
274        .collect();
275    if archived.is_empty() {
276        return Err(refused(
277            Reason::PrerequisiteUnmet,
278            format!(
279                "the inventory lists no predecessor file at {target}, so there is nothing to archive"
280            ),
281            "a predecessor release tool's files",
282            Some(format!(
283                "rk status --target {target} names its classification"
284            )),
285        ));
286    }
287    // The trunk must hold every listed file's exact bytes, unfiltered, and
288    // no listed file the target lacks: a rebuild reads the files back from
289    // the trunk, so an ignored, uncommitted, or unintegrated file, one a
290    // filter converts, and an unintegrated deletion all refuse here.
291    let known: Vec<&str> = inventory::PREDECESSORS
292        .iter()
293        .map(|(path, _, _)| *path)
294        .chain(inventory::ROOT_FILES)
295        .collect();
296    let blobs = git::regular_blobs(target, &base_commit, &known)?;
297    let paths: Vec<&str> = entries.iter().map(|entry| entry.path.as_str()).collect();
298    let raw = git::raw_blob_ids(target, &paths)?;
299    let mut differing: Vec<&str> = paths
300        .iter()
301        .zip(&raw)
302        .filter(|(path, oid)| blobs.get(**path) != Some(*oid))
303        .map(|(path, _)| *path)
304        .collect();
305    let on_trunk: Vec<&str> = blobs.keys().map(String::as_str).collect();
306    differing.extend(
307        inventory::listed(&on_trunk)
308            .into_iter()
309            .filter(|path| !paths.contains(path)),
310    );
311    if !differing.is_empty() {
312        return Err(refused(
313            Reason::StateDrift,
314            format!(
315                "these files differ from the trunk's copy on {trunk}: {}; integrate their edits onto the trunk, then run the archive again (migration:an-archive-moves-only-committed-files)",
316                differing.join(", ")
317            ),
318            "every listed file's bytes equal to its copy on the trunk, so Git holds the bytes the archive moves",
319            None,
320        ));
321    }
322    crate::config::check_writable(target.as_std_path())?;
323    let now = std::time::SystemTime::now();
324    let stamp = migrate::stamp(now);
325    let runs = runs_of(&canonical)?;
326    // The apply claims its workspace exclusively, and a preview reads the
327    // name that claim would take, writing nothing.
328    let (id, workspace) = if apply {
329        let (id, _) = migrate::claim(runs.as_std_path(), &stamp)?;
330        let workspace = runs.join(&id);
331        (id, workspace)
332    } else {
333        let id = migrate::free_id(runs.as_std_path(), &stamp);
334        let workspace = runs.join(&id);
335        (id, workspace)
336    };
337    let archived_paths: Vec<String> = archived.iter().map(|entry| entry.path.clone()).collect();
338    let in_place: Vec<String> = entries
339        .iter()
340        .filter(|entry| entry.placement == Placement::InPlace)
341        .map(|entry| entry.path.clone())
342        .collect();
343    if !apply {
344        for path in &archived_paths {
345            out.result_line(format!("would archive {path}"));
346        }
347        for path in &in_place {
348            out.result_line(format!("stays in place {path}"));
349        }
350        out.result_line(format!("would open the migration {id} at {workspace}"));
351        let next = vec![format!(
352            "rk migrate archive --apply --target {target} moves the files and opens the migration"
353        )];
354        out.next(&next);
355        return out.emit(&ArchiveReport {
356            schema: migrate::SCHEMA,
357            mode: "preview",
358            target: target.to_string(),
359            id,
360            workspace: workspace.to_string(),
361            base_commit,
362            archived: archived_paths,
363            in_place,
364            snapshots: Vec::new(),
365            forge: Vec::new(),
366            next,
367        });
368    }
369
370    // Copy first, and read each copy back against the checksum the
371    // inventory took, before any file leaves the target.
372    let saved = Saved::at(workspace.clone().into_std_path_buf());
373    for entry in &archived {
374        let bytes = std::fs::read(target.join(&entry.path))?;
375        let path = saved.save(&Path::new(migrate::SOURCES_DIR).join(&entry.path), &bytes)?;
376        if Digest::of(&std::fs::read(&path)?).to_string() != entry.sha256 {
377            return Err(refused(
378                Reason::StateDrift,
379                format!(
380                    "the archived copy of {} does not match the bytes the inventory read; the target is unchanged",
381                    entry.path
382                ),
383                "the same bytes on both sides",
384                None,
385            ));
386        }
387    }
388    let at = migrate::at(now);
389    let mut snapshots = git_snapshots(target, &workspace, &saved, &at)?;
390    let forge = take_forge(target, &workspace, &saved, &at, &[], &mut snapshots);
391    let mut sources: Vec<Source> = entries
392        .iter()
393        .map(|entry| {
394            source_of(
395                &entry.path,
396                &entry.sha256,
397                entry.tool,
398                entry.kind,
399                entry.placement,
400                &at,
401            )
402        })
403        .collect();
404    registry::assign_ids(&mut sources);
405    let registry = Registry {
406        schema_version: registry::SCHEMA_VERSION,
407        id: id.clone(),
408        base_commit: base_commit.clone(),
409        sources,
410        groups: Vec::new(),
411        snapshots,
412    };
413    registry::save(&workspace, &registry)?;
414    for path in &archived_paths {
415        std::fs::remove_file(target.join(path))?;
416        prune_empty_parents(target, path);
417    }
418    crate::config::set_migration(target.as_std_path(), Some(&id))?;
419    for path in &archived_paths {
420        out.result_line(format!("archived {path}"));
421    }
422    for row in &forge {
423        out.result_line(format!(
424            "forge snapshot {}: {}{}",
425            row.step,
426            row.state,
427            row.detail
428                .as_deref()
429                .map_or_else(String::new, |detail| format!(" ({detail})"))
430        ));
431    }
432    out.result_line(format!(
433        "opened the migration {id} at {workspace}; .release-kit/config.toml names it"
434    ));
435    let next = vec![
436        format!("rk init --target {target} previews the greenfield landing"),
437        format!("rk migrate status --target {target} reads the registry"),
438    ];
439    out.next(&next);
440    out.emit(&ArchiveReport {
441        schema: migrate::SCHEMA,
442        mode: "apply",
443        target: target.to_string(),
444        id,
445        workspace: workspace.to_string(),
446        base_commit,
447        archived: archived_paths,
448        in_place,
449        snapshots: registry
450            .snapshots
451            .iter()
452            .map(|snapshot| snapshot.id.clone())
453            .collect(),
454        forge,
455        next,
456    })
457}
458
459/// One registry source, pending since `at`.
460fn source_of(
461    path: &str,
462    sha256: &str,
463    tool: &str,
464    kind: inventory::Kind,
465    placement: Placement,
466    at: &str,
467) -> Source {
468    Source {
469        id: registry::source_id(path),
470        path: path.to_owned(),
471        sha256: sha256.to_owned(),
472        tool: tool.to_owned(),
473        kind,
474        placement,
475        tags: Vec::new(),
476        group: None,
477        status: Status::Pending,
478        history: vec![HistoryEntry {
479            at: at.to_owned(),
480            status: Status::Pending,
481            reason: None,
482        }],
483    }
484}
485
486/// The Git snapshots no clone of the trunk holds: a bundle of every
487/// long-lived branch, and the tag list.
488fn git_snapshots(
489    target: &Utf8Path,
490    workspace: &Utf8Path,
491    saved: &Saved,
492    at: &str,
493) -> Result<Vec<Snapshot>, RkError> {
494    let mut snapshots = Vec::new();
495    let branches: Vec<String> = git::lines(
496        target,
497        &["for-each-ref", "--format=%(refname:short)", "refs/heads"],
498    )?
499    .into_iter()
500    .filter(|branch| {
501        crate::assess::LONG_LIVED_BRANCHES.contains(&branch.as_str())
502            || branch.starts_with("release/")
503    })
504    .collect();
505    if !branches.is_empty() {
506        let relative = format!("{}/branches.bundle", migrate::REFS_DIR);
507        let path = workspace.join(&relative);
508        if let Some(parent) = path.parent() {
509            std::fs::create_dir_all(parent)?;
510        }
511        let mut args = vec!["bundle", "create", path.as_str()];
512        args.extend(branches.iter().map(String::as_str));
513        git::stdout(target, &args)?;
514        snapshots.push(Snapshot {
515            id: "long-lived-branches".to_owned(),
516            kind: "git-bundle".to_owned(),
517            file: relative,
518            sha256: Digest::of(&std::fs::read(&path)?).to_string(),
519            taken_at: at.to_owned(),
520            second_copy: false,
521        });
522    }
523    let tags = git::lines(target, &["tag", "--list"])?;
524    let text = tags.iter().fold(String::new(), |mut text, tag| {
525        text.push_str(tag);
526        text.push('\n');
527        text
528    });
529    let relative = format!("{}/tags.txt", migrate::REFS_DIR);
530    saved.save(Path::new(&relative), text.as_bytes())?;
531    snapshots.push(Snapshot {
532        id: "tag-list".to_owned(),
533        kind: "tag-list".to_owned(),
534        file: relative,
535        sha256: Digest::of(text.as_bytes()).to_string(),
536        taken_at: at.to_owned(),
537        second_copy: false,
538    });
539    Ok(snapshots)
540}
541
542/// Take the forge snapshots still missing, appending each one taken to
543/// `snapshots`; a target whose setup does not resolve reads unknown.
544fn take_forge(
545    target: &Utf8PathBuf,
546    workspace: &Utf8Path,
547    saved: &Saved,
548    at: &str,
549    held: &[String],
550    snapshots: &mut Vec<Snapshot>,
551) -> Vec<ForgeRow> {
552    let taken = match setup_cmd::migration_snapshots(target, saved, held) {
553        Ok(taken) => taken,
554        Err(error) => {
555            return vec![ForgeRow {
556                step: "setup".to_owned(),
557                state: "unknown",
558                file: None,
559                detail: Some(error.to_string()),
560            }];
561        }
562    };
563    let mut rows = Vec::new();
564    for (step, result) in taken {
565        match result {
566            ForgeSnapshot::Taken(path) => {
567                let relative = Utf8PathBuf::from_path_buf(path.clone())
568                    .ok()
569                    .and_then(|path| path.strip_prefix(workspace).ok().map(Utf8Path::to_path_buf))
570                    .map_or_else(|| path.display().to_string(), |path| path.to_string());
571                let sha256 = std::fs::read(&path)
572                    .map(|bytes| Digest::of(&bytes).to_string())
573                    .unwrap_or_default();
574                snapshots.push(Snapshot {
575                    id: setup_cmd::forge_snapshot_id(step),
576                    kind: FORGE_STATE.to_owned(),
577                    file: relative.clone(),
578                    sha256,
579                    taken_at: at.to_owned(),
580                    second_copy: false,
581                });
582                rows.push(ForgeRow {
583                    step: step.to_owned(),
584                    state: "taken",
585                    file: Some(relative),
586                    detail: None,
587                });
588            }
589            ForgeSnapshot::Unknown(detail) => rows.push(ForgeRow {
590                step: step.to_owned(),
591                state: "unknown",
592                file: None,
593                detail: Some(detail),
594            }),
595        }
596    }
597    rows
598}
599
600/// Take the forge snapshots an open migration still misses.
601fn resume(target: &Utf8PathBuf, canonical: &Path, id: &str, out: Output) -> Result<(), RkError> {
602    let workspace = workspace_of(canonical, id)?;
603    if !workspace.join(migrate::REGISTRY_FILE).is_file() {
604        return Err(migrate::workspace_missing(id, &workspace));
605    }
606    let mut registry = registry::load(&workspace)?;
607    let now = std::time::SystemTime::now();
608    // A forge snapshot whose file is gone or altered is no snapshot: it
609    // leaves the registry, an altered file is set aside rather than
610    // destroyed, and this run takes the snapshot again.
611    let stamp = migrate::stamp(now);
612    let mut aside = Vec::new();
613    let mut kept = Vec::new();
614    for snapshot in std::mem::take(&mut registry.snapshots) {
615        let state = if snapshot.kind == FORGE_STATE {
616            registry::integrity(&workspace, &snapshot)?
617        } else {
618            Integrity::Intact
619        };
620        match state {
621            Integrity::Intact => kept.push(snapshot),
622            Integrity::Missing => {}
623            Integrity::Altered => {
624                let moved = workspace.join(format!("{}.altered-{stamp}", snapshot.file));
625                std::fs::rename(workspace.join(&snapshot.file), &moved)?;
626                aside.push(moved);
627            }
628        }
629    }
630    registry.snapshots = kept;
631    let held: Vec<String> = registry
632        .snapshots
633        .iter()
634        .map(|snapshot| snapshot.id.clone())
635        .collect();
636    let saved = Saved::at(workspace.clone().into_std_path_buf());
637    let at = migrate::at(now);
638    let forge = take_forge(
639        target,
640        &workspace,
641        &saved,
642        &at,
643        &held,
644        &mut registry.snapshots,
645    );
646    registry::save(&workspace, &registry)?;
647    for moved in &aside {
648        out.result_line(format!(
649            "set an altered snapshot aside at {moved}; its checksum no longer matched"
650        ));
651    }
652    for row in &forge {
653        out.result_line(format!("forge snapshot {}: {}", row.step, row.state));
654    }
655    if forge.is_empty() {
656        out.result_line(format!(
657            "the migration {id} holds every forge snapshot its destructive steps need"
658        ));
659    }
660    let next = vec![format!(
661        "rk migrate status --target {target} reads the registry"
662    )];
663    out.next(&next);
664    out.emit(&ArchiveReport {
665        schema: migrate::SCHEMA,
666        mode: "resume",
667        target: target.to_string(),
668        id: id.to_owned(),
669        workspace: workspace.to_string(),
670        base_commit: registry.base_commit.clone(),
671        archived: Vec::new(),
672        in_place: Vec::new(),
673        snapshots: registry
674            .snapshots
675            .iter()
676            .map(|snapshot| snapshot.id.clone())
677            .collect(),
678        forge,
679        next,
680    })
681}
682
683/// Remove the directories the archive emptied, up to and never including
684/// the target root.
685fn prune_empty_parents(target: &Utf8Path, path: &str) {
686    let mut current = Utf8Path::new(path).parent();
687    while let Some(dir) = current.filter(|dir| !dir.as_str().is_empty()) {
688        let full = target.join(dir);
689        let empty = std::fs::read_dir(&full).is_ok_and(|mut entries| entries.next().is_none());
690        if !empty || std::fs::remove_dir(&full).is_err() {
691            break;
692        }
693        current = dir.parent();
694    }
695}
696
697/// The commit the archive read its sources from: the first parent of the
698/// oldest commit on `HEAD`'s first-parent history that names the
699/// migration in the configuration. A merge is searched by its diff
700/// against its first parent, so a key a side branch carried in is found
701/// at the merge, whose first parent holds the trunk's bytes, never at the
702/// side commit, whose parent may predate the trunk's later edits.
703fn base_from_history(target: &Utf8Path, id: &str) -> Result<String, RkError> {
704    let needle = format!("-Smigration = \"{id}\"");
705    let commits = git::lines(
706        target,
707        &[
708            "log",
709            "--format=%H",
710            "--reverse",
711            "--first-parent",
712            "--diff-merges=first-parent",
713            needle.as_str(),
714            "--",
715            crate::config::CONFIG_PATH,
716        ],
717    )?;
718    let first = commits.first().ok_or_else(|| {
719        refused(
720            Reason::PrerequisiteUnmet,
721            format!(
722                "no commit names the migration {id} in {}, so the base commit cannot be found (migration:a-rebuild-recreates-the-files-alone)",
723                crate::config::CONFIG_PATH
724            ),
725            "the archive's configuration change committed",
726            None,
727        )
728    })?;
729    let parent = format!("{first}^1");
730    Ok(git::lines(target, &["rev-parse", parent.as_str()])?
731        .into_iter()
732        .next()
733        .unwrap_or_default())
734}
735
736/// SATISFIES migration:a-rebuild-recreates-the-files-alone
737#[allow(
738    clippy::too_many_lines,
739    reason = "one pass reads the base, checks each file against the registry, and writes or previews it"
740)]
741fn rebuild_sources(target: &Utf8PathBuf, apply: bool, out: Output) -> Result<(), RkError> {
742    let canonical = canonical(target)?;
743    let id = migrate::open_id(target)?.ok_or_else(migrate::none_open)?;
744    let workspace = workspace_of(&canonical, &id)?;
745    let existing = if workspace.join(migrate::REGISTRY_FILE).is_file() {
746        Some(registry::load(&workspace)?)
747    } else {
748        None
749    };
750    let base_commit = match &existing {
751        Some(registry) => registry.base_commit.clone(),
752        None => base_from_history(target, &id)?,
753    };
754    // Regular files alone, as the inventory lists them: a symlink or a
755    // submodule at the base is no file the archive took.
756    let blobs = git::regular_blobs(target, &base_commit, &[])?;
757    let paths: Vec<&str> = blobs.keys().map(String::as_str).collect();
758    let saved = Saved::at(workspace.clone().into_std_path_buf());
759    let at = migrate::at(std::time::SystemTime::now());
760    let mut sources = Vec::new();
761    let mut rebuilt = Vec::new();
762    let mut in_place = Vec::new();
763    for path in inventory::listed(&paths) {
764        let Some((tool, kind, placement)) = inventory::classify(path) else {
765            continue;
766        };
767        // With a registry, the archive's own list is the subject, never a
768        // file the base holds that the archive did not take.
769        if existing
770            .as_ref()
771            .is_some_and(|registry| !registry.sources.iter().any(|source| source.path == path))
772        {
773            continue;
774        }
775        let object = format!("{base_commit}:{path}");
776        let bytes = git::stdout(target, &["show", object.as_str()])?;
777        let sha256 = Digest::of(&bytes).to_string();
778        if let Some(registry) = &existing
779            && let Some(source) = registry.sources.iter().find(|source| source.path == path)
780            && source.sha256 != sha256
781        {
782            return Err(refused(
783                Reason::StateDrift,
784                format!(
785                    "{path} at {base_commit} does not match the registry's checksum, and nothing was rebuilt from it"
786                ),
787                "the bytes the archive took",
788                None,
789            ));
790        }
791        match placement {
792            Placement::Archived => {
793                if apply {
794                    saved.save(&Path::new(migrate::SOURCES_DIR).join(path), &bytes)?;
795                }
796                rebuilt.push(path.to_owned());
797            }
798            Placement::InPlace => in_place.push(path.to_owned()),
799        }
800        sources.push(source_of(path, &sha256, tool, kind, placement, &at));
801    }
802    if apply && existing.is_none() {
803        registry::assign_ids(&mut sources);
804        registry::save(
805            &workspace,
806            &Registry {
807                schema_version: registry::SCHEMA_VERSION,
808                id: id.clone(),
809                base_commit: base_commit.clone(),
810                sources,
811                groups: Vec::new(),
812                snapshots: Vec::new(),
813            },
814        )?;
815    }
816    let verb = if apply { "rebuilt" } else { "would rebuild" };
817    for path in &rebuilt {
818        out.result_line(format!("{verb} {path}"));
819    }
820    out.result_line(format!(
821        "{verb} the files of the migration {id} at {workspace} from {base_commit}; a snapshot has no second copy, so none is rebuilt"
822    ));
823    let next = vec![if apply {
824        format!("rk migrate status --target {target} reads the registry")
825    } else {
826        format!("rk migrate archive --rebuild --apply --target {target} writes them")
827    }];
828    out.next(&next);
829    out.emit(&ArchiveReport {
830        schema: migrate::SCHEMA,
831        mode: if apply { "rebuild" } else { "preview" },
832        target: target.to_string(),
833        id,
834        workspace: workspace.to_string(),
835        base_commit,
836        archived: rebuilt,
837        in_place,
838        snapshots: existing
839            .map(|registry| {
840                registry
841                    .snapshots
842                    .into_iter()
843                    .map(|snapshot| snapshot.id)
844                    .collect()
845            })
846            .unwrap_or_default(),
847        forge: Vec::new(),
848        next,
849    })
850}
851
852/// The mark report.
853#[derive(Debug, Serialize)]
854struct MarkReport {
855    schema: &'static str,
856    id: String,
857    status: Status,
858    marked: Marked,
859    next: Vec<String>,
860}
861
862/// SATISFIES migration:a-mark-appends-and-never-rewrites
863fn mark(target: &Utf8PathBuf, request: &Mark<'_>, out: Output) -> Result<(), RkError> {
864    let (id, workspace, mut registry) = open(target)?;
865    let at = migrate::at(std::time::SystemTime::now());
866    let marked = registry.mark(request, &at)?;
867    registry::save(&workspace, &registry)?;
868    let status = request.status.unwrap_or(Status::Pending);
869    out.result_line(format!(
870        "marked {} {} {}: {}",
871        marked.subject,
872        marked.id,
873        status.as_str(),
874        marked.sources.join(", ")
875    ));
876    let next = vec![format!(
877        "rk migrate status --target {target} reads the registry"
878    )];
879    out.next(&next);
880    out.emit(&MarkReport {
881        schema: migrate::SCHEMA,
882        id,
883        status,
884        marked,
885        next,
886    })
887}
888
889/// One source in the status report.
890#[derive(Debug, Serialize)]
891struct SourceRow {
892    id: String,
893    path: String,
894    tool: String,
895    kind: inventory::Kind,
896    placement: Placement,
897    status: Status,
898    #[serde(skip_serializing_if = "Option::is_none")]
899    group: Option<String>,
900    #[serde(skip_serializing_if = "Vec::is_empty")]
901    tags: Vec<String>,
902    /// `same`, `changed`, or `missing`: the bytes now against the
903    /// checksum the archive took.
904    checksum: &'static str,
905}
906
907/// The status report.
908#[derive(Debug, Serialize)]
909struct StatusReport {
910    schema: &'static str,
911    id: String,
912    workspace: String,
913    base_commit: String,
914    sources: Vec<SourceRow>,
915    groups: Vec<registry::Group>,
916    snapshots: Vec<Snapshot>,
917    /// The destructive steps whose forge snapshot the registry lacks.
918    forge_missing: Vec<String>,
919    /// What still blocks the close.
920    blocking: Vec<String>,
921    next: Vec<String>,
922}
923
924/// Where the bytes of one source stand against its checksum.
925fn checksum(target: &Utf8Path, workspace: &Utf8Path, source: &Source) -> &'static str {
926    let path = match source.placement {
927        Placement::Archived => workspace.join(migrate::SOURCES_DIR).join(&source.path),
928        Placement::InPlace => target.join(&source.path),
929    };
930    match std::fs::read(&path) {
931        Ok(bytes) if Digest::of(&bytes).to_string() == source.sha256 => "same",
932        Ok(_) => "changed",
933        Err(_) => "missing",
934    }
935}
936
937/// The destructive steps whose snapshot the registry lacks, and every
938/// reason the close refuses.
939fn blocking(
940    target: &Utf8PathBuf,
941    workspace: &Utf8Path,
942    registry: &Registry,
943) -> Result<(Vec<String>, Vec<String>), RkError> {
944    let mut held: Vec<&str> = Vec::new();
945    for snapshot in &registry.snapshots {
946        if registry::integrity(workspace, snapshot)? == Integrity::Intact {
947            held.push(snapshot.id.as_str());
948        }
949    }
950    let forge_missing: Vec<String> = setup_cmd::destructive_steps(target)
951        .unwrap_or_default()
952        .into_iter()
953        .filter(|step| !held.contains(&setup_cmd::forge_snapshot_id(step).as_str()))
954        .map(str::to_owned)
955        .collect();
956    let mut reasons = registry.unfinished(target);
957    match setup_cmd::proof_word(target) {
958        Ok("compatible") => {}
959        Ok(word) => reasons.push(format!(
960            "the setup proof is {word}; rk setup checkpoint on a host that holds the bot's key records the setup as satisfied"
961        )),
962        Err(error) => reasons.push(format!("the setup contract does not resolve: {error}")),
963    }
964    Ok((forge_missing, reasons))
965}
966
967fn status(target: &Utf8PathBuf, out: Output) -> Result<(), RkError> {
968    let (id, workspace, registry) = open(target)?;
969    let sources: Vec<SourceRow> = registry
970        .sources
971        .iter()
972        .map(|source| SourceRow {
973            id: source.id.clone(),
974            path: source.path.clone(),
975            tool: source.tool.clone(),
976            kind: source.kind,
977            placement: source.placement,
978            status: source.status,
979            group: source.group.clone(),
980            tags: source.tags.clone(),
981            checksum: checksum(target, &workspace, source),
982        })
983        .collect();
984    let (forge_missing, reasons) = blocking(target, &workspace, &registry)?;
985    out.result_line(format!(
986        "migration {id} at {workspace}, base {}",
987        registry.base_commit
988    ));
989    for row in &sources {
990        out.result_line(format!(
991            "{} {} ({}{}){}",
992            row.status.as_str(),
993            row.path,
994            row.group
995                .as_deref()
996                .map_or_else(|| "no group".to_owned(), |group| format!("group {group}")),
997            if row.tags.is_empty() {
998                String::new()
999            } else {
1000                format!("; tags {}", row.tags.join(", "))
1001            },
1002            if row.checksum == "same" {
1003                String::new()
1004            } else {
1005                format!(" — checksum {}", row.checksum)
1006            }
1007        ));
1008    }
1009    for step in &forge_missing {
1010        out.result_line(format!(
1011            "no forge snapshot of {step}: the step stays refused"
1012        ));
1013    }
1014    for reason in &reasons {
1015        out.result_line(format!("blocks the close: {reason}"));
1016    }
1017    let next = if reasons.is_empty() {
1018        vec![format!(
1019            "rk migrate close --target {target} previews the close"
1020        )]
1021    } else {
1022        vec![format!(
1023            "rk migrate mark <source-or-group> <status> --target {target} records the next step"
1024        )]
1025    };
1026    out.next(&next);
1027    out.emit(&StatusReport {
1028        schema: migrate::SCHEMA,
1029        id,
1030        workspace: workspace.to_string(),
1031        base_commit: registry.base_commit.clone(),
1032        sources,
1033        groups: registry.groups.clone(),
1034        snapshots: registry.snapshots,
1035        forge_missing,
1036        blocking: reasons,
1037        next,
1038    })
1039}
1040
1041/// The close report.
1042#[derive(Debug, Serialize)]
1043struct CloseReport {
1044    schema: &'static str,
1045    /// `preview` or `apply`.
1046    mode: &'static str,
1047    id: String,
1048    workspace: String,
1049    closed: bool,
1050    next: Vec<String>,
1051}
1052
1053/// SATISFIES migration:close-refuses-an-unfinished-migration
1054fn close(target: &Utf8PathBuf, apply: bool, out: Output) -> Result<(), RkError> {
1055    let (id, workspace, registry) = open(target)?;
1056    let (_, reasons) = blocking(target, &workspace, &registry)?;
1057    if !reasons.is_empty() {
1058        return Err(refused(
1059            Reason::PrerequisiteUnmet,
1060            format!(
1061                "the migration {id} cannot close: {} (migration:close-refuses-an-unfinished-migration)",
1062                reasons.join("; ")
1063            ),
1064            "every source verified or dropped, each verified source's group naming destinations the target holds, and a compatible setup proof",
1065            Some(format!(
1066                "rk migrate status --target {target} lists what is left"
1067            )),
1068        ));
1069    }
1070    if apply {
1071        crate::config::set_migration(target.as_std_path(), None)?;
1072        out.result_line(format!(
1073            "closed the migration {id}; .release-kit/config.toml no longer names it"
1074        ));
1075    } else {
1076        out.result_line(format!("the migration {id} can close"));
1077    }
1078    let next = if apply {
1079        vec![
1080            format!("keep or remove the workspace at {workspace}; its removal is the operator's"),
1081            "the first release through the rk-release skill is the proof".to_owned(),
1082        ]
1083    } else {
1084        vec![format!(
1085            "rk migrate close --apply --target {target} removes the key"
1086        )]
1087    };
1088    out.next(&next);
1089    out.emit(&CloseReport {
1090        schema: migrate::SCHEMA,
1091        mode: if apply { "apply" } else { "preview" },
1092        id,
1093        workspace: workspace.to_string(),
1094        closed: apply,
1095        next,
1096    })
1097}