rsconstruct 0.9.182

Rust based fast build system
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
use anyhow::{Context, Result};
use parking_lot::Mutex;
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use super::{
    OnceTool, PlannedOutput, add_planned_products, files_under, fresh_state_dir, install_staged,
    relative_slash_path, require_planned_output,
};
use crate::config::{StandardConfig, output_config_hash, resolve_extra_inputs};
use crate::file_index::FileIndex;
use crate::graph::{BuildGraph, Product};
use crate::processor::{
    Processor, anchor_display_dir, check_command_output, resolve_anchor_path, run_in_anchor_dir,
};

const CORE_STATIC_FILES: &[&str] = &[
    ".nojekyll",
    "404.html",
    "ayu-highlight.css",
    "book.js",
    "clipboard.min.js",
    "css/chrome.css",
    "css/general.css",
    "css/print.css",
    "css/variables.css",
    "favicon.png",
    "favicon.svg",
    "highlight.css",
    "highlight.js",
    "index.html",
    "toc.html",
    "toc.js",
    "tomorrow-night.css",
];

const SEARCH_STATIC_FILES: &[&str] = &[
    "elasticlunr.min.js",
    "mark.min.js",
    "searcher.js",
    "searchindex.js",
];

const FONT_STATIC_FILES: &[&str] = &[
    "fonts/OPEN-SANS-LICENSE.txt",
    "fonts/SOURCE-CODE-PRO-LICENSE.txt",
    "fonts/fonts.css",
    "fonts/open-sans-v17-all-charsets-300.woff2",
    "fonts/open-sans-v17-all-charsets-300italic.woff2",
    "fonts/open-sans-v17-all-charsets-600.woff2",
    "fonts/open-sans-v17-all-charsets-600italic.woff2",
    "fonts/open-sans-v17-all-charsets-700.woff2",
    "fonts/open-sans-v17-all-charsets-700italic.woff2",
    "fonts/open-sans-v17-all-charsets-800.woff2",
    "fonts/open-sans-v17-all-charsets-800italic.woff2",
    "fonts/open-sans-v17-all-charsets-italic.woff2",
    "fonts/open-sans-v17-all-charsets-regular.woff2",
    "fonts/source-code-pro-v11-all-charsets-500.woff2",
];

#[derive(Debug, Deserialize, Serialize, Clone, Default)]
/// Mdbook config. Custom: `loose_manifest`.
pub struct MdbookConfig {
    /// Report plan-vs-build mismatches as warnings instead of errors.
    #[serde(default)]
    pub loose_manifest: bool,
    #[serde(flatten)]
    pub standard: StandardConfig,
}

struct BookPlan {
    output_dir: PathBuf,
    outputs: Vec<PlannedOutput>,
    relative: BTreeSet<String>,
}

pub struct MdbookProcessor {
    config: MdbookConfig,
    runs: Mutex<BTreeMap<PathBuf, Arc<OnceTool>>>,
}

impl MdbookProcessor {
    pub const fn new(config: MdbookConfig) -> Self {
        Self {
            config,
            runs: Mutex::new(BTreeMap::new()),
        }
    }

    fn run_guard(&self, book_toml: &Path) -> Arc<OnceTool> {
        let mut guard = self.runs.lock();
        Arc::clone(
            guard
                .entry(book_toml.to_path_buf())
                .or_insert_with(|| Arc::new(OnceTool::new())),
        )
    }

    /// Plan all files `mdbook build` writes for `book_toml`.
    fn plan_book(&self, book_toml: &Path) -> Result<BookPlan> {
        let text = fs::read_to_string(book_toml)
            .with_context(|| format!("Failed to read {}", book_toml.display()))?;
        let doc: toml::Value = toml::from_str(&text)
            .with_context(|| format!("Failed to parse {}", book_toml.display()))?;

        let anchor_dir = crate::processor::parent_dir_or_empty(book_toml);
        let src_rel = doc
            .get("book")
            .and_then(|b| b.get("src"))
            .and_then(toml::Value::as_str)
            .unwrap_or("src");
        let src_dir = resolve_anchor_path(anchor_dir, src_rel);
        let output_dir = resolve_anchor_path(anchor_dir, &self.config.standard.output_dir);

        let html = doc.get("output").and_then(|o| o.get("html"));
        if html
            .and_then(|h| h.get("hash-files"))
            .and_then(toml::Value::as_bool)
            == Some(true)
        {
            anyhow::bail!(
                "{}: [output.html].hash-files = true is not supported by the mdbook mass generator; omit it so mdbook writes deterministic filenames",
                book_toml.display()
            );
        }
        let print_enabled = html
            .and_then(|h| h.get("print"))
            .and_then(|p| p.get("enable"))
            .and_then(toml::Value::as_bool)
            .unwrap_or(true);
        let search_enabled = html
            .and_then(|h| h.get("search"))
            .and_then(|s| s.get("enable"))
            .and_then(toml::Value::as_bool)
            .unwrap_or(true);
        let copy_fonts = html
            .and_then(|h| h.get("copy-fonts"))
            .and_then(toml::Value::as_bool)
            .unwrap_or(true);

        let mut relative: BTreeSet<String> =
            CORE_STATIC_FILES.iter().map(|s| (*s).to_string()).collect();
        if print_enabled {
            relative.insert("print.html".to_string());
        }
        if search_enabled {
            for f in SEARCH_STATIC_FILES {
                relative.insert((*f).to_string());
            }
        }
        if copy_fonts {
            for f in FONT_STATIC_FILES {
                relative.insert((*f).to_string());
            }
        }

        let mut sources = vec![book_toml.to_path_buf()];
        for key in ["additional-css", "additional-js"] {
            if let Some(arr) = html
                .and_then(|h| h.get(key))
                .and_then(toml::Value::as_array)
            {
                for item in arr.iter().filter_map(toml::Value::as_str) {
                    let trimmed = item.strip_prefix("./").unwrap_or(item);
                    relative.insert(trimmed.to_string());
                    let src_path = resolve_anchor_path(anchor_dir, trimmed);
                    if !sources.contains(&src_path) {
                        sources.push(src_path);
                    }
                }
            }
        }

        let summary_path = src_dir.join("SUMMARY.md");
        let summary = fs::read_to_string(&summary_path)
            .with_context(|| format!("Failed to read {}", summary_path.display()))?;
        for chapter_md in extract_summary_links(&summary) {
            if let Some(html_rel) = md_path_to_html(&chapter_md) {
                relative.insert(html_rel);
            }
        }

        let mut chapters: Vec<PathBuf> = Vec::new();
        for file in files_under(&src_dir)? {
            if file.extension().and_then(|e| e.to_str()) == Some("md") {
                chapters.push(file.clone());
            } else {
                relative.insert(relative_slash_path(&src_dir, &file));
            }
            if !sources.contains(&file) {
                sources.push(file);
            }
        }
        // What the chapters pull in with `{{#include}}` and its relatives
        // from outside `src/` (example code kept beside the book, say) is
        // part of the pages too: unlisted, an edit to such a file left the
        // book cached with the old text. An included file may include
        // further ones, so each new one is scanned in turn.
        let mut to_scan = chapters;
        while let Some(file) = to_scan.pop() {
            let content = fs::read_to_string(&file)
                .with_context(|| format!("Failed to read {}", file.display()))?;
            for included in included_files(&file, &content) {
                // A file that is not there is mdbook's error to report.
                if included.is_file() && !sources.contains(&included) {
                    sources.push(included.clone());
                    to_scan.push(included);
                }
            }
        }

        // A custom theme: every file in it (templates, css, js, fonts) can
        // change every page, so each is a source of every output. The
        // directory is `theme/` next to `book.toml` unless `[output.html]
        // theme` names another; a book without one has no such files.
        let theme_rel = html
            .and_then(|h| h.get("theme"))
            .and_then(toml::Value::as_str)
            .unwrap_or("theme");
        let theme_dir = resolve_anchor_path(anchor_dir, theme_rel);
        for file in files_under(&theme_dir)? {
            if !sources.contains(&file) {
                sources.push(file);
            }
        }

        let outputs = relative
            .iter()
            .map(|rel| PlannedOutput {
                path: output_dir.join(rel),
                sources: sources.clone(),
            })
            .collect();

        Ok(BookPlan {
            output_dir,
            outputs,
            relative,
        })
    }

    /// Run `mdbook build` into a staging directory, check against the plan,
    /// and move the planned files into `output_dir`.
    fn execute_mdbook(
        &self,
        ctx: &crate::build_context::BuildContext,
        book_toml: &Path,
        instance_name: &str,
    ) -> Result<()> {
        let plan = self.plan_book(book_toml)?;
        let flat = book_toml.to_string_lossy().replace('/', "_");
        let staging = fresh_state_dir(instance_name, &format!(".{flat}.staging"))?;
        let cwd =
            std::env::current_dir().context("Failed to get current directory for mdbook build")?;
        let staging_abs = cwd.join(&staging);

        let mut cmd = Command::new(&self.config.standard.command);
        cmd.arg("build");
        cmd.arg("-d").arg(&staging_abs);
        cmd.arg(".");
        cmd.env("MDBOOK_OUTPUT__HTML__HASH_FILES", "false");
        for arg in &self.config.standard.args {
            cmd.arg(arg);
        }
        let output = run_in_anchor_dir(ctx, &mut cmd, book_toml)?;
        check_command_output(
            &output,
            format_args!("mdbook build in {}", anchor_display_dir(book_toml)),
        )?;

        install_staged(
            &staging,
            &plan.relative,
            &plan.output_dir,
            instance_name,
            &self.config.standard.command,
            self.config.loose_manifest,
        )
    }
}

/// The files `content`, the text of `file`, pulls in with mdbook's
/// `{{#include PATH}}`, `{{#rustdoc_include PATH}}` and `{{#playground
/// PATH}}`, resolved against `file`'s directory as mdbook resolves them. A
/// `:range` or `:anchor` after the path is not part of it; an escaped
/// `\{{#include …}}` is text, not a directive.
fn included_files(file: &Path, content: &str) -> Vec<PathBuf> {
    static DIRECTIVE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    let directive = DIRECTIVE.get_or_init(|| {
        regex::Regex::new(r"(\\?)\{\{\s*#(?:include|rustdoc_include|playground)\s+([^\s:}]+)")
            .expect(crate::errors::INVALID_REGEX)
    });
    let dir = file.parent().unwrap_or_else(|| Path::new(""));
    directive
        .captures_iter(content)
        .filter(|caps| caps[1].is_empty())
        .map(|caps| crate::analyzers::lexical_normalize(&dir.join(&caps[2])))
        .collect()
}

/// Extract the target paths from `[title](path)` links in `SUMMARY.md`.
fn extract_summary_links(summary: &str) -> Vec<String> {
    let mut links = Vec::new();
    let bytes = summary.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'[' {
            let mut j = i + 1;
            while j < bytes.len() && bytes[j] != b']' && bytes[j] != b'\n' {
                j += 1;
            }
            if j + 1 < bytes.len() && bytes[j] == b']' && bytes[j + 1] == b'(' {
                let start = j + 2;
                let mut end = start;
                while end < bytes.len() && bytes[end] != b')' && bytes[end] != b'\n' {
                    end += 1;
                }
                if end < bytes.len() && bytes[end] == b')' {
                    let target = summary[start..end].trim();
                    if !target.is_empty() {
                        links.push(target.to_string());
                    }
                    i = end + 1;
                    continue;
                }
            }
        }
        i += 1;
    }
    links
}

/// Convert a `SUMMARY.md` link path into the HTML path `mdbook` writes.
fn md_path_to_html(md_path: &str) -> Option<String> {
    let clean = md_path
        .strip_prefix("./")
        .or_else(|| md_path.strip_prefix('/'))
        .unwrap_or(md_path);
    if clean == "README.md" {
        Some("index.html".to_string())
    } else if let Some(prefix) = clean.strip_suffix("/README.md") {
        Some(format!("{prefix}/index.html"))
    } else {
        clean.strip_suffix(".md").map(|stem| format!("{stem}.html"))
    }
}

impl Processor for MdbookProcessor {
    fn scan_config(&self) -> &crate::config::StandardConfig {
        &self.config.standard
    }

    fn config_json(&self) -> Option<String> {
        crate::processor::ProcessorBase::config_json(&self.config)
    }

    fn replaces_own_outputs(&self) -> bool {
        true
    }

    fn required_tools(&self) -> Vec<String> {
        crate::processor::with_declared_tools(
            vec![self.config.standard.command.clone()],
            &self.config.standard,
        )
    }

    fn discover(
        &self,
        graph: &mut BuildGraph,
        file_index: &FileIndex,
        instance_name: &str,
    ) -> Result<()> {
        let Some(files) = crate::processor::scan_or_skip(&self.config.standard, file_index) else {
            return Ok(());
        };
        let config_hash = output_config_hash(
            &self.config,
            &crate::config::checksum_fields_of(instance_name),
        );
        let extra = resolve_extra_inputs(&self.config.standard.dep_inputs)?;

        let mut all_planned = Vec::new();
        for book_toml in files {
            let plan = self.plan_book(&book_toml)?;
            all_planned.extend(plan.outputs);
        }
        add_planned_products(graph, &all_planned, instance_name, &config_hash, &extra)
    }

    fn execute(&self, ctx: &crate::build_context::BuildContext, product: &Product) -> Result<()> {
        let book_toml = product.primary_input();
        let instance_name = &product.processor;
        let guard = self.run_guard(book_toml);
        guard.run(&self.config.standard.command, || {
            self.execute_mdbook(ctx, book_toml, instance_name)
        })?;
        require_planned_output(product, &self.config.standard.command)
    }
}

fn plugin_create(toml: &toml::Value) -> anyhow::Result<Box<dyn crate::processor::Processor>> {
    crate::registries::deserialize_and_create(toml, |cfg| Box::new(MdbookProcessor::new(cfg)))
}
inventory::submit! {
    crate::registries::ProcessorPlugin {
        version: 2,
        name: "mdbook",
        processor_type: crate::processor::ProcessorType::MassGenerator,
        create: plugin_create,
        fields: &[
            crate::config::FieldSpec { name: "loose_manifest", ty: crate::config::FieldType::Bool,
                affects_output: false, required: false,
                doc: "Report plan-vs-build mismatches as warnings instead of failing the build" },
        ],
        omit_standard_fields: &["formats", "dep_auto", "batch"],
        scan_defaults: Some(crate::config::ScanDefaultsData { src_dirs: &[], src_extensions: &["book.toml"], src_exclude_dirs: &[] }),
        defaults: Some(crate::config::ProcessorDefaults { command: "mdbook", output_dir: "book", ..crate::config::ProcessorDefaults::EMPTY }),
        defconfig_json: crate::registries::default_config_json::<MdbookConfig>,
        keywords: &["markdown", "md", "rust", "documentation", "book", "html"],
        description: "Build mdbook documentation",
        is_builtin: false,
        is_rust: true,
        supports_batch: false,
        caches_outputs: true,
        sandboxable: true,
        max_jobs_cap: Some(1),
    }
}
inventory::submit! { crate::tools::ToolInfo {
    name: "mdbook", runtime: "rust",
    project: Some(crate::tools::InstallMethod::new("cargo", "mdbook")),
    machine: Some(crate::tools::InstallMethod::new("cargo", "mdbook")),
    alternatives: &[], prefer: None, sandbox_writable: &[], needs_network: false,
} }

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

    #[test]
    fn summary_links_map_chapters_and_readmes_to_html() {
        let summary = "# Summary\n\n[Intro](./README.md)\n- [Ch 1](ch1.md)\n  - [Sub](./sub/README.md)\n- [Draft]()\n";
        let links = extract_summary_links(summary);
        let htmls: Vec<String> = links.iter().filter_map(|l| md_path_to_html(l)).collect();
        assert_eq!(htmls, vec!["index.html", "ch1.html", "sub/index.html"]);
    }

    /// A book in `dir` with one chapter, `book_toml` as its manifest text.
    fn write_book(dir: &Path, book_toml: &str) -> PathBuf {
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("book.toml"), book_toml).unwrap();
        std::fs::write(
            dir.join("src/SUMMARY.md"),
            "# Summary\n\n- [Ch 1](ch1.md)\n",
        )
        .unwrap();
        std::fs::write(dir.join("src/ch1.md"), "# Ch 1\n").unwrap();
        dir.join("book.toml")
    }

    /// The sources every planned file depends on, for the book at `book_toml`.
    fn plan_sources(book_toml: &Path) -> Vec<PathBuf> {
        let processor = MdbookProcessor::new(MdbookConfig::default());
        let plan = processor.plan_book(book_toml).unwrap();
        let first = &plan.outputs[0];
        for output in &plan.outputs {
            assert_eq!(
                output.sources, first.sources,
                "every output shares the sources"
            );
        }
        first.sources.clone()
    }

    /// A file a chapter includes from outside `src/` is a source, and so is
    /// one that file includes in turn; an escaped directive and a missing
    /// file add nothing. Editing such a file used to leave the book cached.
    #[test]
    fn included_files_outside_src_are_sources() {
        let tmp = tempfile::TempDir::new().unwrap();
        let book = tmp.path().join("book");
        let book_toml = write_book(&book, "[book]\ntitle = \"Inc\"\n");
        std::fs::create_dir_all(book.join("ex")).unwrap();
        std::fs::write(book.join("ex/code.rs"), "fn main() {}\n").unwrap();
        std::fs::write(book.join("ex/part.md"), "{{#include nested.txt}}\n").unwrap();
        std::fs::write(book.join("ex/nested.txt"), "nested\n").unwrap();
        std::fs::write(book.join("ex/escaped.txt"), "not included\n").unwrap();
        std::fs::write(
            book.join("src/ch1.md"),
            "# Ch 1\n\n```rust\n{{#rustdoc_include ../ex/code.rs:2:5}}\n```\n\n\
             {{#include ../ex/part.md}}\n\\{{#include ../ex/escaped.txt}}\n\
             {{#include ../ex/missing.txt}}\n",
        )
        .unwrap();

        let sources = plan_sources(&book_toml);
        for included in ["ex/code.rs", "ex/part.md", "ex/nested.txt"] {
            assert!(
                sources.contains(&book.join(included)),
                "{included}: {sources:?}"
            );
        }
        for not_included in ["ex/escaped.txt", "ex/missing.txt"] {
            assert!(!sources.contains(&book.join(not_included)), "{sources:?}");
        }
    }

    /// Theme files (the default `theme/` or the `[output.html] theme`
    /// directory) are copied into or rendered through every page, so they
    /// are sources of every planned output; a book with no theme directory
    /// has none.
    #[test]
    fn custom_theme_files_are_sources_of_every_output() {
        let tmp = tempfile::TempDir::new().unwrap();

        let plain = tmp.path().join("plain");
        let book_toml = write_book(&plain, "[book]\ntitle = \"Plain\"\n");
        let sources = plan_sources(&book_toml);
        assert!(
            sources
                .iter()
                .all(|s| s.starts_with(&plain) && !s.starts_with(plain.join("theme"))),
            "{sources:?}"
        );

        let themed = tmp.path().join("themed");
        let book_toml = write_book(&themed, "[book]\ntitle = \"Themed\"\n");
        std::fs::create_dir_all(themed.join("theme/css")).unwrap();
        std::fs::write(themed.join("theme/index.hbs"), "{{{ content }}}\n").unwrap();
        std::fs::write(themed.join("theme/css/chrome.css"), "body {}\n").unwrap();
        let sources = plan_sources(&book_toml);
        assert!(
            sources.contains(&themed.join("theme/index.hbs")),
            "{sources:?}"
        );
        assert!(
            sources.contains(&themed.join("theme/css/chrome.css")),
            "{sources:?}"
        );

        let custom = tmp.path().join("custom");
        let book_toml = write_book(
            &custom,
            "[book]\ntitle = \"Custom\"\n\n[output.html]\ntheme = \"my-theme\"\n",
        );
        std::fs::create_dir_all(custom.join("my-theme")).unwrap();
        std::fs::write(custom.join("my-theme/head.hbs"), "<meta>\n").unwrap();
        std::fs::create_dir_all(custom.join("theme")).unwrap();
        std::fs::write(custom.join("theme/index.hbs"), "unused\n").unwrap();
        let sources = plan_sources(&book_toml);
        assert!(
            sources.contains(&custom.join("my-theme/head.hbs")),
            "{sources:?}"
        );
        assert!(
            !sources.contains(&custom.join("theme/index.hbs")),
            "the default theme dir is not read when [output.html] theme names another: {sources:?}"
        );
    }
}