Skip to main content

spec_driven_docs/services/
installer.rs

1//! Instance installation: project the embedded payload into a target.
2//!
3//! The chezmoi vocabulary applies: the embedded payload and profile are the
4//! source state, the computed projection is the target state, the repository
5//! on disk is the destination state, and the manifest — written last — is
6//! the persistent entry state. The whole target state is computed before a
7//! byte lands; a non-empty target previews by default; every destination is
8//! guarded; and any failure mid-apply rolls the target back. What the
9//! payload contains is `embedded`'s and the profiles' business.
10
11use camino::{Utf8Path, Utf8PathBuf};
12
13use crate::domain::manifest::{MANIFEST_PATH, validate_docs_scratch_path};
14use crate::domain::paths::{AGENTS_DIGEST_PATH, HOOKS_CONFIG_PATH};
15use crate::domain::profile::{ProfileId, resolve_destination};
16use crate::domain::version::CanonVersion;
17use crate::error::AppError;
18
19/// What an installation was asked to do.
20#[derive(Debug, Clone)]
21pub struct InitOptions {
22    /// The absolute target repository.
23    pub target: Utf8PathBuf,
24    /// The profile to project.
25    pub profile: ProfileId,
26    /// Write even into a non-empty target with no instance.
27    pub apply: bool,
28    /// Preview only, regardless of the target's state.
29    pub dry_run: bool,
30    /// The docs scratch to record. `None` keeps whatever is recorded, and
31    /// `Some(None)` clears it.
32    pub docs_scratch: Option<Option<Utf8PathBuf>>,
33    /// Paths to record under `reserved:` in the instance's declaration. An
34    /// empty list keeps whatever is recorded.
35    pub reserve: Vec<String>,
36    /// The writing-style selection to record in the declaration. `None`
37    /// keeps whatever is recorded.
38    pub writing_style: Option<crate::domain::instance_config::WritingStyle>,
39    /// The acquisition decision to record in the declaration. `None` keeps
40    /// whatever is recorded.
41    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
42    /// Destinations the operator named for replacement. The caller saves
43    /// each one's bytes before the landing runs.
44    pub replace: Vec<String>,
45}
46
47/// What an installation did.
48#[derive(Debug)]
49pub struct InitOutcome {
50    /// Every line to print: the proposed destinations, then any notices.
51    pub lines: Vec<String>,
52    /// Whether files were written.
53    pub applied: bool,
54    /// Every destination the landing retired and deleted, or would, relative
55    /// to the target.
56    pub removed: Vec<String>,
57    /// Every destination the landing dropped and left as the project's, or
58    /// would, relative to the target.
59    pub dropped: Vec<String>,
60}
61
62fn canonical_target(target: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
63    if !target.is_absolute() {
64        return Err(AppError::Usage("target must be absolute".to_string()));
65    }
66    if !target.is_dir() {
67        return Err(AppError::Usage(format!("unresolved target: {target}")));
68    }
69    let canonical = std::fs::canonicalize(target)?;
70    let canonical = Utf8PathBuf::from_path_buf(canonical)
71        .map_err(|p| AppError::Usage(format!("target is not UTF-8: {}", p.display())))?;
72    // The canon checkout is an ordinary target: it lands and upgrades its
73    // own instance like any repository.
74    // SATISFIES release:the-canon-is-an-ordinary-instance
75    if canonical.as_str().chars().all(|c| c == '/') {
76        return Err(AppError::Usage("refusing root target".to_string()));
77    }
78    Ok(canonical)
79}
80
81fn target_has_content(target: &Utf8Path) -> Result<bool, AppError> {
82    for entry in target.read_dir_utf8()? {
83        let entry = entry?;
84        if entry.file_name() != ".git" {
85            return Ok(true);
86        }
87    }
88    Ok(false)
89}
90
91/// One field of whatever manifest the target already carries.
92///
93/// Read as free JSON rather than through [`Manifest::parse`]: a reinstall
94/// over a record of another schema version must still carry the operator's
95/// declared values forward, and a typed parse would refuse to read it.
96pub(crate) fn recorded_field(target: &Utf8Path, key: &str) -> Option<serde_json::Value> {
97    std::fs::read_to_string(target.join(MANIFEST_PATH))
98        .ok()
99        .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
100        .and_then(|value| value.get(key).cloned())
101        .filter(|value| !value.is_null())
102}
103
104fn installed_at(target: &Utf8Path) -> String {
105    recorded_field(target, "installed_at")
106        .and_then(|value| value.as_str().map(String::from))
107        .unwrap_or_else(|| {
108            jiff::Timestamp::now()
109                .strftime("%Y-%m-%dT%H:%M:%SZ")
110                .to_string()
111        })
112}
113
114/// The docs scratch to record: the flag, else the recorded value, else none.
115///
116/// An omitted flag never clears a declared value. `sdd upgrade` reinstalls
117/// with no flag at all, so "absent means the default" would erase the
118/// operator's declaration on every upgrade. The flag is two-level on
119/// purpose: absent keeps what is recorded, and `--docs-scratch none` clears
120/// it.
121///
122/// # Errors
123///
124/// [`AppError::ManifestInvalid`] when the recorded value is not a string.
125pub(crate) fn resolved_docs_scratch(
126    target: &Utf8Path,
127    flag: Option<&Option<Utf8PathBuf>>,
128) -> Result<Option<Utf8PathBuf>, AppError> {
129    if let Some(declared) = flag {
130        return Ok(declared.clone());
131    }
132    let Some(recorded) = recorded_field(target, "docs_scratch") else {
133        return Ok(None);
134    };
135    let path = recorded
136        .as_str()
137        .filter(|path| !path.is_empty())
138        .map(Utf8PathBuf::from)
139        .ok_or_else(|| {
140            AppError::ManifestInvalid(format!(
141                "the recorded docs_scratch is not a path ({recorded}); \
142                 re-declare it with --docs-scratch"
143            ))
144        })?;
145    if let Err(error) = validate_docs_scratch_path(&path) {
146        return Err(AppError::ManifestInvalid(format!(
147            "the recorded docs_scratch is not usable ({error}); \
148             re-declare it with --docs-scratch"
149        )));
150    }
151    Ok(Some(path))
152}
153
154/// Every byte one landing would put in a target, and what it would say.
155///
156/// The planner takes this rather than deriving it a second time: what a
157/// release lands into a target is one computation, and two of them would
158/// be two places for one rule to drift.
159#[derive(Debug, Clone)]
160pub struct TargetState {
161    /// Each destination and the bytes that would go there.
162    pub files: Vec<(Utf8PathBuf, Vec<u8>)>,
163    /// What the operator would be told.
164    pub lines: Vec<String>,
165}
166
167/// What this binary would put in a target, and what it would say.
168///
169/// Observation happens here and projection happens in [`crate::candidate`].
170/// Everything this function reads from the target is a value it hands over,
171/// so the bytes a stage renders and the bytes a landing writes come out of
172/// one pure pass over the same evidence.
173///
174/// # Errors
175///
176/// [`AppError::Refused`] when this release declares no such profile, when a
177/// marked region cannot be read, or when the root author-instructions file
178/// is a link, and I/O errors reading the target.
179pub fn compute_target_state(
180    target: &Utf8Path,
181    options: &InitOptions,
182) -> Result<TargetState, AppError> {
183    let candidate = candidate_for(target, options)?;
184    let mut lines: Vec<String> = Vec::new();
185    for destination in &candidate.destinations {
186        lines.push(destination.path.to_string());
187    }
188    lines.extend(candidate.notes.iter().cloned());
189    lines.push(MANIFEST_PATH.to_string());
190    Ok(TargetState {
191        files: candidate.files(),
192        lines,
193    })
194}
195
196/// The candidate this binary renders for one target.
197///
198/// # Errors
199///
200/// As [`compute_target_state`].
201pub fn candidate_for(
202    target: &Utf8Path,
203    options: &InitOptions,
204) -> Result<crate::candidate::Candidate, AppError> {
205    crate::candidate::project(&gather(target, options)?)
206}
207
208/// The target a landing or a stage will read, canonical and known-good.
209///
210/// # Errors
211///
212/// [`AppError::Usage`] for a path no verb can mean: relative, absent, the
213/// or the filesystem root.
214pub fn resolved_target(target: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
215    canonical_target(target)
216}
217
218/// Which names of every yield set this release declares exist at the
219/// target root.
220///
221/// A seed that yields reads nothing from these files but their presence:
222/// the project's own configuration governs, whatever its grammar.
223#[must_use]
224pub fn present_at_root(target: &Utf8Path) -> Vec<String> {
225    let mut present: Vec<String> = Vec::new();
226    for projection in &crate::domain::profile::DECLARATION.adopted {
227        let Some(set) = projection.yield_set() else {
228            continue;
229        };
230        for name in set.names() {
231            if target.join(name).is_file() && !present.iter().any(|held| held == name) {
232                present.push(name.to_string());
233            }
234        }
235    }
236    present
237}
238
239/// Read the target once, so the projection never has to.
240fn gather(target: &Utf8Path, options: &InitOptions) -> Result<crate::candidate::Input, AppError> {
241    let docs_root = crate::candidate::docs_root_of(options.profile)?;
242
243    // What the target already records as adopted. A destination that holds
244    // project content and is recorded nowhere is preserved and noted: the
245    // seed does not land, and the project should know the specification it
246    // would have received.
247    let recorded_adopted: Vec<String> = recorded_field(target, "adopted_files")
248        .and_then(|value| {
249            value.as_array().map(|entries| {
250                entries
251                    .iter()
252                    .filter_map(|entry| entry.get("destination")?.as_str().map(String::from))
253                    .collect()
254            })
255        })
256        .unwrap_or_default();
257
258    let mut existing = std::collections::BTreeMap::new();
259    for projection in &crate::domain::profile::DECLARATION.adopted {
260        let destination = resolve_destination(&projection.destination, docs_root);
261        let path = target.join(&destination);
262        if path.is_file() {
263            existing.insert(destination, std::fs::read(&path)?);
264        }
265    }
266
267    let present_at_root = present_at_root(target);
268
269    let hooks_path = target.join(HOOKS_CONFIG_PATH);
270    let hooks_host = if hooks_path.is_file() {
271        std::fs::read_to_string(&hooks_path)?
272    } else {
273        String::new()
274    };
275
276    // The root AGENTS.md documentation block routes authors to the context they
277    // load before editing. A symlinked host is refused before it is read, so a
278    // link cannot redirect the read outside the target.
279    let agents_path = target.join(AGENTS_DIGEST_PATH);
280    if agents_path.is_symlink() {
281        return Err(AppError::Refused(
282            "AGENTS.md is a symlink; refusing to write the documentation block through it"
283                .to_string(),
284        ));
285    }
286    let agents_exists = agents_path.is_file();
287    let agents_host = if agents_exists {
288        std::fs::read_to_string(&agents_path)?
289    } else {
290        String::new()
291    };
292
293    Ok(crate::candidate::Input {
294        profile: options.profile,
295        version: CanonVersion::current(),
296        installed_at: installed_at(target),
297        docs_scratch: resolved_docs_scratch(target, options.docs_scratch.as_ref())?,
298        reserve: options.reserve.clone(),
299        writing_style: options.writing_style.clone(),
300        acquisition: options.acquisition.clone(),
301        evidence: crate::candidate::Evidence {
302            existing,
303            recorded_adopted,
304            hooks_host,
305            agents_host,
306            agents_exists,
307            present_at_root,
308        },
309    })
310}
311
312/// Install or reinstall an instance.
313///
314/// # Errors
315///
316/// [`AppError::Usage`] for a target the arguments cannot mean,
317/// [`AppError::Marker`] for a configuration whose markers cannot be
318/// trusted, and [`AppError::Refused`] when a destination escapes the
319/// target, holds bytes no record accounts for, or cannot be written.
320pub fn init(
321    options: &InitOptions,
322    intent: crate::landing::classify::Intent,
323) -> Result<InitOutcome, AppError> {
324    init_holding(None, options, intent)
325}
326
327/// Install or reinstall an instance under a lock the caller already holds.
328///
329/// A verb that observed the target before it decided to land must hold the
330/// target across both, so the tree it decided from is the tree it writes.
331///
332/// # Errors
333///
334/// As [`init`].
335pub fn init_holding(
336    held: Option<crate::transaction::lock::Lock>,
337    options: &InitOptions,
338    intent: crate::landing::classify::Intent,
339) -> Result<InitOutcome, AppError> {
340    let target = canonical_target(&options.target)?;
341    // The target is known-good before it is classified, so an argument
342    // this verb cannot mean is a usage answer rather than a walk of
343    // whatever the argument happened to name.
344    crate::commands::front::serves(intent, &target)?;
345    let forced_dry = !options.apply
346        && !options.dry_run
347        && target_has_content(&target)?
348        && !target.join(MANIFEST_PATH).is_file();
349    let dry = options.dry_run || forced_dry;
350
351    // A preview reads and writes nothing, so it needs no lock. An apply
352    // holds one across the observation as well as the writes: a candidate
353    // rendered before the lock would describe a target another run could
354    // still be changing. A caller that already holds it passes it in,
355    // because taking it twice from one process proves nothing.
356    let held = match (dry, held) {
357        (true, _) => None,
358        (false, Some(held)) => Some(held),
359        (false, None) => Some(crate::landing::lock::hold(&target)?),
360    };
361
362    // A profile carries the documentation root, so changing it moves every
363    // adopted document to a new home and leaves the old corpus where it
364    // is. That is a migration somebody asks for deliberately, never a
365    // consequence of running a landing verb with a different flag.
366    if let Some(recorded) = recorded_field(&target, "profile").and_then(|value| {
367        ProfileId::every().find(|profile| Some(profile.as_str()) == value.as_str())
368    }) && recorded != options.profile
369    {
370        return Err(AppError::Refused(format!(
371            "{target} records the {recorded} profile and this run asks for {}; \
372             moving a profile moves the documentation root, which is a migration to ask for deliberately",
373            options.profile
374        )));
375    }
376
377    let candidate = candidate_for(&target, options)?;
378    let mut lines: Vec<String> = candidate
379        .destinations
380        .iter()
381        .map(|destination| destination.path.to_string())
382        .collect();
383    lines.extend(candidate.notes.iter().cloned());
384    lines.push(MANIFEST_PATH.to_string());
385
386    if dry {
387        if forced_dry {
388            lines.push(
389                "DRY RUN: the target is a non-empty repository with no instance; re-run with --apply to write these files"
390                    .to_string(),
391            );
392        }
393        lines.push("DRY RUN: no files written".to_string());
394        // A preview names what the apply deletes and what it leaves, by the
395        // sort the apply itself runs.
396        let (removed, dropped) =
397            crate::landing::apply::departures(&target, &candidate, &recorded(&target)).into_paths();
398        return Ok(InitOutcome {
399            lines,
400            applied: false,
401            removed,
402            dropped,
403        });
404    }
405
406    let mut vouched = recorded(&target);
407    vouched.replace.clone_from(&options.replace);
408    let outcome = crate::landing::apply::land(&target, &candidate, &vouched)?;
409    drop(held);
410    Ok(InitOutcome {
411        lines,
412        applied: true,
413        removed: outcome.removed,
414        dropped: outcome.dropped,
415    })
416}
417
418/// What the target's own record says this tool owns today.
419///
420/// Read as free JSON, so a record an older release wrote still says which
421/// files this tool may refresh, which regions it may re-splice, and which
422/// files it may take back.
423pub(crate) fn recorded(target: &Utf8Path) -> crate::landing::apply::Recorded {
424    crate::landing::apply::Recorded {
425        managed: digests(target, "managed_files", "destination", "sha256"),
426        integration: digests(target, "integration_blocks", "path", "marker_hash"),
427        replace: Vec::new(),
428    }
429}
430
431/// One recorded list, as pairs of destination and digest.
432fn digests(
433    target: &Utf8Path,
434    key: &str,
435    name: &str,
436    digest: &str,
437) -> Vec<(String, crate::domain::ownership::Sha256)> {
438    let Some(value) = recorded_field(target, key) else {
439        return Vec::new();
440    };
441    let Some(entries) = value.as_array() else {
442        return Vec::new();
443    };
444    entries
445        .iter()
446        .filter_map(|entry| {
447            let destination = entry.get(name)?.as_str()?.to_string();
448            let held = entry.get(digest)?.as_str()?;
449            let held = held.parse::<crate::domain::ownership::Sha256>().ok()?;
450            Some((destination, held))
451        })
452        .collect()
453}