Skip to main content

specfold_core/export/markdown/
out.rs

1//! The `--out` folder of a Markdown export: checked before anything is written, then written
2//! with its manifest.
3
4use super::types::{MANIFEST, Target, Tree};
5use anyhow::{Context, Result, bail};
6use serde_json::{Value, json};
7use std::path::{Path, PathBuf};
8
9/// Checks `out` can take an export (missing, empty or an earlier export, outside the repository
10/// and `.spec`/`.git`) and returns the files the earlier export listed. `abs` is `out` made
11/// absolute by the caller; `out` is how messages name it.
12pub fn check_out(out: &Path, abs: &Path, root: &Path) -> Result<Vec<String>> {
13    // C221: the nearest existing folder resolved, so a symbolic link cannot hide a spec or git
14    // directory; the missing rest is appended as written.
15    let real = crate::paths::real_with_missing_tail(abs).unwrap_or_else(|| abs.to_path_buf());
16    let spec_or_git =
17        |p: &Path| p.components().any(|c| matches!(c.as_os_str().to_str(), Some(".spec" | ".spec.local" | ".git")));
18    if spec_or_git(out) || spec_or_git(&real) {
19        bail!("refusing to export into {}: it is inside a spec or git directory", out.display());
20    }
21    let root_real = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
22    if root_real.starts_with(&real) {
23        bail!("refusing to export into {}: it contains the repository", out.display());
24    }
25    // C259: a dangling link reads as missing but cannot be created as a folder; refuse in preview too.
26    if !abs.exists() && abs.symlink_metadata().is_ok() {
27        let to = std::fs::read_link(abs).map(|t| t.display().to_string()).unwrap_or_default();
28        let target = out.parent().map_or_else(|| PathBuf::from(&to), |p| p.join(&to));
29        bail!(
30            "{} is a symbolic link to {to}, which does not exist; create that folder or give another --out; next: mkdir -p {}",
31            out.display(),
32            target.display()
33        );
34    }
35    if !abs.exists() {
36        return Ok(vec![]);
37    }
38    if !abs.is_dir() {
39        bail!("{} is not a directory", out.display());
40    }
41    let canon = abs.canonicalize()?;
42    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
43    if root.starts_with(&canon) {
44        bail!("refusing to export into {}: it contains the repository", out.display());
45    }
46    let m = out.join(MANIFEST);
47    if abs.join(MANIFEST).is_file() {
48        let v: Value = serde_json::from_str(&std::fs::read_to_string(abs.join(MANIFEST))?)
49            .with_context(|| format!("reading {}", m.display()))?;
50        return Ok(v["files"]
51            .as_array()
52            .into_iter()
53            .flatten()
54            .filter_map(|f| f.as_str().map(str::to_string))
55            .collect());
56    }
57    if std::fs::read_dir(abs)?.next().is_some() {
58        bail!(
59            "refusing to export into {}: it is not empty and holds no {MANIFEST} from an earlier export",
60            out.display()
61        );
62    }
63    Ok(vec![])
64}
65
66/// Writes the tree and its manifest, removing the files of the previous export first.
67pub fn write(out: &Path, tree: &Tree, target: Target, previous: &[String]) -> Result<()> {
68    for f in previous {
69        if f.split('/').any(|s| s == ".." || s.is_empty()) || Path::new(f).is_absolute() {
70            continue;
71        }
72        let p = out.join(f);
73        if p.is_file() {
74            std::fs::remove_file(&p)?;
75            let mut dir = p.parent();
76            while let Some(d) = dir.filter(|d| *d != out) {
77                if std::fs::remove_dir(d).is_err() {
78                    break;
79                }
80                dir = d.parent();
81            }
82        }
83    }
84    for (rel, text) in &tree.files {
85        let p = out.join(rel);
86        std::fs::create_dir_all(p.parent().expect("an output path joined from a file name has a parent"))?;
87        std::fs::write(&p, text)?;
88    }
89    let manifest = json!({
90        "generator": "specfold",
91        "target": target.name(),
92        "files": tree.files.keys().collect::<Vec<_>>(),
93    });
94    // C222: an export of no documents is the manifest alone, in a folder made for it.
95    std::fs::create_dir_all(out)?;
96    std::fs::write(out.join(MANIFEST), serde_json::to_string_pretty(&manifest)? + "\n")?;
97    Ok(())
98}