Skip to main content

spec_driven_docs/gates/
paths.rs

1//! Where an instance keeps the documents the gates read.
2//!
3//! One of these locations is declared rather than fixed: the docs scratch.
4//! It is recorded in the manifest and named by one environment variable,
5//! and the variable wins where it is set.
6//!
7//! The documentation root comes from the manifest when one exists, is
8//! discovered from the conventional layouts when none does, and defaults to
9//! `_docs`. Known-issue roots follow the same ladder, and explicit arguments
10//! win over all of it — a repository keeping records outside the root passes
11//! the directories holding them. Nothing here judges content; that is each
12//! gate's business.
13
14use camino::{Utf8Path, Utf8PathBuf};
15
16use crate::domain::manifest::{DOCS_SCRATCH_VAR, MANIFEST_PATH};
17use crate::gates::{GateCtx, GateError};
18
19/// One field of the instance manifest, read permissively.
20///
21/// A gate reads the record as free JSON rather than through `Manifest::parse`
22/// on purpose: a record of another schema version is a reason to upgrade, and
23/// a gate that went blind there would report a clean tree it never read.
24fn manifest_field(ctx: &GateCtx, key: &str) -> Option<serde_json::Value> {
25    let text = std::fs::read_to_string(ctx.path(MANIFEST_PATH)).ok()?;
26    let value: serde_json::Value = serde_json::from_str(&text).ok()?;
27    value.get(key).cloned().filter(|found| !found.is_null())
28}
29
30/// What a variable carries here, trimmed, or `None` when it is unset or blank.
31fn variable(name: &str) -> Option<Utf8PathBuf> {
32    std::env::var(name)
33        .ok()
34        .map(|value| value.trim().to_string())
35        .filter(|value| !value.is_empty())
36        .map(Utf8PathBuf::from)
37}
38
39/// Resolve the docs scratch: the variable first, then the recorded path.
40///
41/// `None` means the project declared none. A caller with a discovery
42/// candidate of its own supplies it; there is none here, because a gate that
43/// guessed the location would judge a directory nobody declared.
44#[must_use]
45pub fn docs_scratch(ctx: &GateCtx) -> Option<Utf8PathBuf> {
46    docs_scratch_with(ctx, variable(DOCS_SCRATCH_VAR))
47}
48
49/// What [`DOCS_SCRATCH_VAR`] carries here, or `None` when it is unset.
50///
51/// The one place the environment is read for this value, so a caller that
52/// resolves it can be tested by supplying the answer instead.
53#[must_use]
54pub fn docs_scratch_variable() -> Option<Utf8PathBuf> {
55    variable(DOCS_SCRATCH_VAR)
56}
57
58/// The resolution, with the variable's value supplied.
59///
60/// The environment is read at one boundary and passed in, so every case is
61/// reachable from a test. This crate forbids unsafe code, and setting a
62/// variable is unsafe from the 2024 edition on.
63#[must_use]
64pub fn docs_scratch_with(ctx: &GateCtx, named: Option<Utf8PathBuf>) -> Option<Utf8PathBuf> {
65    named.or_else(|| {
66        manifest_field(ctx, "docs_scratch")
67            .and_then(|value| value.as_str().map(Utf8PathBuf::from))
68            .filter(|path| !path.as_str().is_empty())
69    })
70}
71
72/// The instance's documentation root, relative to the repository.
73#[must_use]
74pub fn docs_root(ctx: &GateCtx) -> Utf8PathBuf {
75    if let Some(named) = ctx.named_docs_root() {
76        return named.to_path_buf();
77    }
78    if let Ok(text) = std::fs::read_to_string(ctx.path(MANIFEST_PATH))
79        && let Ok(value) = serde_json::from_str::<serde_json::Value>(&text)
80        && let Some(root) = value.get("docs_root").and_then(serde_json::Value::as_str)
81        && !root.is_empty()
82    {
83        return Utf8PathBuf::from(root);
84    }
85    for candidate in ["_docs", "docs"] {
86        if discovered(ctx, &Utf8Path::new(candidate).join("specs")) {
87            return Utf8PathBuf::from(candidate);
88        }
89    }
90    Utf8PathBuf::from("_docs")
91}
92
93/// The directories that may hold known-issue records, relative to the
94/// repository. Arguments win; a manifest names one root; a bare consumer's
95/// roots are discovered.
96#[must_use]
97pub fn ki_record_roots(ctx: &GateCtx, args: &[String]) -> Vec<Utf8PathBuf> {
98    if !args.is_empty() {
99        return args.iter().map(Utf8PathBuf::from).collect();
100    }
101    if ctx.path(MANIFEST_PATH).is_file() {
102        return vec![docs_root(ctx).join("reference/known-issues")];
103    }
104    ["_docs", "docs"]
105        .into_iter()
106        .map(|candidate| Utf8Path::new(candidate).join("reference/known-issues"))
107        .filter(|root| discovered(ctx, root))
108        .collect()
109}
110
111/// Whether a discovered candidate is a directory the caller must read.
112///
113/// A candidate whose metadata cannot be read is kept rather than dropped.
114/// `is_dir` answers false for a directory the process cannot stat, so
115/// dropping it there would report an unreadable layout as a layout the
116/// repository does not keep. Kept, it reaches the reader, which raises the
117/// failure or reports the layout as moved rather than judging a tree it
118/// never opened.
119fn discovered(ctx: &GateCtx, root: &Utf8Path) -> bool {
120    match std::fs::metadata(ctx.path(root)) {
121        Ok(metadata) => metadata.is_dir(),
122        Err(source) => source.kind() != std::io::ErrorKind::NotFound,
123    }
124}
125
126/// Every known-issue record under the resolved roots, repository-relative.
127///
128/// A root that is not there is a zone the repository does not keep, and it
129/// is skipped. Every other failure is raised: a directory the process
130/// cannot read holds records this returns none of, and reporting that as an
131/// empty zone would read as a clean review.
132///
133/// # Errors
134///
135/// [`crate::gates::GateError::Io`] when a present root cannot be listed.
136/// The records this gate judges, filtered.
137///
138/// [`ki_records`] stays unfiltered because the same records are support for
139/// `suppression-names-its-case`, which resolves a case id against them
140/// rather than judging their contents. A gate that judges a record's own
141/// text calls this one.
142///
143/// # Errors
144///
145/// See [`ki_records`].
146pub fn ki_records_judged(ctx: &GateCtx, args: &[String]) -> Result<Vec<Utf8PathBuf>, GateError> {
147    Ok(ctx.retained(ki_records(ctx, args)?))
148}
149
150/// Every known-issue record the instance carries, unfiltered.
151///
152/// Unfiltered because the same records are support for
153/// `suppression-names-its-case`. A gate judging a record's own text calls
154/// [`ki_records_judged`].
155///
156/// # Errors
157///
158/// [`GateError::Io`] naming the root that could not be read.
159pub fn ki_records(ctx: &GateCtx, args: &[String]) -> Result<Vec<Utf8PathBuf>, GateError> {
160    let mut records = Vec::new();
161    for root in ki_record_roots(ctx, args) {
162        let entries = match ctx.path(&root).read_dir_utf8() {
163            Ok(entries) => entries,
164            Err(source) if source.kind() == std::io::ErrorKind::NotFound => continue,
165            Err(source) => return Err(GateError::io(&root, source)),
166        };
167        let mut names = Vec::new();
168        for entry in entries {
169            let entry = entry.map_err(|source| GateError::io(&root, source))?;
170            if !entry
171                .file_type()
172                .map_err(|source| GateError::io(&root, source))?
173                .is_file()
174            {
175                continue;
176            }
177            let name = entry.file_name().to_string();
178            if name
179                .strip_prefix("KI-")
180                .and_then(|rest| rest.strip_suffix(".md"))
181                .is_some_and(|slug| !slug.is_empty())
182            {
183                names.push(name);
184            }
185        }
186        names.sort();
187        records.extend(names.into_iter().map(|name| root.join(name)));
188    }
189    Ok(records)
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    fn ctx(dir: &tempfile::TempDir) -> GateCtx {
197        GateCtx::new(dir.path().to_str().unwrap())
198    }
199
200    fn write(dir: &tempfile::TempDir, path: &str, text: &str) {
201        let path = dir.path().join(path);
202        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
203        std::fs::write(path, text).unwrap();
204    }
205
206    #[test]
207    fn the_docs_scratch_takes_the_variable_then_the_record() {
208        let dir = tempfile::tempdir().unwrap();
209        let ctx = ctx(&dir);
210        assert_eq!(docs_scratch_with(&ctx, None), None);
211
212        write(
213            &dir,
214            ".spec-driven-docs/manifest.json",
215            "{\"docs_scratch\": \"../beside\"}\n",
216        );
217        assert_eq!(
218            docs_scratch_with(&ctx, None),
219            Some(Utf8PathBuf::from("../beside"))
220        );
221        assert_eq!(
222            docs_scratch_with(&ctx, Some(Utf8PathBuf::from("inside"))),
223            Some(Utf8PathBuf::from("inside"))
224        );
225    }
226
227    #[test]
228    fn manifest_root_wins() {
229        let dir = tempfile::tempdir().unwrap();
230        write(
231            &dir,
232            ".spec-driven-docs/manifest.json",
233            "{\n  \"docs_root\": \"docs\"\n}\n",
234        );
235        assert_eq!(docs_root(&ctx(&dir)), "docs");
236    }
237
238    #[test]
239    fn roots_are_discovered_without_a_manifest() {
240        let dir = tempfile::tempdir().unwrap();
241        write(&dir, "docs/specs/SPEC-sample.md", "# S\n");
242        assert_eq!(docs_root(&ctx(&dir)), "docs");
243
244        let both = tempfile::tempdir().unwrap();
245        write(&both, "_docs/specs/SPEC-sample.md", "# S\n");
246        write(&both, "docs/specs/SPEC-sample.md", "# S\n");
247        assert_eq!(docs_root(&ctx(&both)), "_docs");
248
249        let neither = tempfile::tempdir().unwrap();
250        assert_eq!(docs_root(&ctx(&neither)), "_docs");
251    }
252
253    #[test]
254    fn record_arguments_win_over_discovery() {
255        let dir = tempfile::tempdir().unwrap();
256        write(&dir, "docs/reference/known-issues/KI-real.md", "# R\n");
257        let roots = ki_record_roots(&ctx(&dir), &["tests/fixtures".to_string()]);
258        assert_eq!(roots, vec![Utf8PathBuf::from("tests/fixtures")]);
259    }
260
261    #[test]
262    fn records_follow_the_manifest_root() {
263        let dir = tempfile::tempdir().unwrap();
264        write(
265            &dir,
266            ".spec-driven-docs/manifest.json",
267            "{\n  \"docs_root\": \"docs\"\n}\n",
268        );
269        write(&dir, "docs/reference/known-issues/KI-vendor.md", "# V\n");
270        write(&dir, "docs/reference/known-issues/KI-.md", "# empty slug\n");
271        write(
272            &dir,
273            "docs/reference/known-issues/notes.md",
274            "# not a record\n",
275        );
276        assert_eq!(
277            ki_records(&ctx(&dir), &[]).unwrap(),
278            vec![Utf8PathBuf::from(
279                "docs/reference/known-issues/KI-vendor.md"
280            )]
281        );
282    }
283
284    #[test]
285    fn bare_consumer_roots_are_discovered() {
286        let dir = tempfile::tempdir().unwrap();
287        write(&dir, "docs/reference/known-issues/KI-a.md", "# A\n");
288        write(&dir, "docs/reference/known-issues/KI-b.md", "# B\n");
289        assert_eq!(
290            ki_records(&ctx(&dir), &[]).unwrap(),
291            vec![
292                Utf8PathBuf::from("docs/reference/known-issues/KI-a.md"),
293                Utf8PathBuf::from("docs/reference/known-issues/KI-b.md"),
294            ]
295        );
296    }
297
298    #[test]
299    fn an_unreadable_layout_is_not_read_as_an_absent_one() {
300        let dir = tempfile::tempdir().unwrap();
301        std::fs::create_dir_all(dir.path().join("docs/specs")).unwrap();
302        assert_eq!(docs_root(&ctx(&dir)), "docs");
303
304        let specs = dir.path().join("docs/specs");
305        let mut mode = std::fs::metadata(&specs).unwrap().permissions();
306        std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o000);
307        std::fs::set_permissions(dir.path().join("docs"), mode.clone()).unwrap();
308        let resolved = docs_root(&ctx(&dir));
309        std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o755);
310        std::fs::set_permissions(dir.path().join("docs"), mode).unwrap();
311        assert_eq!(
312            resolved, "docs",
313            "an unreadable layout fell through to the default root"
314        );
315    }
316
317    #[test]
318    fn an_unsearchable_ancestor_is_raised_rather_than_discovered_away() {
319        let dir = tempfile::tempdir().unwrap();
320        std::fs::create_dir_all(dir.path().join("docs/reference/known-issues")).unwrap();
321        let ancestor = dir.path().join("docs/reference");
322        let mut mode = std::fs::metadata(&ancestor).unwrap().permissions();
323        std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o000);
324        std::fs::set_permissions(&ancestor, mode.clone()).unwrap();
325        let raised = ki_records(&ctx(&dir), &[]).is_err();
326        std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o755);
327        std::fs::set_permissions(&ancestor, mode).unwrap();
328        assert!(raised, "an unsearchable ancestor listed as no zone");
329    }
330
331    #[test]
332    fn an_absent_zone_is_skipped_and_an_unreadable_one_is_raised() {
333        let dir = tempfile::tempdir().unwrap();
334        write(&dir, "docs/specs/SPEC-a.md", "# A\n");
335        assert!(ki_records(&ctx(&dir), &[]).unwrap().is_empty());
336
337        let zone = dir.path().join("docs/reference/known-issues");
338        std::fs::create_dir_all(&zone).unwrap();
339        let mut mode = std::fs::metadata(&zone).unwrap().permissions();
340        std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o000);
341        std::fs::set_permissions(&zone, mode.clone()).unwrap();
342        let raised = ki_records(&ctx(&dir), &[]).is_err();
343        std::os::unix::fs::PermissionsExt::set_mode(&mut mode, 0o755);
344        std::fs::set_permissions(&zone, mode).unwrap();
345        assert!(raised, "an unreadable zone listed as empty");
346    }
347}