calepin 0.0.51

A Rust CLI for preprocessing Typst documents with executable code chunks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use anyhow::{anyhow, Context, Result};
use std::path::{Path, PathBuf};

use crate::typst::model::LayoutPaths;
pub use crate::utils::path::slash_path;

pub(crate) const CALEPIN_DIR: &str = ".calepin";

/// Name prefix shared by every generated Typst entry file Calepin writes beside
/// a source document. The leading dot keeps the files out of ordinary listings
/// and out of website page discovery, which skips hidden paths.
pub const ENTRY_FILE_PREFIX: &str = ".calepin-entry.";

/// Suffixes appended after the document stem, one per generated entry file.
pub const ENTRY_FILE_NAMES: &[&str] = &["source.typ", "wrapper.typ", "query-wrapper.typ"];

/// True when `path` names a generated entry file. Callers that walk a project
/// tree (website discovery, static copying, link checks, the watcher) use this
/// to ignore Calepin's own scratch files.
pub fn is_generated_entry_file(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.starts_with(ENTRY_FILE_PREFIX))
}

/// Delete the generated entry files for one document. Callers run this after a
/// successful render: keeping them after a failure lets Typst's error spans,
/// which point into the entry file, still resolve.
pub fn remove_entry_files(layout: &LayoutPaths) {
    for path in layout.entry_paths() {
        let _ = std::fs::remove_file(path);
    }
}

/// Documents whose stale entry files this process has already swept.
static SWEPT_DOCUMENTS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<PathBuf>>> =
    std::sync::OnceLock::new();

/// Remove leftover entry files for one document, once per process.
///
/// A build removes its own entry files on success, but a failed render keeps
/// them on purpose so Typst's error spans still resolve, and a panic or a
/// `SIGKILL` skips cleanup entirely. Sweeping before the first staging of each
/// document makes those strays self-healing rather than cumulative.
///
/// The once-per-process guard matters: `prepare_preprocess_plan` runs again on
/// every watch iteration, and `write_staged_source` leaves an unchanged file
/// untouched so its mtime stays put. Deleting on each iteration would bump the
/// mtime every time and make the child `typst watch` re-render on edits that
/// change nothing it can see.
pub fn sweep_stale_entry_files(layout: &LayoutPaths) {
    let swept = SWEPT_DOCUMENTS.get_or_init(Default::default);
    let Ok(mut swept) = swept.lock() else {
        return;
    };
    if !swept.insert(layout.input.clone()) {
        return;
    }
    remove_entry_files(layout);
}

/// Removes a document's entry files if the current thread unwinds.
///
/// The normal cleanup paths are explicit calls after a render, and a *failed*
/// render deliberately keeps its entry files so Typst's error spans still
/// resolve. A panic is different: there are no diagnostics pointing into the
/// file, so nothing is lost by removing it. Dropping without a panic does
/// nothing, leaving the deliberate keep-on-failure behavior intact.
///
/// This cannot help with `SIGKILL`; `sweep_stale_entry_files` is what makes
/// those strays self-healing.
pub struct EntryFilePanicGuard {
    layout: LayoutPaths,
    keep: bool,
}

impl EntryFilePanicGuard {
    pub fn new(layout: &LayoutPaths, keep: bool) -> Self {
        Self {
            layout: layout.clone(),
            keep,
        }
    }
}

impl Drop for EntryFilePanicGuard {
    fn drop(&mut self) {
        if self.keep || !std::thread::panicking() {
            return;
        }
        remove_entry_files(&self.layout);
    }
}

/// Name of one generated entry file for the document with this stem.
pub fn entry_file_name_for(stem: &str, name: &str) -> String {
    format!("{ENTRY_FILE_PREFIX}{stem}.{name}")
}

/// Delete the generated entry files for a document identified by its source
/// path. Website builds clean up page by page rather than sweeping the source
/// tree, so a concurrent build or watcher keeps its own in-flight entry files.
pub fn remove_entry_files_for_document(input: &Path) {
    let (Some(dir), Some(stem)) = (
        input.parent(),
        input.file_stem().and_then(|stem| stem.to_str()),
    ) else {
        return;
    };
    for name in ENTRY_FILE_NAMES {
        let _ = std::fs::remove_file(dir.join(entry_file_name_for(stem, name)));
    }
}

/// Every generated entry file under `dir`, sorted. `calepin clean` sweeps the
/// tree with this; builds clean up per document instead.
pub fn find_entry_files(dir: &Path) -> Result<Vec<PathBuf>> {
    let mut out = Vec::new();
    collect_entry_files(dir, &mut out)?;
    out.sort();
    Ok(out)
}

fn collect_entry_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(_) => return Ok(()),
    };
    for entry in entries {
        let path = entry?.path();
        if path.is_dir() {
            let skip = path
                .file_name()
                .and_then(|name| name.to_str())
                .is_some_and(|name| crate::utils::static_files::COMMON_SKIP_DIRS.contains(&name));
            if !skip {
                collect_entry_files(&path, out)?;
            }
        } else if is_generated_entry_file(&path) {
            out.push(path);
        }
    }
    Ok(())
}

pub fn resolve_layout(input: &Path, root: Option<&Path>) -> Result<LayoutPaths> {
    resolve_layout_in_dir(input, root, Path::new(CALEPIN_DIR))
}

pub fn resolve_layout_in_dir(
    input: &Path,
    root: Option<&Path>,
    artifact_dir: &Path,
) -> Result<LayoutPaths> {
    let input_abs = canonicalize_input_file(input)?;
    let root_abs = match root {
        Some(root) => canonicalize_root_dir(root)?,
        None => input_abs
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| PathBuf::from(".")),
    };

    let input_rel = input_abs
        .strip_prefix(&root_abs)
        .map(Path::to_path_buf)
        .map_err(|_| {
            anyhow!(
                "input `{}` is not under root `{}`",
                input_abs.display(),
                root_abs.display()
            )
        })?;
    let stem = input_stem(&input_rel)?;
    let base = root_abs.join(artifact_dir).join(&stem);
    let results_path = base.join("results.json");
    let work_dir = input_abs
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| root_abs.clone());

    Ok(LayoutPaths {
        root: root_abs,
        input: input_abs,
        input_rel: input_rel.clone(),
        render_input: input_rel.clone(),
        work_dir,
        artifact_dir: base.clone(),
        results_path,
        figures_dir: base.join("figures"),
    })
}

pub fn artifact_reference(root: &Path, path: &Path) -> Result<String> {
    let rel = path.strip_prefix(root).map_err(|_| {
        anyhow!(
            "artifact `{}` is not under root `{}`",
            path.display(),
            root.display()
        )
    })?;
    Ok(format!("/{}", slash_path(rel)))
}

pub fn project_relative_path(root: &Path, path: &Path) -> String {
    path.strip_prefix(root)
        .map(slash_path)
        .unwrap_or_else(|_| display_path(path))
}

fn canonicalize_input_file(path: &Path) -> Result<PathBuf> {
    let path = canonicalize_existing_path(path, "input")?;
    let metadata = std::fs::metadata(&path)
        .with_context(|| format!("failed to inspect {}", path.display()))?;
    if !metadata.is_file() {
        return Err(anyhow!("input `{}` must be a file", path.display()));
    }
    Ok(path)
}

fn canonicalize_root_dir(path: &Path) -> Result<PathBuf> {
    let path = canonicalize_existing_path(path, "root")?;
    let metadata = std::fs::metadata(&path)
        .with_context(|| format!("failed to inspect {}", path.display()))?;
    if !metadata.is_dir() {
        return Err(anyhow!("root `{}` must be a directory", path.display()));
    }
    Ok(path)
}

fn canonicalize_existing_path(path: &Path, label: &str) -> Result<PathBuf> {
    std::fs::canonicalize(path)
        .with_context(|| format!("failed to resolve {label} `{}`", path.display()))
}

fn display_path(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

fn input_stem(input_rel: &Path) -> Result<PathBuf> {
    let mut stem = input_rel.to_path_buf();
    if stem.extension().and_then(|extension| extension.to_str()) != Some("typ") {
        return Err(anyhow!(
            "input `{}` must have a .typ extension",
            input_rel.display()
        ));
    }
    stem.set_extension("");
    Ok(stem)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn lays_out_root_relative_nested_input() {
        let dir = tempfile::tempdir().unwrap();
        let input = dir.path().join("chapters").join("intro.typ");
        std::fs::create_dir_all(input.parent().unwrap()).unwrap();
        std::fs::write(&input, "").unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        let layout = resolve_layout(&input, Some(dir.path())).unwrap();

        assert_eq!(layout.input_rel, PathBuf::from("chapters/intro.typ"));
        assert_eq!(layout.artifact_root(), root.join(".calepin"));
        assert_eq!(
            layout.results_path,
            root.join(".calepin/chapters/intro/results.json")
        );
        assert_eq!(
            layout.figures_dir,
            root.join(".calepin/chapters/intro/figures")
        );
    }

    #[test]
    fn defaults_root_to_input_directory() {
        let dir = tempfile::tempdir().unwrap();
        let input = dir.path().join("paper.typ");
        std::fs::write(&input, "").unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        let layout = resolve_layout(&input, None).unwrap();

        assert_eq!(layout.input_rel, PathBuf::from("paper.typ"));
        assert_eq!(
            layout.results_path,
            root.join(".calepin/paper/results.json")
        );
    }

    #[test]
    fn custom_artifact_dir_changes_generated_paths() {
        let dir = tempfile::tempdir().unwrap();
        let input = dir.path().join("paper.typ");
        std::fs::write(&input, "").unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        let layout = resolve_layout_in_dir(&input, None, Path::new("_calepin")).unwrap();

        assert_eq!(layout.artifact_dir, root.join("_calepin/paper"));
        assert_eq!(layout.artifact_root(), root.join("_calepin"));
        assert_eq!(
            layout.results_path,
            root.join("_calepin/paper/results.json")
        );
        assert_eq!(layout.figures_dir, root.join("_calepin/paper/figures"));
    }

    #[test]
    fn rejects_missing_input() {
        let dir = tempfile::tempdir().unwrap();
        let input = dir.path().join("missing.typ");

        let err = resolve_layout(&input, Some(dir.path()))
            .unwrap_err()
            .to_string();

        assert!(err.contains("failed to resolve input"), "{err}");
        assert!(err.contains("missing.typ"), "{err}");
    }

    #[test]
    fn rejects_directory_input() {
        let dir = tempfile::tempdir().unwrap();
        let input = dir.path().join("paper.typ");
        std::fs::create_dir(&input).unwrap();

        let err = resolve_layout(&input, Some(dir.path()))
            .unwrap_err()
            .to_string();

        assert!(err.contains("must be a file"), "{err}");
        assert!(err.contains("paper.typ"), "{err}");
    }

    #[test]
    fn rejects_missing_root() {
        let dir = tempfile::tempdir().unwrap();
        let input = dir.path().join("paper.typ");
        let root = dir.path().join("missing-root");
        std::fs::write(&input, "").unwrap();

        let err = resolve_layout(&input, Some(&root)).unwrap_err().to_string();

        assert!(err.contains("failed to resolve root"), "{err}");
        assert!(err.contains("missing-root"), "{err}");
    }

    #[test]
    fn rejects_file_root() {
        let dir = tempfile::tempdir().unwrap();
        let input = dir.path().join("paper.typ");
        let root = dir.path().join("calepin.toml");
        std::fs::write(&input, "").unwrap();
        std::fs::write(&root, "").unwrap();

        let err = resolve_layout(&input, Some(&root)).unwrap_err().to_string();

        assert!(err.contains("must be a directory"), "{err}");
        assert!(err.contains("calepin.toml"), "{err}");
    }

    #[test]
    fn rejects_missing_parent_segment_input_before_layout() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("project");
        std::fs::create_dir(&root).unwrap();
        let input = root.join("../outside.typ");

        let err = resolve_layout(&input, Some(&root)).unwrap_err().to_string();

        assert!(err.contains("failed to resolve input"), "{err}");
        assert!(err.contains("outside.typ"), "{err}");
    }

    #[test]
    fn artifact_refs_are_root_relative_with_slashes() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".calepin/paper/figures/fig.svg");
        assert_eq!(
            artifact_reference(dir.path(), &path).unwrap(),
            "/.calepin/paper/figures/fig.svg"
        );
    }

    #[test]
    fn artifact_reference_rejects_paths_outside_root() {
        let root = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let path = outside.path().join("fig.svg");

        let err = artifact_reference(root.path(), &path)
            .unwrap_err()
            .to_string();

        assert!(err.contains("is not under root"), "{err}");
        assert!(err.contains("fig.svg"), "{err}");
    }

    #[test]
    fn project_relative_paths_are_short_for_humans() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".calepin/paper/results.json");
        assert_eq!(
            project_relative_path(dir.path(), &path),
            ".calepin/paper/results.json"
        );
    }

    #[test]
    fn project_relative_path_normalizes_outside_backslash_paths() {
        assert_eq!(
            project_relative_path(Path::new("/project"), Path::new(r"C:\project\paper.typ")),
            "C:/project/paper.typ"
        );
    }

    #[test]
    fn project_relative_path_preserves_single_root_for_absolute_fallback() {
        assert_eq!(
            project_relative_path(Path::new("/project"), Path::new("/tmp/paper.typ")),
            "/tmp/paper.typ"
        );
    }
}