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