Skip to main content

spec_driven_docs/services/
self_manifest.rs

1//! Write the payload record: what this tree embeds, described by the tree.
2//!
3//! The record is an artifact of the tree, like the binary. Its identity is
4//! the crate version of `Cargo.toml` and the hash of every file under the
5//! declared payload roots, so it describes the payload of the checkout that
6//! writes it whatever sdd a devshell pins. It holds no instance field, and
7//! nothing compares it with an instance record: this repository's own
8//! instance is an ordinary one, landed by its pinned previous release.
9//!
10//! SATISFIES release:the-payload-record-describes-its-tree
11
12use camino::{Utf8Path, Utf8PathBuf};
13use serde::{Deserialize, Serialize};
14
15use crate::adapters::fs::sha256_file;
16use crate::domain::ownership::Sha256;
17use crate::domain::version::CanonVersion;
18use crate::error::AppError;
19
20/// Where the tree keeps its payload record, relative to its root.
21pub const PAYLOAD_RECORD_PATH: &str = "instance/payload-manifest.json";
22
23/// The schema id the payload record carries.
24pub const PAYLOAD_RECORD_SCHEMA: &str = "sdd.payload-manifest/1";
25
26/// One payload source and its digest.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct PayloadFile {
29    /// The path relative to the tree root.
30    pub path: Utf8PathBuf,
31    /// The digest of its bytes.
32    pub sha256: Sha256,
33}
34
35/// The description of the payload one tree embeds.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct PayloadRecord {
39    /// The schema id, [`PAYLOAD_RECORD_SCHEMA`].
40    pub schema: String,
41    /// The crate version of the tree.
42    pub version: CanonVersion,
43    /// Every file under the declared payload roots, sorted by path, the
44    /// record itself excepted.
45    pub files: Vec<PayloadFile>,
46}
47
48impl PayloadRecord {
49    /// The record as the tree writes it: pretty JSON with a final newline.
50    #[must_use]
51    pub fn to_json(&self) -> String {
52        let mut text = serde_json::to_string_pretty(self).unwrap_or_default();
53        text.push('\n');
54        text
55    }
56}
57
58pub(crate) fn is_canon_checkout(root: &Utf8Path) -> bool {
59    std::fs::read_to_string(root.join("Cargo.toml"))
60        .is_ok_and(|cargo| cargo.contains("name = \"spec-driven-docs\""))
61}
62
63/// Describe the payload the tree at `root` carries.
64///
65/// # Errors
66///
67/// I/O errors walking a root or reading a file.
68pub fn describe(root: &Utf8Path) -> Result<PayloadRecord, AppError> {
69    let mut files = Vec::new();
70    for declared in crate::payload_roots::PAYLOAD_ROOTS {
71        if !root.join(declared).exists() {
72            continue;
73        }
74        for entry in walkdir::WalkDir::new(root.join(declared)).sort_by_file_name() {
75            let entry = entry.map_err(|source| AppError::Io(std::io::Error::from(source)))?;
76            if !entry.file_type().is_file() {
77                continue;
78            }
79            let Some(path) = Utf8Path::from_path(entry.path()) else {
80                continue;
81            };
82            let relative = path.strip_prefix(root).unwrap_or(path).to_owned();
83            if relative == PAYLOAD_RECORD_PATH {
84                continue;
85            }
86            files.push(PayloadFile {
87                sha256: sha256_file(path)?,
88                path: relative,
89            });
90        }
91    }
92    files.sort_by(|left, right| left.path.cmp(&right.path));
93    Ok(PayloadRecord {
94        schema: PAYLOAD_RECORD_SCHEMA.to_string(),
95        version: CanonVersion::current(),
96        files,
97    })
98}
99
100/// Write the payload record of the canon checkout at `root`.
101///
102/// # Errors
103///
104/// [`AppError::Refused`] outside the canon checkout, and I/O errors when a
105/// payload file cannot be read or the record cannot be written.
106pub fn regenerate(root: &Utf8Path) -> Result<String, AppError> {
107    if !is_canon_checkout(root) {
108        return Err(AppError::Refused("not the canon checkout".to_string()));
109    }
110    let record = describe(root)?;
111    crate::adapters::fs::write_file(&root.join(PAYLOAD_RECORD_PATH), record.to_json().as_bytes())?;
112    Ok(format!("OK regenerated {PAYLOAD_RECORD_PATH}"))
113}