Skip to main content

spec_driven_docs/services/
env.rs

1//! The shell environment a project's gates read, reported and written.
2//!
3//! Two items exist: the docs scratch variable, which overrides the location
4//! the instance records, and the ignore entry that keeps a docs scratch
5//! inside the repository out of version control. The report reads which
6//! shell loader the repository records and whether each item is in place.
7//! An apply writes one item through that loader, and nothing else.
8//!
9//! The loader is read from the repository's own files, never from the host:
10//! `.envrc` means direnv, `.env` means a dotenv loader, and neither means
11//! nothing loads a variable here. With direnv, the per-developer value goes
12//! to `.envrc.local`, which the repository ignores and `.envrc` sources.
13
14use camino::{Utf8Path, Utf8PathBuf};
15use serde::Serialize;
16
17use crate::domain::manifest::DOCS_SCRATCH_VAR;
18use crate::error::AppError;
19
20/// The machine schema `sdd env --json` declares.
21pub const SCHEMA: &str = "sdd.env/1";
22
23/// The direnv loader file.
24pub const ENVRC: &str = ".envrc";
25
26/// The per-developer file `.envrc` sources.
27pub const ENVRC_LOCAL: &str = ".envrc.local";
28
29/// The dotenv loader file.
30pub const DOTENV: &str = ".env";
31
32/// The repository's ignore file.
33pub const GITIGNORE: &str = ".gitignore";
34
35/// The line `.envrc` carries to load the per-developer file.
36pub const SOURCE_LOCAL: &str = "source_env_if_exists .envrc.local";
37
38/// Which shell loader the repository records.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
40#[serde(rename_all = "kebab-case")]
41pub enum Loader {
42    /// The repository carries `.envrc`.
43    Direnv,
44    /// The repository carries `.env` and no `.envrc`.
45    Dotenv,
46    /// The repository carries neither.
47    None,
48}
49
50/// One environment item this verb reports and writes.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, clap::ValueEnum)]
52#[serde(rename_all = "kebab-case")]
53pub enum Item {
54    /// The docs scratch variable, through the recorded loader.
55    DocsScratchVariable,
56    /// The ignore entry for a docs scratch inside the repository.
57    DocsScratchIgnore,
58}
59
60impl Item {
61    /// The word the command line and the JSON spell.
62    #[must_use]
63    pub const fn as_str(self) -> &'static str {
64        match self {
65            Self::DocsScratchVariable => "docs-scratch-variable",
66            Self::DocsScratchIgnore => "docs-scratch-ignore",
67        }
68    }
69}
70
71/// Where one item stands.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
73#[serde(rename_all = "kebab-case")]
74pub enum ItemState {
75    /// The item is in place.
76    Wired,
77    /// The item can be written and is not there yet.
78    Unwired,
79    /// No loader is recorded, so nothing loads the variable.
80    NoLoader,
81    /// The docs scratch sits outside the repository, so no entry applies.
82    Outside,
83    /// No docs scratch is declared, so there is nothing to ignore.
84    Undeclared,
85}
86
87/// One item's row.
88#[derive(Debug, Clone, Serialize)]
89pub struct ItemReport {
90    /// Which item.
91    pub item: Item,
92    /// Where it stands.
93    pub state: ItemState,
94    /// The file the item lives in, where one applies.
95    pub file: Option<Utf8PathBuf>,
96    /// The value the item names: the variable's value as the file or the
97    /// shell holds it, or the scratch path the entry covers.
98    pub value: Option<String>,
99}
100
101/// The whole report.
102#[derive(Debug, Clone, Serialize)]
103pub struct Report {
104    /// The machine schema of this object.
105    pub schema: &'static str,
106    /// The repository read.
107    pub target: Utf8PathBuf,
108    /// The loader the repository records.
109    pub loader: Loader,
110    /// Whether this shell carries the variable now.
111    pub variable_in_shell: Option<String>,
112    /// One row per item.
113    pub items: Vec<ItemReport>,
114    /// Every line an apply wrote, as `file: line`.
115    pub wrote: Vec<String>,
116}
117
118/// The loader the repository records.
119fn loader(target: &Utf8Path) -> Loader {
120    if target.join(ENVRC).is_file() {
121        Loader::Direnv
122    } else if target.join(DOTENV).is_file() {
123        Loader::Dotenv
124    } else {
125        Loader::None
126    }
127}
128
129/// The file the variable's line goes to under each loader.
130const fn variable_file(loader: Loader) -> Option<&'static str> {
131    match loader {
132        Loader::Direnv => Some(ENVRC_LOCAL),
133        Loader::Dotenv => Some(DOTENV),
134        Loader::None => None,
135    }
136}
137
138/// The assignment one loader file carries.
139fn assignment(loader: Loader, value: &str) -> String {
140    let quoted = format!("'{}'", value.replace('\'', r"'\''"));
141    match loader {
142        Loader::Direnv => format!("export {DOCS_SCRATCH_VAR}={quoted}"),
143        Loader::Dotenv | Loader::None => format!("{DOCS_SCRATCH_VAR}={quoted}"),
144    }
145}
146
147/// Whether a line assigns the variable, in either loader's spelling.
148fn assigns(line: &str) -> bool {
149    let line = line.trim_start();
150    let line = line.strip_prefix("export ").unwrap_or(line);
151    line.starts_with(&format!("{DOCS_SCRATCH_VAR}="))
152}
153
154/// The words of the first command on a shell line, with quotes removed.
155///
156/// A quoted word stays one word, whatever it holds. Backslashes follow
157/// Bash: outside quotes one escapes any character, inside double quotes it
158/// escapes only `$`, a backtick, `"`, `\`, or a newline and stays literal
159/// before anything else, and inside single quotes it is literal. An
160/// unquoted `;`, `&`, or `|` ends the command, and so does a `#` that opens
161/// a word.
162fn command_words(line: &str) -> Vec<String> {
163    let mut words = Vec::new();
164    let mut word: Option<String> = None;
165    let mut chars = line.chars().peekable();
166    while let Some(c) = chars.next() {
167        match c {
168            '\'' => {
169                let held = word.get_or_insert_with(String::new);
170                held.extend(chars.by_ref().take_while(|&quoted| quoted != '\''));
171            }
172            '"' => {
173                let held = word.get_or_insert_with(String::new);
174                while let Some(quoted) = chars.next() {
175                    match quoted {
176                        '"' => break,
177                        '\\' => match chars.peek() {
178                            Some('$' | '`' | '"' | '\\' | '\n') => held.extend(chars.next()),
179                            _ => held.push('\\'),
180                        },
181                        _ => held.push(quoted),
182                    }
183                }
184            }
185            '\\' => word.get_or_insert_with(String::new).extend(chars.next()),
186            ';' | '&' | '|' => break,
187            '#' if word.is_none() => break,
188            _ if c.is_whitespace() => words.extend(word.take()),
189            _ => word.get_or_insert_with(String::new).push(c),
190        }
191    }
192    words.extend(word);
193    words
194}
195
196/// Whether an `.envrc` line loads the per-developer file.
197///
198/// Only a command that reads the file counts, and only when the file is the
199/// operand it reads. A line that merely names it, such as
200/// `watch_file .envrc.local` or a trailing comment, loads nothing.
201fn sources_local(line: &str) -> bool {
202    let words = command_words(line);
203    matches!(
204        words.first().map(String::as_str),
205        Some("source_env" | "source_env_if_exists" | "source" | ".")
206    ) && words
207        .get(1)
208        .is_some_and(|operand| operand.trim_start_matches("./") == ENVRC_LOCAL)
209}
210
211/// Whether the repository's `.envrc` loads the per-developer file.
212fn envrc_sources_local(target: &Utf8Path) -> bool {
213    std::fs::read_to_string(target.join(ENVRC)).is_ok_and(|text| text.lines().any(sources_local))
214}
215
216/// The value one loader file assigns, unquoted, where it assigns one.
217fn assigned(text: &str) -> Option<String> {
218    text.lines().rfind(|line| assigns(line)).map(|line| {
219        let (_, value) = line.split_once('=').unwrap_or_default();
220        value
221            .trim()
222            .trim_matches('\'')
223            .trim_matches('"')
224            .to_string()
225    })
226}
227
228/// The docs scratch in effect: the variable, then the record.
229fn scratch(target: &Utf8Path) -> Option<Utf8PathBuf> {
230    crate::gates::paths::docs_scratch_variable().or_else(|| {
231        crate::services::installer::recorded_field(target, "docs_scratch")
232            .and_then(|value| value.as_str().map(Utf8PathBuf::from))
233            .filter(|path| !path.as_str().is_empty())
234    })
235}
236
237/// The scratch path relative to the target, where it sits inside it.
238fn inside(target: &Utf8Path, scratch: &Utf8Path) -> Option<Utf8PathBuf> {
239    let relative = if scratch.is_absolute() {
240        scratch.strip_prefix(target).ok()?.to_owned()
241    } else {
242        scratch.to_owned()
243    };
244    let escapes = relative
245        .components()
246        .any(|part| matches!(part, camino::Utf8Component::ParentDir));
247    (!escapes && !relative.as_str().is_empty()).then(|| {
248        Utf8PathBuf::from(
249            relative
250                .as_str()
251                .trim_start_matches("./")
252                .trim_end_matches('/'),
253        )
254    })
255}
256
257/// The ignore-file lines that name exactly one path.
258fn ignore_forms(path: &Utf8Path) -> [String; 4] {
259    [
260        path.to_string(),
261        format!("/{path}"),
262        format!("{path}/"),
263        format!("/{path}/"),
264    ]
265}
266
267/// Whether the repository ignores `path`.
268fn covered(target: &Utf8Path, path: &Utf8Path) -> bool {
269    // The scratch is a directory, and a directory-only pattern such as
270    // `.docs-scratch/` matches a path Git has never seen only when the path
271    // says it is one.
272    let directory = Utf8PathBuf::from(format!("{path}/"));
273    if let Some(answer) = crate::adapters::history::ignores(target, &directory) {
274        return answer;
275    }
276    let forms = ignore_forms(path);
277    std::fs::read_to_string(target.join(GITIGNORE)).is_ok_and(|text| {
278        text.lines()
279            .any(|line| forms.iter().any(|form| line.trim() == form))
280    })
281}
282
283/// The ignore entry's row for a declared docs scratch.
284fn ignore_row(target: &Utf8Path, path: &Utf8Path) -> ItemReport {
285    inside(target, path).map_or_else(
286        || ItemReport {
287            item: Item::DocsScratchIgnore,
288            state: ItemState::Outside,
289            file: None,
290            value: Some(path.to_string()),
291        },
292        |relative| ItemReport {
293            item: Item::DocsScratchIgnore,
294            state: if covered(target, &relative) {
295                ItemState::Wired
296            } else {
297                ItemState::Unwired
298            },
299            file: Some(Utf8PathBuf::from(GITIGNORE)),
300            value: Some(relative.to_string()),
301        },
302    )
303}
304
305/// Report the environment items of `target`.
306///
307/// SATISFIES setup:env-reports-the-loader-and-each-item
308#[must_use]
309pub fn report(target: &Utf8Path) -> Report {
310    let loader = loader(target);
311    let file = variable_file(loader);
312    let held = file.and_then(|file| std::fs::read_to_string(target.join(file)).ok());
313    let value = held.as_deref().and_then(assigned);
314    let variable = ItemReport {
315        item: Item::DocsScratchVariable,
316        state: match (loader, &value) {
317            (Loader::None, _) => ItemState::NoLoader,
318            (Loader::Direnv, Some(_)) if !envrc_sources_local(target) => ItemState::Unwired,
319            (_, Some(_)) => ItemState::Wired,
320            (_, None) => ItemState::Unwired,
321        },
322        file: file.map(Utf8PathBuf::from),
323        value,
324    };
325    let ignore = scratch(target).as_deref().map_or(
326        ItemReport {
327            item: Item::DocsScratchIgnore,
328            state: ItemState::Undeclared,
329            file: None,
330            value: None,
331        },
332        |path| ignore_row(target, path),
333    );
334    Report {
335        schema: SCHEMA,
336        target: target.to_owned(),
337        loader,
338        variable_in_shell: crate::domain::paths::variable(DOCS_SCRATCH_VAR),
339        items: vec![variable, ignore],
340        wrote: Vec::new(),
341    }
342}
343
344/// Append `line` to the file at `path` unless a line already satisfies
345/// `held`, keeping every byte already there.
346fn ensure_line(
347    target: &Utf8Path,
348    file: &str,
349    line: &str,
350    held: impl Fn(&str) -> bool,
351    wrote: &mut Vec<String>,
352) -> Result<(), AppError> {
353    let path = target.join(file);
354    if path.is_symlink() {
355        return Err(AppError::Refused(format!(
356            "{file} is a symlink; refusing to write through it"
357        )));
358    }
359    let text = match std::fs::read_to_string(&path) {
360        Ok(text) => text,
361        Err(source) if source.kind() == std::io::ErrorKind::NotFound => String::new(),
362        Err(source) => return Err(AppError::Io(source)),
363    };
364    if text.lines().any(&held) {
365        return Ok(());
366    }
367    let mut next = text;
368    if !next.is_empty() && !next.ends_with('\n') {
369        next.push('\n');
370    }
371    next.push_str(line);
372    next.push('\n');
373    crate::adapters::fs::write_atomic(&path, next.as_bytes())?;
374    wrote.push(format!("{file}: {line}"));
375    Ok(())
376}
377
378/// Set the variable's line in one file, replacing an earlier assignment.
379fn set_assignment(
380    target: &Utf8Path,
381    file: &str,
382    line: &str,
383    wrote: &mut Vec<String>,
384) -> Result<(), AppError> {
385    let path = target.join(file);
386    if path.is_symlink() {
387        return Err(AppError::Refused(format!(
388            "{file} is a symlink; refusing to write through it"
389        )));
390    }
391    let text = match std::fs::read_to_string(&path) {
392        Ok(text) => text,
393        Err(source) if source.kind() == std::io::ErrorKind::NotFound => String::new(),
394        Err(source) => return Err(AppError::Io(source)),
395    };
396    if text.lines().any(|held| held == line) {
397        return Ok(());
398    }
399    let mut next = String::new();
400    let mut replaced = false;
401    for held in text.lines() {
402        if assigns(held) && !replaced {
403            next.push_str(line);
404            replaced = true;
405        } else if assigns(held) {
406            continue;
407        } else {
408            next.push_str(held);
409        }
410        next.push('\n');
411    }
412    if !replaced {
413        next.push_str(line);
414        next.push('\n');
415    }
416    crate::adapters::fs::write_atomic(&path, next.as_bytes())?;
417    wrote.push(format!("{file}: {line}"));
418    Ok(())
419}
420
421/// Write one item through the loader the repository records.
422///
423/// SATISFIES setup:env-writes-one-item-through-the-recorded-loader
424///
425/// # Errors
426///
427/// [`AppError::Usage`] where the variable item names no value, and
428/// [`AppError::Refused`] where no loader is recorded, where the scratch sits
429/// outside the repository or is not declared, or where a file to write is a
430/// symlink.
431pub fn apply(target: &Utf8Path, item: Item, value: Option<&str>) -> Result<Report, AppError> {
432    let mut wrote = Vec::new();
433    match item {
434        Item::DocsScratchVariable => {
435            let Some(value) = value.filter(|value| !value.trim().is_empty()) else {
436                return Err(AppError::Usage(format!(
437                    "--apply {} needs --value <PATH>: the location this host keeps the docs scratch at",
438                    item.as_str()
439                )));
440            };
441            let loader = loader(target);
442            let Some(file) = variable_file(loader) else {
443                return Err(AppError::Refused(format!(
444                    "{target} records no shell loader, neither {ENVRC} nor {DOTENV}, so nothing would load the variable; set `{}` in the shell that runs the gates",
445                    assignment(Loader::None, value)
446                )));
447            };
448            set_assignment(target, file, &assignment(loader, value), &mut wrote)?;
449            if loader == Loader::Direnv {
450                ensure_line(target, ENVRC, SOURCE_LOCAL, sources_local, &mut wrote)?;
451            }
452            let forms = ignore_forms(Utf8Path::new(file));
453            ensure_line(
454                target,
455                GITIGNORE,
456                file,
457                |line| forms.iter().any(|form| line.trim() == form),
458                &mut wrote,
459            )?;
460        }
461        Item::DocsScratchIgnore => {
462            let Some(scratch) = scratch(target) else {
463                return Err(AppError::Refused(format!(
464                    "{target} declares no docs scratch, so there is nothing to ignore"
465                )));
466            };
467            let Some(relative) = inside(target, &scratch) else {
468                return Err(AppError::Refused(format!(
469                    "the docs scratch {scratch} sits outside {target}, so no ignore entry applies"
470                )));
471            };
472            if !covered(target, &relative) {
473                let forms = ignore_forms(&relative);
474                ensure_line(
475                    target,
476                    GITIGNORE,
477                    &format!("/{relative}/"),
478                    |line| forms.iter().any(|form| line.trim() == form),
479                    &mut wrote,
480                )?;
481            }
482        }
483    }
484    let mut report = report(target);
485    report.wrote = wrote;
486    Ok(report)
487}
488
489#[cfg(test)]
490mod tests {
491    #![allow(
492        clippy::unwrap_used,
493        reason = "a test panics as its failure signal, not as control flow"
494    )]
495
496    use super::*;
497
498    #[test]
499    fn an_assignment_reads_back_in_either_spelling() {
500        assert_eq!(
501            assigned("export SDD_DOCS_SCRATCH='../notes'\n").as_deref(),
502            Some("../notes")
503        );
504        assert_eq!(assigned("SDD_DOCS_SCRATCH=\"x\"\n").as_deref(), Some("x"));
505        assert_eq!(assigned("OTHER=1\n"), None);
506    }
507
508    #[test]
509    fn only_a_command_that_reads_the_local_file_loads_it() {
510        assert!(sources_local("source_env_if_exists .envrc.local"));
511        assert!(sources_local("  source_env ./.envrc.local"));
512        assert!(sources_local("source \".envrc.local\""));
513        assert!(!sources_local("watch_file .envrc.local"));
514        assert!(!sources_local("# source_env_if_exists .envrc.local"));
515        assert!(!sources_local("source_env_if_exists .envrc.other"));
516        assert!(!sources_local(
517            "source_env_if_exists .envrc.private # .envrc.local"
518        ));
519        assert!(!sources_local(
520            "source_env_if_exists \".envrc.local backup\""
521        ));
522        assert!(sources_local("source_env_if_exists .envrc.local;"));
523        assert!(sources_local(
524            "source_env_if_exists .envrc.local && echo loaded"
525        ));
526        assert!(sources_local("source_env_if_exists '.envrc.local'||true"));
527        assert!(!sources_local(r#"source_env_if_exists "\.envrc.local""#));
528        assert!(sources_local(r"source_env_if_exists \.envrc.local"));
529        assert!(!sources_local(r"source_env_if_exists '\.envrc.local'"));
530        assert_eq!(command_words(r#"a "x\"y\\z\q""#), ["a", r#"x"y\z\q"#]);
531    }
532
533    #[test]
534    fn a_value_with_a_quote_stays_one_shell_word() {
535        assert_eq!(
536            assignment(Loader::Direnv, "it's"),
537            r"export SDD_DOCS_SCRATCH='it'\''s'"
538        );
539    }
540
541    #[test]
542    fn a_scratch_inside_the_target_is_relative_and_one_outside_is_none() {
543        let target = Utf8Path::new("/work/project");
544        assert_eq!(
545            inside(target, Utf8Path::new(".docs-scratch/")),
546            Some(Utf8PathBuf::from(".docs-scratch"))
547        );
548        assert_eq!(
549            inside(target, Utf8Path::new("/work/project/notes")),
550            Some(Utf8PathBuf::from("notes"))
551        );
552        assert_eq!(inside(target, Utf8Path::new("../beside")), None);
553        assert_eq!(inside(target, Utf8Path::new("/elsewhere")), None);
554    }
555}