1use camino::{Utf8Path, Utf8PathBuf};
15use serde::Serialize;
16
17use crate::domain::manifest::DOCS_SCRATCH_VAR;
18use crate::error::AppError;
19
20pub const SCHEMA: &str = "sdd.env/1";
22
23pub const ENVRC: &str = ".envrc";
25
26pub const ENVRC_LOCAL: &str = ".envrc.local";
28
29pub const DOTENV: &str = ".env";
31
32pub const GITIGNORE: &str = ".gitignore";
34
35pub const SOURCE_LOCAL: &str = "source_env_if_exists .envrc.local";
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
40#[serde(rename_all = "kebab-case")]
41pub enum Loader {
42 Direnv,
44 Dotenv,
46 None,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, clap::ValueEnum)]
52#[serde(rename_all = "kebab-case")]
53pub enum Item {
54 DocsScratchVariable,
56 DocsScratchIgnore,
58}
59
60impl Item {
61 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
73#[serde(rename_all = "kebab-case")]
74pub enum ItemState {
75 Wired,
77 Unwired,
79 NoLoader,
81 Outside,
83 Undeclared,
85}
86
87#[derive(Debug, Clone, Serialize)]
89pub struct ItemReport {
90 pub item: Item,
92 pub state: ItemState,
94 pub file: Option<Utf8PathBuf>,
96 pub value: Option<String>,
99}
100
101#[derive(Debug, Clone, Serialize)]
103pub struct Report {
104 pub schema: &'static str,
106 pub target: Utf8PathBuf,
108 pub loader: Loader,
110 pub variable_in_shell: Option<String>,
112 pub items: Vec<ItemReport>,
114 pub wrote: Vec<String>,
116}
117
118fn 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
129const 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
138fn 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
147fn 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
154fn 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(|"ed| 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
196fn 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
211fn 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
216fn 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
228fn 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
237fn 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
257fn ignore_forms(path: &Utf8Path) -> [String; 4] {
259 [
260 path.to_string(),
261 format!("/{path}"),
262 format!("{path}/"),
263 format!("/{path}/"),
264 ]
265}
266
267fn covered(target: &Utf8Path, path: &Utf8Path) -> bool {
269 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
283fn 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#[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
344fn 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
378fn 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
421pub 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}