Skip to main content

spec_driven_docs/services/
migration.rs

1//! A migration that archives the old corpus and rebuilds it from there.
2//!
3//! The verbs behind `sdd migrate`. `inventory` lists every document the
4//! target holds. `archive` moves each one but the root metadata into a
5//! workspace under this tool's state root, writes the registry beside it,
6//! and records the open migration in the declaration, so the repository
7//! reads as greenfield and every clone sees that a migration is open.
8//! `mark` moves a source or a group through its statuses, `status` reports
9//! where each stands, and `close` ends the migration once every source is
10//! verified or dropped.
11//!
12//! Three copies of every byte exist before a move: Git holds it at the base
13//! commit, because the archive refuses a document whose bytes differ from
14//! the trunk's copy, the archive holds it with its checksum, and
15//! `--rebuild` recreates the archive from Git on any clone. The base commit
16//! is the trunk's, so it outlives the branch the migration ran on.
17
18use camino::{Utf8Path, Utf8PathBuf};
19use serde::Serialize;
20
21use crate::adapters::history::History;
22use crate::domain::instance_config::{
23    CONFIG_PATH, InstanceConfig, with_migration, without_migration,
24};
25use crate::domain::migration::{
26    Event, Kind, Marking, Placement, REGISTRY_FILE, REGISTRY_SCHEMA, Registry, SOURCES_DIR, Source,
27    Status, kind_of, slug_of,
28};
29use crate::domain::ownership::Sha256;
30use crate::error::AppError;
31use crate::landing::classify::Classification;
32
33/// The machine schema every `sdd migrate --json` report declares.
34pub const SCHEMA: &str = "sdd.migrate/1";
35
36/// The directory every workspace sits under, inside the state root.
37pub const MIGRATIONS_DIR: &str = "migrations";
38
39/// Whether a document's home is one the convention or the corpus names.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
41#[serde(rename_all = "kebab-case")]
42pub enum Home {
43    /// Under a documentation root or a methodology marker.
44    Recognized,
45    /// Anywhere else.
46    Unrecognized,
47}
48
49/// One document the inventory found.
50#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
51pub struct Entry {
52    /// Where it sits, relative to the target.
53    pub path: Utf8PathBuf,
54    /// What kind of document it is.
55    pub kind: Kind,
56    /// The SHA-256 of its bytes.
57    pub sha256: String,
58    /// Whether the archive moves it or it stays in place.
59    pub placement: Placement,
60    /// Whether its home is a recognized one.
61    pub home: Home,
62}
63
64/// Every document a target holds, as `sdd migrate inventory` reports it.
65#[derive(Debug, Serialize)]
66pub struct Inventory {
67    /// The machine schema this object declares.
68    pub schema: &'static str,
69    /// Every document, in path order.
70    pub documents: Vec<Entry>,
71}
72
73/// What `sdd migrate archive` did, or would do.
74#[derive(Debug, Serialize)]
75pub struct ArchiveReport {
76    /// The machine schema this object declares.
77    pub schema: &'static str,
78    /// The migration id the declaration records.
79    pub id: String,
80    /// Where the workspace is.
81    pub workspace: Utf8PathBuf,
82    /// The commit that holds every byte the archive moves.
83    pub base_commit: String,
84    /// Every path the archive moves out of the target.
85    pub archived: Vec<Utf8PathBuf>,
86    /// Every path that stays in place, registered as a source.
87    pub in_place: Vec<Utf8PathBuf>,
88    /// Whether anything was written.
89    pub applied: bool,
90}
91
92/// What `sdd migrate status` reports for one source.
93#[derive(Debug, Serialize)]
94pub struct SourceState {
95    /// The source id.
96    pub id: String,
97    /// Where it sat at the base commit.
98    pub path: Utf8PathBuf,
99    /// Where it stands.
100    pub status: Status,
101    /// The group it is filed in.
102    pub group: Option<String>,
103    /// Whether its bytes differ from the registry's checksum: the archived
104    /// copy for an archived source, the file in place for root metadata.
105    pub changed: bool,
106}
107
108/// The whole state of an open migration.
109#[derive(Debug, Serialize)]
110pub struct StatusReport {
111    /// The machine schema this object declares.
112    pub schema: &'static str,
113    /// The migration id.
114    pub id: String,
115    /// Where the workspace is.
116    pub workspace: Utf8PathBuf,
117    /// The commit that held every source byte.
118    pub base_commit: String,
119    /// Every source, in path order.
120    pub sources: Vec<SourceState>,
121    /// Why the migration cannot close yet. Empty means it can.
122    pub unfinished: Vec<String>,
123}
124
125/// What `sdd migrate mark` changed.
126#[derive(Debug, Serialize)]
127pub struct MarkReport {
128    /// The machine schema this object declares.
129    pub schema: &'static str,
130    /// Every source id the mark moved.
131    pub marked: Vec<String>,
132    /// The status each one took.
133    pub status: Status,
134}
135
136/// What `sdd migrate close` did, or would do.
137#[derive(Debug, Serialize)]
138pub struct CloseReport {
139    /// The machine schema this object declares.
140    pub schema: &'static str,
141    /// The migration id.
142    pub id: String,
143    /// The workspace, which stays: the archive is the operator's to remove.
144    pub workspace: Utf8PathBuf,
145    /// Whether the declaration key was removed.
146    pub applied: bool,
147}
148
149/// The documents `target` holds, classified, in path order.
150///
151/// SATISFIES setup:inventory-lists-every-document
152///
153/// # Errors
154///
155/// I/O errors when the tree or a document cannot be read.
156pub fn inventory(target: &Utf8Path) -> Result<Inventory, AppError> {
157    let corpus =
158        crate::services::assess::corpus(target, crate::gates::paths::docs_scratch_variable())?;
159    let homes: Vec<String> = corpus
160        .doc_roots
161        .iter()
162        .chain(&corpus.methodology_markers)
163        .cloned()
164        .collect();
165    let mut documents = Vec::new();
166    for path in &corpus.documents {
167        let bytes = std::fs::read(target.join(path))?;
168        documents.push(entry(path, &bytes, &homes));
169    }
170    Ok(Inventory {
171        schema: SCHEMA,
172        documents,
173    })
174}
175
176/// One inventory entry for a document and its bytes.
177fn entry(path: &Utf8Path, bytes: &[u8], homes: &[String]) -> Entry {
178    let metadata = crate::services::assess::is_root_metadata(path);
179    let kind = kind_of(path, metadata);
180    let recognized = metadata
181        || matches!(kind, Kind::Decision | Kind::Spec)
182        || homes.iter().any(|home| path.starts_with(home.as_str()));
183    Entry {
184        path: path.to_owned(),
185        kind,
186        sha256: Sha256::of(bytes).to_string(),
187        placement: if metadata {
188            Placement::InPlace
189        } else {
190            Placement::Archived
191        },
192        home: if recognized {
193            Home::Recognized
194        } else {
195            Home::Unrecognized
196        },
197    }
198}
199
200/// The migration the declaration holds open, if any.
201///
202/// # Errors
203///
204/// [`AppError::Refused`] naming the declaration where it cannot be read.
205pub fn open_migration(target: &Utf8Path) -> Result<Option<String>, AppError> {
206    InstanceConfig::read(target)
207        .map(|declaration| declaration.migration)
208        .map_err(|error| AppError::Refused(error.to_string()))
209}
210
211/// Where one migration's workspace is.
212///
213/// # Errors
214///
215/// [`AppError::Refused`] where no state root resolves, because the home is
216/// not set and no variable names one.
217pub fn workspace(target: &Utf8Path, id: &str) -> Result<Utf8PathBuf, AppError> {
218    let state = crate::domain::paths::UserEnv::from_process()
219        .state_root()
220        .ok_or_else(|| {
221            AppError::Refused(
222                "no state root resolves: set HOME or XDG_STATE_HOME so the archive has a home"
223                    .to_string(),
224            )
225        })?;
226    Ok(state
227        .path
228        .join(MIGRATIONS_DIR)
229        .join(crate::stage::stage_name(target))
230        .join(id))
231}
232
233/// The history the archive rests on, or the refusal that names why none is.
234fn history(target: &Utf8Path) -> Result<History, AppError> {
235    History::open(target).map_err(|missing| {
236        AppError::Refused(format!(
237            "{missing}; a migration archives only what Git holds, so commit the corpus in a repository first (setup:an-archive-moves-only-committed-documents)"
238        ))
239    })
240}
241
242/// The time a status change is recorded at, in UTC.
243fn now() -> String {
244    jiff::Timestamp::now()
245        .strftime("%Y-%m-%dT%H:%M:%SZ")
246        .to_string()
247}
248
249/// Move every document but the root metadata into a new workspace.
250///
251/// Without `apply` this reports what would move and writes nothing.
252///
253/// SATISFIES setup:an-archive-moves-only-committed-documents
254///
255/// # Errors
256///
257/// [`AppError::Refused`] where a migration is already open, the target is
258/// not a migration, no trunk resolves, a listed document differs from the
259/// trunk's copy, or the instance directory cannot be written through.
260/// Nothing is written when it refuses.
261pub fn archive(
262    target: &Utf8Path,
263    trunk: Option<&str>,
264    apply: bool,
265) -> Result<ArchiveReport, AppError> {
266    if let Some(id) = open_migration(target)? {
267        return Err(AppError::Refused(format!(
268            "the migration {id} is already open; read it with 'sdd migrate status'"
269        )));
270    }
271    let found = crate::services::status::classify_target(target)?.classification;
272    if found != Classification::Migration {
273        return Err(AppError::Refused(format!(
274            "sdd migrate archive serves a migration target, and this target is {found}"
275        )));
276    }
277    let history = history(target)?;
278    if history.head().is_none() {
279        return Err(AppError::Refused(
280            "the repository has no commit, so Git holds none of the corpus; commit it first"
281                .to_string(),
282        ));
283    }
284    let trunk = trunk
285        .map(str::to_string)
286        .or_else(|| history.default_trunk())
287        .ok_or_else(|| {
288            AppError::Refused(
289                "the remote's HEAD names no local branch; name the trunk with --trunk <ref>"
290                    .to_string(),
291            )
292        })?;
293    let base_commit = history.commit_of(&trunk).ok_or_else(|| {
294        AppError::Refused(format!(
295            "the trunk {trunk} names no commit; name the trunk with --trunk <ref>"
296        ))
297    })?;
298    let listed = inventory(target)?.documents;
299    let paths: Vec<&Utf8Path> = listed.iter().map(|entry| entry.path.as_path()).collect();
300    // A document the trunk holds and the target lacks was deleted off the
301    // trunk: that is an edit too, and it integrates before the archive.
302    let mut differing = history.differing(&base_commit, &paths)?;
303    differing.extend(
304        documents_at(target, &history, &base_commit)?
305            .into_iter()
306            .filter(|path| !paths.contains(&path.as_path())),
307    );
308    differing.sort();
309    if !differing.is_empty() {
310        let names: Vec<String> = differing.iter().map(ToString::to_string).collect();
311        return Err(AppError::Refused(format!(
312            "these documents differ from the trunk's copy on {trunk}: {}; integrate their edits onto the trunk, then run the archive again (setup:an-archive-moves-only-committed-documents)",
313            names.join(", ")
314        )));
315    }
316    for written in [CONFIG_PATH, crate::domain::manifest::MANIFEST_PATH] {
317        crate::adapters::fs::check_destination(target, Utf8Path::new(written)).map_err(
318            |refusal| {
319                AppError::Refused(format!(
320                    "{written}: {refusal}; the archive writes nothing through it"
321                ))
322            },
323        )?;
324    }
325    let stamp = jiff::Timestamp::now()
326        .strftime("%Y%m%dT%H%M%SZ")
327        .to_string();
328    // An apply claims its workspace exclusively, so two archives in one
329    // second never share one; a preview only names where it would land.
330    let planned = workspace(target, &stamp)?;
331    let workspace = match planned.parent() {
332        Some(runs) if apply => crate::adapters::fs::claim_run_dir(runs, &stamp)?,
333        _ => planned,
334    };
335    let id = workspace.file_name().unwrap_or(stamp.as_str()).to_string();
336    let (archived, in_place): (Vec<&Entry>, Vec<&Entry>) = listed
337        .iter()
338        .partition(|entry| entry.placement == Placement::Archived);
339    let report = ArchiveReport {
340        schema: SCHEMA,
341        id: id.clone(),
342        workspace: workspace.clone(),
343        base_commit: base_commit.clone(),
344        archived: archived.iter().map(|entry| entry.path.clone()).collect(),
345        in_place: in_place.iter().map(|entry| entry.path.clone()).collect(),
346        applied: apply,
347    };
348    if !apply {
349        return Ok(report);
350    }
351    for entry in &archived {
352        let bytes = std::fs::read(target.join(&entry.path))?;
353        let copy = workspace.join(SOURCES_DIR).join(&entry.path);
354        crate::adapters::fs::write_atomic(&copy, &bytes)?;
355        if Sha256::of(&std::fs::read(&copy)?).to_string() != entry.sha256 {
356            return Err(AppError::Refused(format!(
357                "{copy} does not read back as the bytes it was copied from; nothing was moved"
358            )));
359        }
360    }
361    let registry = new_registry(&id, &base_commit, &listed);
362    write_registry(&workspace, &registry)?;
363    write_declaration(target, |text| with_migration(text, &id))?;
364    for entry in &archived {
365        crate::adapters::fs::remove_within(target, &entry.path)?;
366        prune_empty_parents(target, &entry.path);
367    }
368    Ok(report)
369}
370
371/// A registry with every listed document pending.
372///
373/// Each source id is the slug of its path. Paths are taken in byte order,
374/// so where two slugs collide the first path keeps the bare slug and each
375/// later one takes the next free `-N`, the same on every rebuild.
376fn new_registry(id: &str, base_commit: &str, listed: &[Entry]) -> Registry {
377    let at = now();
378    let mut ordered: Vec<&Entry> = listed.iter().collect();
379    ordered.sort_by(|left, right| left.path.as_str().cmp(right.path.as_str()));
380    let mut sources: Vec<Source> = Vec::new();
381    for entry in ordered {
382        let mut slug = slug_of(&entry.path);
383        let mut suffix = 2;
384        while sources.iter().any(|source| source.id == slug) {
385            slug = format!("{}-{suffix}", slug_of(&entry.path));
386            suffix += 1;
387        }
388        sources.push(Source {
389            id: slug,
390            path: entry.path.clone(),
391            sha256: entry.sha256.clone(),
392            kind: entry.kind,
393            placement: entry.placement,
394            tags: Vec::new(),
395            group: None,
396            status: Status::Pending,
397            history: vec![Event {
398                at: at.clone(),
399                status: Status::Pending,
400                reason: None,
401            }],
402        });
403    }
404    Registry {
405        schema_version: REGISTRY_SCHEMA,
406        id: id.to_string(),
407        base_commit: base_commit.to_string(),
408        sources,
409        groups: Vec::new(),
410    }
411}
412
413/// Rewrite the declaration through `change`, creating it where it is
414/// absent, and keep the instance's record of it current.
415fn write_declaration(target: &Utf8Path, change: impl Fn(&str) -> String) -> Result<(), AppError> {
416    let path = target.join(CONFIG_PATH);
417    let text = match std::fs::read_to_string(&path) {
418        Ok(text) => text,
419        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
420        Err(error) => return Err(AppError::Io(error)),
421    };
422    let changed = change(&text);
423    crate::adapters::fs::write_within(target, Utf8Path::new(CONFIG_PATH), changed.as_bytes())?;
424    rerecord_declaration(target, changed.as_bytes())
425}
426
427/// Update the instance's record of the declaration, where an instance is
428/// landed, so a verb that wrote it leaves no drift behind.
429fn rerecord_declaration(target: &Utf8Path, bytes: &[u8]) -> Result<(), AppError> {
430    let manifest = target.join(crate::domain::manifest::MANIFEST_PATH);
431    let Ok(text) = std::fs::read_to_string(&manifest) else {
432        return Ok(());
433    };
434    let mut document: serde_json::Value = serde_json::from_str(&text)
435        .map_err(|error| AppError::ManifestInvalid(error.to_string()))?;
436    let recorded = document
437        .get("adopted_files")
438        .and_then(serde_json::Value::as_array)
439        .is_some_and(|entries| {
440            entries.iter().any(|entry| {
441                entry.get("destination").and_then(serde_json::Value::as_str) == Some(CONFIG_PATH)
442            })
443        });
444    if !recorded {
445        return Ok(());
446    }
447    crate::services::policy::with_adopted_record(
448        &mut document,
449        "",
450        Utf8Path::new(CONFIG_PATH),
451        bytes,
452        &[],
453    )?;
454    let rendered = serde_json::to_string_pretty(&document)
455        .map_err(|error| AppError::ManifestInvalid(error.to_string()))?;
456    crate::adapters::fs::write_within(
457        target,
458        Utf8Path::new(crate::domain::manifest::MANIFEST_PATH),
459        format!("{rendered}\n").as_bytes(),
460    )?;
461    Ok(())
462}
463
464/// Remove each parent directory of `path` the move left empty, up to the
465/// target, so the archive leaves no hollow tree behind.
466fn prune_empty_parents(target: &Utf8Path, path: &Utf8Path) {
467    let mut parent = path.parent();
468    while let Some(directory) = parent.filter(|directory| !directory.as_str().is_empty()) {
469        if std::fs::remove_dir(target.join(directory)).is_err() {
470            break;
471        }
472        parent = directory.parent();
473    }
474}
475
476/// Write the registry into the workspace.
477fn write_registry(workspace: &Utf8Path, registry: &Registry) -> Result<(), AppError> {
478    let text = registry
479        .render()
480        .map_err(|error| AppError::Refused(error.to_string()))?;
481    crate::adapters::fs::write_atomic(&workspace.join(REGISTRY_FILE), text.as_bytes())?;
482    Ok(())
483}
484
485/// The open migration's id, workspace, and registry.
486///
487/// # Errors
488///
489/// [`AppError::Refused`] where no migration is open or the registry cannot
490/// be read.
491fn opened(target: &Utf8Path) -> Result<(String, Utf8PathBuf, Registry), AppError> {
492    let id = open_migration(target)?.ok_or_else(|| {
493        AppError::Refused("no migration is open here; 'sdd migrate archive' opens one".to_string())
494    })?;
495    let workspace = workspace(target, &id)?;
496    let text = std::fs::read_to_string(workspace.join(REGISTRY_FILE)).map_err(|error| {
497        AppError::Refused(format!(
498            "the registry of {id} cannot be read under {workspace}: {error}; 'sdd migrate archive --rebuild --apply' recreates the archive from Git"
499        ))
500    })?;
501    let registry = Registry::parse(&text).map_err(|error| AppError::Refused(error.to_string()))?;
502    Ok((id, workspace, registry))
503}
504
505/// Recreate the open migration's archive from Git at its base commit.
506///
507/// The registry is read where the workspace holds one. On a clone that has
508/// none, the base commit is the parent of the commit that recorded the
509/// migration in the declaration, and the registry is rebuilt from the
510/// documents that commit holds, every one pending again.
511///
512/// SATISFIES setup:an-archive-rebuilds-from-git
513///
514/// # Errors
515///
516/// [`AppError::Refused`] where no migration is open, the history does not
517/// hold the base commit, or a recreated byte does not match its checksum.
518pub fn rebuild(target: &Utf8Path, apply: bool) -> Result<ArchiveReport, AppError> {
519    let id = open_migration(target)?.ok_or_else(|| {
520        AppError::Refused("no migration is open here, so there is nothing to rebuild".to_string())
521    })?;
522    let workspace = workspace(target, &id)?;
523    let history = history(target)?;
524    let registry = if let Ok(text) = std::fs::read_to_string(workspace.join(REGISTRY_FILE)) {
525        Registry::parse(&text).map_err(|error| AppError::Refused(error.to_string()))?
526    } else {
527        reconstructed(target, &history, &id)?
528    };
529    let archived: Vec<&Source> = registry
530        .sources
531        .iter()
532        .filter(|source| source.placement == Placement::Archived)
533        .collect();
534    let mut recreated = Vec::new();
535    for source in &archived {
536        let bytes = history
537            .show(&registry.base_commit, &source.path)
538            .ok_or_else(|| {
539                AppError::Refused(format!(
540                    "{} holds no {}; fetch the history that holds it",
541                    registry.base_commit, source.path
542                ))
543            })?;
544        if Sha256::of(&bytes).to_string() != source.sha256 {
545            return Err(AppError::Refused(format!(
546                "{} at {} does not match its registered checksum",
547                source.path, registry.base_commit
548            )));
549        }
550        recreated.push((source.path.clone(), bytes));
551    }
552    if apply {
553        for (path, bytes) in &recreated {
554            crate::adapters::fs::write_atomic(&workspace.join(SOURCES_DIR).join(path), bytes)?;
555        }
556        if !workspace.join(REGISTRY_FILE).is_file() {
557            write_registry(&workspace, &registry)?;
558        }
559    }
560    Ok(ArchiveReport {
561        schema: SCHEMA,
562        id,
563        workspace,
564        base_commit: registry.base_commit.clone(),
565        archived: archived.iter().map(|source| source.path.clone()).collect(),
566        in_place: registry
567            .sources
568            .iter()
569            .filter(|source| source.placement == Placement::InPlace)
570            .map(|source| source.path.clone())
571            .collect(),
572        applied: apply,
573    })
574}
575
576/// The documents `commit` holds, selected the way an inventory selects them
577/// from a tree: regular files a walk would count, outside the docs scratch.
578fn documents_at(
579    target: &Utf8Path,
580    history: &History,
581    commit: &str,
582) -> Result<Vec<Utf8PathBuf>, AppError> {
583    let scratch = crate::services::assess::scratch_within(
584        target,
585        crate::gates::paths::docs_scratch_variable(),
586    );
587    Ok(history
588        .files_at(commit)?
589        .into_iter()
590        .filter(|path| {
591            crate::services::assess::is_document_path(path)
592                && !scratch
593                    .as_ref()
594                    .is_some_and(|scratch| path.starts_with(scratch))
595        })
596        .collect())
597}
598
599/// The registry of a migration whose workspace this host does not hold,
600/// rebuilt from the commit before the one that recorded it.
601///
602/// The sources are selected the way an inventory selects them: regular
603/// files a walk would count, outside the docs scratch. The scratch is the
604/// one that resolves today, because only the lost registry recorded which
605/// documents the archive took.
606fn reconstructed(target: &Utf8Path, history: &History, id: &str) -> Result<Registry, AppError> {
607    let base = history
608        .before_adding(
609            Utf8Path::new(CONFIG_PATH),
610            &crate::domain::instance_config::migration_line(id),
611        )
612        .ok_or_else(|| {
613            AppError::Refused(format!(
614                "no commit records the migration {id} in {CONFIG_PATH}, so the base commit cannot be found"
615            ))
616        })?;
617    let mut listed = Vec::new();
618    for path in documents_at(target, history, &base)? {
619        if let Some(bytes) = history.show(&base, &path) {
620            listed.push(entry(&path, &bytes, &[]));
621        }
622    }
623    Ok(new_registry(id, &base, &listed))
624}
625
626/// Move a source, or every source of a group, to `status`.
627///
628/// SATISFIES setup:mark-appends-and-never-rewrites
629///
630/// # Errors
631///
632/// [`AppError::Usage`] where a destination leaves the target, and
633/// [`AppError::Refused`] where no migration is open or the registry
634/// refuses the change. The registry is unchanged when either refuses.
635pub fn mark(
636    target: &Utf8Path,
637    name: &str,
638    status: Status,
639    marking: &Marking,
640) -> Result<MarkReport, AppError> {
641    // Close judges each destination under the target, so one that names
642    // an absolute path or climbs out of it would judge a foreign file.
643    for destination in &marking.destinations {
644        let inside = !destination.as_str().is_empty()
645            && destination.components().all(|part| {
646                matches!(
647                    part,
648                    camino::Utf8Component::Normal(_) | camino::Utf8Component::CurDir
649                )
650            });
651        if !inside {
652            return Err(AppError::Usage(format!(
653                "the destination {destination} leaves the target; name a path relative to the target root"
654            )));
655        }
656    }
657    let (_, workspace, mut registry) = opened(target)?;
658    let marked = registry
659        .mark(name, status, marking, &now())
660        .map_err(|error| AppError::Refused(error.to_string()))?;
661    write_registry(&workspace, &registry)?;
662    Ok(MarkReport {
663        schema: SCHEMA,
664        marked,
665        status,
666    })
667}
668
669/// Where every source of the open migration stands.
670///
671/// # Errors
672///
673/// [`AppError::Refused`] where no migration is open, and the I/O error of a
674/// held copy that exists and cannot be read: an unreadable copy is not a
675/// changed one.
676pub fn status(target: &Utf8Path) -> Result<StatusReport, AppError> {
677    let (id, workspace, registry) = opened(target)?;
678    let sources = registry
679        .sources
680        .iter()
681        .map(|source| {
682            let held = match source.placement {
683                Placement::Archived => workspace.join(SOURCES_DIR).join(&source.path),
684                Placement::InPlace => target.join(&source.path),
685            };
686            let changed = match std::fs::read(&held) {
687                Ok(bytes) => Sha256::of(&bytes).to_string() != source.sha256,
688                Err(error) if error.kind() == std::io::ErrorKind::NotFound => true,
689                Err(error) => return Err(AppError::Io(error)),
690            };
691            Ok(SourceState {
692                id: source.id.clone(),
693                path: source.path.clone(),
694                status: source.status,
695                group: source.group.clone(),
696                changed,
697            })
698        })
699        .collect::<Result<Vec<_>, AppError>>()?;
700    let root = target.canonicalize_utf8()?;
701    Ok(StatusReport {
702        schema: SCHEMA,
703        id,
704        workspace,
705        base_commit: registry.base_commit.clone(),
706        sources,
707        unfinished: registry.unfinished(|path| holds(&root, target, path)),
708    })
709}
710
711/// Whether the target holds `destination` as a file inside it. A link that
712/// leads out of the target is a file the target does not hold.
713fn holds(root: &Utf8Path, target: &Utf8Path, destination: &Utf8Path) -> bool {
714    target
715        .join(destination)
716        .canonicalize_utf8()
717        .is_ok_and(|held| held.starts_with(root) && held.is_file())
718}
719
720/// End the open migration: remove the declaration key once every source is
721/// verified or dropped. The workspace stays for the operator to remove.
722///
723/// SATISFIES setup:close-refuses-an-unfinished-source
724///
725/// # Errors
726///
727/// [`AppError::Refused`] naming every unfinished source. Nothing is written
728/// when it refuses.
729pub fn close(target: &Utf8Path, apply: bool) -> Result<CloseReport, AppError> {
730    let (id, workspace, registry) = opened(target)?;
731    let root = target.canonicalize_utf8()?;
732    let unfinished = registry.unfinished(|path| holds(&root, target, path));
733    if !unfinished.is_empty() {
734        return Err(AppError::Refused(format!(
735            "the migration {id} cannot close: {} (setup:close-refuses-an-unfinished-source)",
736            unfinished.join("; ")
737        )));
738    }
739    if apply {
740        write_declaration(target, without_migration)?;
741    }
742    Ok(CloseReport {
743        schema: SCHEMA,
744        id,
745        workspace,
746        applied: apply,
747    })
748}