nornir 0.4.10

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
Documentation
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Per-repo nornir layout and the source→output render pipeline.
//!
//! Every repo owned by nornir gets a `.nornir/` directory at its root:
//!
//! ```text
//! repo/
//! ├── .nornir/                  ← nornir's namespace
//! │   ├── README.md             ← SOURCE (you edit this)
//! │   ├── CHANGELOG.md          ← SOURCE (you edit this)
//! │   ├── assets/               ← TRACKED media (depgraph.svg, logos, figures)
//! │   ├── warehouse/            ← DATA ONLY: the Iceberg warehouse (gitignored)
//! │   ├── cache/                ← transient: images + the docs index (gitignored)
//! │   └── .gitignore            ← ignores cache/ + warehouse/
//! ├── README.md                 ← GENERATED — DO NOT EDIT (chmod -w)
//! ├── CHANGELOG.md              ← GENERATED — DO NOT EDIT (chmod -w)
//! ├── docs/                     ← GENERATED rendered docs (book.pdf/.md, …); tracked
//! └── ...
//! ```
//!
//! Rendered exports (`docs export` / `docs book`) write the *current* artifact
//! to `<repo>/docs/` and historize the bytes in the Iceberg `doc_exports`
//! table; `.nornir/warehouse/` is data-only.
//!
//! The source files use the same `<!-- nornir:gen:start:NAME -->` markers as
//! [`super::sections`] for dynamic fills (bench tables, callgraphs, ...).
//! Render writes the whole output file (not just marker regions) and prepends
//! a loud header so anyone opening the artifact knows where the truth lives.

use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use serde::Deserialize;

use super::sections::{rewrite_str, Ctx};

/// Header prepended to every generated output file. The leading newline keeps
/// the comment on its own line; the warning lands in line 1 of the artifact.
pub const GENERATED_HEADER_PREFIX: &str =
    "<!-- ⚠ GENERATED by nornir from .nornir/";
pub const GENERATED_HEADER_SUFFIX: &str = " — DO NOT EDIT this file -->\n\n";

/// File names nornir manages by default. Adding new ones is a single-line
/// change: extend this list and they automatically get init / render / check.
pub const MANAGED_DOCS: &[&str] = &["README.md", "CHANGELOG.md"];

/// Per-repo render configuration, read from `<repo>/.nornir/docs.toml`.
///
/// Controls *which artifact(s)* `nornir docs render` emits for this repo:
///
/// - `"markdown"` (alias `"md"`) — the managed top-level `README.md` /
///   `CHANGELOG.md`, rendered from their `.nornir/` sources (nornir's default
///   and historical behaviour).
/// - `"pdf"` — the whole-documentation **book** rendered to `docs/book.pdf`
///   (needs a nornir built with the `docs-export` feature).
/// - `"all"` — both of the above.
///
/// **Absent file ⇒ `["markdown"]`** — so existing repos are unchanged. A repo
/// that wants *only* a rendered PDF and keeps its markdown hand-edited sets:
///
/// ```toml
/// # <repo>/.nornir/docs.toml
/// outputs = ["pdf"]
/// ```
///
/// With `outputs = ["pdf"]`, `render` never writes any markdown into the repo —
/// it only (re)builds `docs/book.pdf` from the repo's doc set. This is the way
/// to add documentation rendering to a project whose `*.md` are authored by
/// hand and must not be overwritten.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct DocsRenderCfg {
    /// Artifact kinds to emit. See the type docs for accepted tokens.
    pub outputs: Vec<String>,
}

impl Default for DocsRenderCfg {
    fn default() -> Self {
        Self {
            outputs: vec!["markdown".to_string()],
        }
    }
}

impl DocsRenderCfg {
    /// Path to the config file: `<repo>/.nornir/docs.toml`.
    pub fn path(layout: &RepoLayout) -> PathBuf {
        layout.nornir_dir().join("docs.toml")
    }

    /// Load the config for `layout`'s repo. Returns the default
    /// (`["markdown"]`) when `.nornir/docs.toml` is absent.
    pub fn load(layout: &RepoLayout) -> Result<Self> {
        let p = Self::path(layout);
        if !p.exists() {
            return Ok(Self::default());
        }
        let text =
            std::fs::read_to_string(&p).with_context(|| format!("read {}", p.display()))?;
        toml::from_str(&text).with_context(|| format!("parse {}", p.display()))
    }

    /// Whether the managed markdown artifacts should be (re)rendered.
    pub fn wants_markdown(&self) -> bool {
        self.outputs
            .iter()
            .any(|o| matches!(o.to_ascii_lowercase().as_str(), "markdown" | "md" | "all"))
    }

    /// Whether the PDF documentation book should be rendered.
    pub fn wants_pdf(&self) -> bool {
        self.outputs
            .iter()
            .any(|o| matches!(o.to_ascii_lowercase().as_str(), "pdf" | "all"))
    }
}

/// Layout of nornir-owned paths under one repo.
#[derive(Debug, Clone)]
pub struct RepoLayout {
    pub repo_root: PathBuf,
}

impl RepoLayout {
    pub fn new(repo_root: impl Into<PathBuf>) -> Self {
        Self {
            repo_root: repo_root.into(),
        }
    }

    /// `<repo>/.nornir/`
    pub fn nornir_dir(&self) -> PathBuf {
        self.repo_root.join(".nornir")
    }
    /// `<repo>/.nornir/warehouse/`
    pub fn warehouse_dir(&self) -> PathBuf {
        self.nornir_dir().join("warehouse")
    }
    /// `<repo>/.nornir/cache/`
    pub fn cache_dir(&self) -> PathBuf {
        self.nornir_dir().join("cache")
    }
    /// Image-cache subdir used by [`super::export`].
    pub fn image_cache_dir(&self) -> PathBuf {
        self.cache_dir().join("images")
    }
    /// Source path for one managed doc, e.g. `.nornir/README.md`.
    pub fn source_of(&self, doc_name: &str) -> PathBuf {
        self.nornir_dir().join(doc_name)
    }
    /// Output (artifact) path for one managed doc, e.g. `README.md`.
    pub fn output_of(&self, doc_name: &str) -> PathBuf {
        self.repo_root.join(doc_name)
    }
    /// `<repo>/docs/` — the canonical, git-tracked output directory for
    /// nornir-rendered documents (README/book PDF/HTML/MD). README links here.
    pub fn docs_dir(&self) -> PathBuf {
        self.repo_root.join("docs")
    }
    /// Path of a rendered export under `docs/`, e.g. `docs/book.pdf`. Stable
    /// (version-free) so links from the README don't churn per release.
    pub fn export_path(&self, doc_name: &str, ext: &str) -> PathBuf {
        self.docs_dir().join(format!("{doc_name}.{ext}"))
    }
}

/// Per-file render outcome.
#[derive(Debug)]
pub struct RenderReport {
    pub doc_name: String,
    pub source: PathBuf,
    pub output: PathBuf,
    pub sections: Vec<String>,
    pub changed: bool,
    pub bytes: usize,
}

/// Render a single managed doc: read source → fill markers → prepend warning
/// → atomically write output → restore read-only bit if file was previously
/// locked. Returns `Ok(None)` when no source exists for that doc (so a repo
/// can opt into only README and not CHANGELOG, etc.).
pub fn render_doc(layout: &RepoLayout, doc_name: &str, ctx: &Ctx) -> Result<Option<RenderReport>> {
    let src = layout.source_of(doc_name);
    if !src.exists() {
        return Ok(None);
    }
    let raw = std::fs::read_to_string(&src)
        .with_context(|| format!("read {}", src.display()))?;
    let (filled, sections) = rewrite_str(&raw, ctx)?;
    let header = format!("{GENERATED_HEADER_PREFIX}{doc_name}{GENERATED_HEADER_SUFFIX}");
    let mut output = String::with_capacity(header.len() + filled.len());
    output.push_str(&header);
    output.push_str(&filled);

    let dst = layout.output_of(doc_name);
    let prev = std::fs::read_to_string(&dst).ok();
    let changed = prev.as_deref() != Some(output.as_str());
    if changed {
        write_atomic(&dst, &output)?;
    }
    Ok(Some(RenderReport {
        doc_name: doc_name.to_string(),
        source: src,
        output: dst,
        sections,
        changed,
        bytes: output.len(),
    }))
}

/// Render every managed doc found under `.nornir/`.
pub fn render_all(layout: &RepoLayout, ctx: &Ctx) -> Result<Vec<RenderReport>> {
    let mut reports = Vec::new();
    for &doc in MANAGED_DOCS {
        if let Some(r) = render_doc(layout, doc, ctx)? {
            reports.push(r);
        }
    }
    Ok(reports)
}

/// In-memory dry-run of [`render_doc`] — bails if rendering would change
/// the output file. Use as a CI gate.
pub fn check_doc(layout: &RepoLayout, doc_name: &str, ctx: &Ctx) -> Result<Option<bool>> {
    let src = layout.source_of(doc_name);
    if !src.exists() {
        return Ok(None);
    }
    let raw = std::fs::read_to_string(&src)?;
    let (filled, _) = rewrite_str(&raw, ctx)?;
    let header = format!("{GENERATED_HEADER_PREFIX}{doc_name}{GENERATED_HEADER_SUFFIX}");
    let expected = format!("{header}{filled}");
    let dst = layout.output_of(doc_name);
    let prev = std::fs::read_to_string(&dst).unwrap_or_default();
    if prev != expected {
        bail!(
            "{} is out of date with {} — run `nornir docs render <repo>` to regenerate",
            dst.display(),
            src.display()
        );
    }
    Ok(Some(true))
}

/// Check every managed doc.
pub fn check_all(layout: &RepoLayout, ctx: &Ctx) -> Result<()> {
    for &doc in MANAGED_DOCS {
        check_doc(layout, doc, ctx)?;
    }
    Ok(())
}

/// Scaffold `.nornir/` for a repo:
///   - create `.nornir/`, `.nornir/cache/`, `.nornir/warehouse/`
///   - migrate any existing top-level managed docs (README.md, CHANGELOG.md)
///     into `.nornir/` as the source
///   - if no managed doc exists, write a minimal scaffold for README.md
///   - write `.nornir/.gitignore` (ignores cache/)
///
/// Returns the list of source files now present in `.nornir/`.
pub fn init_repo(layout: &RepoLayout) -> Result<Vec<PathBuf>> {
    std::fs::create_dir_all(layout.nornir_dir())?;
    std::fs::create_dir_all(layout.cache_dir())?;
    std::fs::create_dir_all(layout.warehouse_dir())?;
    std::fs::create_dir_all(layout.image_cache_dir())?;

    let gi = layout.nornir_dir().join(".gitignore");
    if !gi.exists() {
        std::fs::write(&gi, "cache/\n")?;
    }

    let mut sources = Vec::new();
    let mut had_any = false;
    for &doc in MANAGED_DOCS {
        let src = layout.source_of(doc);
        let dst = layout.output_of(doc);
        if src.exists() {
            sources.push(src);
            had_any = true;
            continue;
        }
        if dst.exists() {
            // Migrate the existing artifact into .nornir/ as the source.
            // The artifact will be re-rendered (with the GENERATED warning)
            // on the next `nornir docs render`.
            let existing = std::fs::read_to_string(&dst)
                .with_context(|| format!("read {}", dst.display()))?;
            // Strip any pre-existing GENERATED header so a re-init is a no-op.
            let cleaned = strip_generated_header(&existing);
            std::fs::write(&src, cleaned)
                .with_context(|| format!("write {}", src.display()))?;
            sources.push(src);
            had_any = true;
        }
    }
    if !had_any {
        // No README anywhere — scaffold a starter.
        let starter = scaffold_readme(&layout.repo_root);
        let src = layout.source_of("README.md");
        std::fs::write(&src, starter)?;
        sources.push(src);
    }
    Ok(sources)
}

/// Strip a pre-existing GENERATED-by-nornir header (if any) from the start
/// of `text`. Idempotent.
fn strip_generated_header(text: &str) -> String {
    if let Some(rest) = text.strip_prefix(GENERATED_HEADER_PREFIX) {
        // Find the matching suffix `-->` and the following blank line.
        if let Some(end) = rest.find("-->") {
            let after = &rest[end + 3..];
            let after = after.trim_start_matches(['\n', '\r']);
            return after.to_string();
        }
    }
    text.to_string()
}

fn scaffold_readme(repo_root: &Path) -> String {
    let name = repo_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("project");
    format!(
        r#"# {name}

> One-line description of {name}.

<!-- Headline: paste your single most meaningful benchmark number here, e.g.
     **9,950 MB/s decompress · 32 cores**. The full table renders below. -->

<!-- Write any intro prose here. Anything outside the marker blocks below
     is preserved verbatim on every render. -->

## Benchmarks

<!-- The `benches` renderer pivots the latest run into a table and bolds the
     winning cell per row (e.g. ours vs a legacy tool). Direction is inferred
     from the metric unit (`_mbs` higher-better, `_ms` lower-better); override
     odd cases with `benches best=metric:low`. -->
<!-- nornir:gen:start:benches -->
<!-- nornir:gen:end:benches -->

## Tests

<!-- Unit / integration / doc tests, enumerated from source via syn. -->
<!-- nornir:gen:start:tests -->
<!-- nornir:gen:end:tests -->

## Dependency graph

<!-- nornir:gen:start:depgraph -->
<!-- nornir:gen:end:depgraph -->

## License

MIT OR Apache-2.0.
"#
    )
}

/// Write `content` to `dst` atomically (write to tmp, fsync, rename),
/// honouring a previous read-only bit by clearing it before write and
/// restoring it after.
fn write_atomic(dst: &Path, content: &str) -> Result<()> {
    use std::io::Write;
    if let Some(parent) = dst.parent() {
        std::fs::create_dir_all(parent)?;
    }
    // Capture & clear any read-only bit so we can overwrite.
    let prev_readonly = match std::fs::metadata(dst) {
        Ok(m) => {
            let ro = m.permissions().readonly();
            if ro {
                let mut p = m.permissions();
                #[allow(clippy::permissions_set_readonly_false)]
                p.set_readonly(false);
                std::fs::set_permissions(dst, p)?;
            }
            ro
        }
        Err(_) => false,
    };

    let tmp = dst.with_extension(format!(
        "{}.nornir-tmp",
        dst.extension()
            .and_then(|e| e.to_str())
            .unwrap_or("tmp")
    ));
    {
        let mut f = std::fs::File::create(&tmp)
            .with_context(|| format!("create {}", tmp.display()))?;
        f.write_all(content.as_bytes())?;
        f.sync_all().ok();
    }
    std::fs::rename(&tmp, dst)
        .with_context(|| format!("rename {} -> {}", tmp.display(), dst.display()))?;

    if prev_readonly {
        let mut p = std::fs::metadata(dst)?.permissions();
        p.set_readonly(true);
        std::fs::set_permissions(dst, p)?;
    }
    Ok(())
}

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

    fn layout() -> (TempDir, RepoLayout) {
        let t = TempDir::new().unwrap();
        let l = RepoLayout::new(t.path());
        (t, l)
    }

    #[test]
    fn init_creates_skeleton_when_empty() {
        let (_t, l) = layout();
        let srcs = init_repo(&l).unwrap();
        assert!(l.nornir_dir().exists());
        assert!(l.cache_dir().exists());
        assert!(l.warehouse_dir().exists());
        assert!(l.nornir_dir().join(".gitignore").exists());
        assert_eq!(srcs.len(), 1);
        assert!(srcs[0].ends_with("README.md"));
        let scaffold = std::fs::read_to_string(&srcs[0]).unwrap();
        assert!(scaffold.contains("nornir:gen:start:benches"));
        assert!(scaffold.contains("nornir:gen:start:tests"));
        assert!(scaffold.contains("nornir:gen:start:depgraph"));
    }

    #[test]
    fn init_migrates_existing_readme() {
        let (t, l) = layout();
        std::fs::write(t.path().join("README.md"), "# already here\n\nbody\n").unwrap();
        let srcs = init_repo(&l).unwrap();
        assert_eq!(srcs.len(), 1);
        let s = std::fs::read_to_string(&srcs[0]).unwrap();
        assert!(s.contains("# already here"));
    }

    #[test]
    fn init_strips_old_header_on_remigrate() {
        let (t, l) = layout();
        let body = "# x\n\nbody\n";
        let with_header = format!(
            "{}README.md{}{}",
            GENERATED_HEADER_PREFIX, GENERATED_HEADER_SUFFIX, body
        );
        std::fs::write(t.path().join("README.md"), &with_header).unwrap();
        init_repo(&l).unwrap();
        let s = std::fs::read_to_string(l.source_of("README.md")).unwrap();
        assert!(!s.contains("GENERATED"));
        assert!(s.starts_with("# x"));
    }

    #[test]
    fn render_writes_header_and_preserves_source() {
        let (t, l) = layout();
        let src = l.source_of("README.md");
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(&src, "# title\n\nhello\n").unwrap();
        let ctx = Ctx::new(t.path(), t.path(), None);
        let r = render_doc(&l, "README.md", &ctx).unwrap().unwrap();
        assert!(r.changed);
        let out = std::fs::read_to_string(&r.output).unwrap();
        assert!(out.starts_with(GENERATED_HEADER_PREFIX));
        assert!(out.contains("# title"));
    }

    #[test]
    fn render_is_idempotent() {
        let (t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(l.source_of("README.md"), "# x\n").unwrap();
        let ctx = Ctx::new(t.path(), t.path(), None);
        let r1 = render_doc(&l, "README.md", &ctx).unwrap().unwrap();
        assert!(r1.changed);
        let r2 = render_doc(&l, "README.md", &ctx).unwrap().unwrap();
        assert!(!r2.changed);
    }

    #[test]
    fn check_fails_on_drift() {
        let (t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(l.source_of("README.md"), "# original\n").unwrap();
        let ctx = Ctx::new(t.path(), t.path(), None);
        render_doc(&l, "README.md", &ctx).unwrap();
        // Mutate source so the output is now stale.
        std::fs::write(l.source_of("README.md"), "# changed\n").unwrap();
        assert!(check_doc(&l, "README.md", &ctx).is_err());
    }

    #[test]
    fn render_respects_readonly_bit() {
        let (t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(l.source_of("README.md"), "# v1\n").unwrap();
        let ctx = Ctx::new(t.path(), t.path(), None);
        render_doc(&l, "README.md", &ctx).unwrap();
        // Lock the output, then mutate source and re-render. write_atomic
        // should clear+restore the bit.
        let out = l.output_of("README.md");
        let mut p = std::fs::metadata(&out).unwrap().permissions();
        p.set_readonly(true);
        std::fs::set_permissions(&out, p).unwrap();
        std::fs::write(l.source_of("README.md"), "# v2\n").unwrap();
        render_doc(&l, "README.md", &ctx).unwrap();
        let new = std::fs::read_to_string(&out).unwrap();
        assert!(new.contains("# v2"));
        assert!(std::fs::metadata(&out).unwrap().permissions().readonly());
    }

    #[test]
    fn docs_render_cfg_defaults_to_markdown() {
        let (_t, l) = layout();
        let cfg = DocsRenderCfg::load(&l).unwrap();
        assert!(cfg.wants_markdown());
        assert!(!cfg.wants_pdf());
    }

    #[test]
    fn docs_render_cfg_pdf_only_skips_markdown() {
        let (_t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(DocsRenderCfg::path(&l), "outputs = [\"pdf\"]\n").unwrap();
        let cfg = DocsRenderCfg::load(&l).unwrap();
        assert!(cfg.wants_pdf());
        assert!(!cfg.wants_markdown());
    }

    #[test]
    fn docs_render_cfg_all_wants_both() {
        let (_t, l) = layout();
        std::fs::create_dir_all(l.nornir_dir()).unwrap();
        std::fs::write(DocsRenderCfg::path(&l), "outputs = [\"all\"]\n").unwrap();
        let cfg = DocsRenderCfg::load(&l).unwrap();
        assert!(cfg.wants_pdf());
        assert!(cfg.wants_markdown());
    }
}