1use camino::{Utf8Path, Utf8PathBuf};
15
16use crate::domain::manifest::{DOCS_SCRATCH_VAR, MANIFEST_PATH};
17use crate::gates::{GateCtx, GateError};
18
19fn 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
30fn 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#[must_use]
45pub fn docs_scratch(ctx: &GateCtx) -> Option<Utf8PathBuf> {
46 docs_scratch_with(ctx, variable(DOCS_SCRATCH_VAR))
47}
48
49#[must_use]
54pub fn docs_scratch_variable() -> Option<Utf8PathBuf> {
55 variable(DOCS_SCRATCH_VAR)
56}
57
58#[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#[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#[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
111fn 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
126pub fn ki_records_judged(ctx: &GateCtx, args: &[String]) -> Result<Vec<Utf8PathBuf>, GateError> {
147 Ok(ctx.retained(ki_records(ctx, args)?))
148}
149
150pub 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}