compile-typst-site 2.1.0

Command-line program for static site generation using Typst.
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
//! `compile-typst-site` project configuration, pulling from command-line arguments and a config file.

use anyhow::{Context as _, Result, anyhow};
use glob::{MatchOptions, Pattern};
use nanoserde::{Toml, TomlParser};
use onlyargs_derive::OnlyArgs;
use std::fmt::Debug;
use std::fs;
use std::io::IsTerminal as _;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::OnceLock;

#[derive(Debug)]
pub enum LogWithColor {
    Auto,
    Always,
    Never,
}

static IS_TERMINAL: OnceLock<bool> = OnceLock::new();

impl LogWithColor {
    pub fn use_color(&self) -> bool {
        match self {
            LogWithColor::Auto => *IS_TERMINAL.get_or_init(|| std::io::stdout().is_terminal()),
            LogWithColor::Always => true,
            LogWithColor::Never => false,
        }
    }

    pub fn str(&self) -> &'static str {
        match self {
            LogWithColor::Auto => "auto",
            LogWithColor::Always => "always",
            LogWithColor::Never => "never",
        }
    }

    pub fn str_collapsing_auto(&self) -> &'static str {
        if self.use_color() { "always" } else { "never" }
    }
}

impl FromStr for LogWithColor {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "auto" => Ok(Self::Auto),
            "always" => Ok(Self::Always),
            "never" => Ok(Self::Never),
            _ => Err(anyhow!(
                "color argument must be one of \"auto\", \"always\", or \"never\""
            )),
        }
    }
}

impl Default for LogWithColor {
    fn default() -> Self {
        Self::Auto
    }
}

// Don't need a Args rustdoc here because our current crate scrapes from the Cargo.toml description I guess??
#[derive(Clone, Debug, Eq, PartialEq, OnlyArgs)]
struct Args {
    /// Use the specified path as the project root.
    path: Option<PathBuf>,
    /// Build and then watch for changes.
    watch: bool,
    /// Build and then watch for changes while serving website locally.
    serve: bool,
    /// Ignore initial full-site compilation step.
    ignore_initial: bool,
    /// Enable verbose logging.
    verbose: bool,
    /// Enable very verbose logging.
    trace: bool,
    /// Whether to use color. [default: auto] [possible values: auto, always, never]
    color: Option<String>,
}

#[derive(Default)]
struct ConfigFile {
    /// Array of globs to match for passthrough-copying.
    ///
    /// Example in the TOML config file: `passthrough_copy = ["*.css", "*.js", "assets/*"]
    passthrough_copy: Vec<String>,
    /// Command to run before a full rebuild.
    ///
    /// Strings should not contain $ unless the symbol begins:
    /// - $PROJECT_ROOT, which is replaced with the path to the project root.
    ///
    /// E.g., `passthrough_copy = ["python", "$PROJECT_ROOT/prebuild.py"]`.
    init: Vec<String>,
    /// Command to run to post-process HTML files generated by Typst.
    ///
    /// Must take in stdin and return via stdout.
    ///
    /// Strings should not contain $ unless the symbol begins:
    /// - $PROJECT_ROOT, which is replaced with the path to the project root.
    ///
    /// Example in the TOML config file: `post_processing_typ = ["python", "$PROJECT_ROOT/post_processing_script.py"]`.
    post_processing_typ: Vec<String>,
    /// Convert paths literally instead of magically tranforming to index.html.
    ///
    /// i.e., ./content.typ goes to ./content.html instead of defaulting to ./content/index.html.
    ///
    /// Example in the TOML config file: `literal_paths = true`
    literal_paths: bool,
    /// Typst cannot yet glob-find multiple files, which is a problem if one wants to list, e.g., all blog posts on a page.
    /// To work around this, we write all Typst files(?) as a JSON to the project root directory.
    ///
    /// We also let you query for data. (You might want the dates of those blog posts to appear on your listing page).
    /// This is slower than the other options because we have to call `typst query`.
    ///
    /// Must be one of "disabled", "enabled", "include-data"
    ///
    /// Example in the TOML config file: `file_listing = "enabled"`
    file_listing: FileListing,
    /// Add extra arguments to the underlying file listing `typst query` invokation.
    ///
    /// This can be helpful for ignoring system fonts when querying,
    /// which can drastically speed up Typst querying
    /// (until Typst releases https://github.com/typst/typst/pull/7380).
    ///
    /// Example in the TOML config file: `file_listing_extra_args = ["--ignore-system-fonts"]`
    file_listing_extra_args: Vec<String>,
    /// Add extra arguments to the underlying `typst compile` invokation.
    ///
    /// This can be helpful for ignoring system fonts when compiling,
    /// which can drastically speed up Typst querying
    /// (until Typst releases https://github.com/typst/typst/pull/7380).
    ///
    /// Example in the TOML config file: `compilation_extra_args = ["--ignore-system-fonts"]`
    compilation_extra_args: Vec<String>,
    /// Disable incremental compilation while using serve or watch mode.
    ///
    /// Example in the TOML config file: `disable_incremental = true`
    disable_incremental: bool,
}

#[derive(Debug)]
pub enum FileListing {
    Disabled,
    Enabled,
    IncludeData,
}

impl FileListing {
    pub const DISABLED_STR: &str = "disabled";
    pub const ENABLED_STR: &str = "enabled";
    pub const INCLUDE_DATA_STR: &str = "include-data";
    pub const DEFAULT_STR: &str = Self::DISABLED_STR;
}

impl Default for FileListing {
    fn default() -> Self {
        Self::Disabled
    }
}

impl FromStr for FileListing {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            Self::DISABLED_STR => Ok(FileListing::Disabled),
            Self::ENABLED_STR => Ok(FileListing::Enabled),
            Self::INCLUDE_DATA_STR => Ok(FileListing::IncludeData),
            _ => Err(anyhow!(
                "TOML parsing error: file_listing must be one of \"{}\", \"{}\", \"{}\", not {}",
                Self::DISABLED_STR,
                Self::ENABLED_STR,
                Self::INCLUDE_DATA_STR,
                s
            )),
        }
    }
}

pub struct PassthroughCopyGlobs(Vec<Pattern>);

impl PassthroughCopyGlobs {
    const MATCH_CFG: MatchOptions = MatchOptions {
        case_sensitive: true,
        require_literal_separator: true,
        require_literal_leading_dot: false,
    };

    pub fn matches_path_with(&self, path: &Path) -> bool {
        self.0
            .iter()
            .any(|glob| glob.matches_path_with(&path, Self::MATCH_CFG))
    }
}

/// Ignore the gnarly debug impl for `Pattern`.
impl Debug for PassthroughCopyGlobs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("omitted for brevity. see below")
    }
}

/// Full config after taking in command line arguments, a configuration file, and other post-computations.
///
/// See [`Args`] and [`ConfigFile`] for documentation of fields.
#[derive(Debug)]
pub struct Config {
    pub watch: bool,
    pub serve: bool,
    pub disable_incremental: bool,
    pub ignore_initial: bool,
    pub verbose: bool,
    pub trace: bool,
    pub color: LogWithColor,
    pub passthrough_copy: Vec<String>,
    pub passthrough_copy_globs: PassthroughCopyGlobs,
    // Pattern has gnarly debug impl; emit a String version instead.
    pub passthrough_copy_globs_string_form: Vec<String>,
    pub init: Vec<String>,
    pub post_processing_typ: Vec<String>,
    pub literal_paths: bool,
    pub file_listing: FileListing,
    pub file_listing_extra_args: Vec<String>,
    pub compilation_extra_args: Vec<String>,
    pub project_root: PathBuf,
    pub content_relpath: PathBuf,
    pub output_relpath: PathBuf,
    pub template_relpath: PathBuf,
}
pub const CONFIG_FNAME: &str = "compile-typst-site.toml";

impl Config {
    pub fn content_root(&self) -> PathBuf {
        self.project_root.join(&self.content_relpath)
    }

    pub fn output_root(&self) -> PathBuf {
        self.project_root.join(&self.output_relpath)
    }

    pub fn template_root(&self) -> PathBuf {
        self.project_root.join(&self.template_relpath)
    }

    pub fn new() -> Result<Self> {
        let content_relpath = PathBuf::from("src");
        let output_relpath = PathBuf::from("_site");
        let template_relpath = PathBuf::from("templates");

        let Args {
            path,
            watch,
            serve,
            ignore_initial,
            verbose,
            trace,
            color,
        } = onlyargs::parse()?;

        let color = match color {
            Some(c) => c.parse()?,
            None => LogWithColor::default(),
        };

        // map with Ok, or else search for the root, then ?
        let project_root = path.map_or_else(Self::get_project_root, Ok)?;

        let ConfigFile {
            passthrough_copy,
            init,
            post_processing_typ,
            literal_paths,
            file_listing,
            file_listing_extra_args,
            compilation_extra_args,
            disable_incremental,
        } = Self::get_configfile(&project_root)?;

        let (passthrough_copy_globs, passthrough_copy_globs_string_form) =
            Self::compile_globs(&passthrough_copy, &project_root, &content_relpath)?;

        Ok(Self {
            watch,
            serve,
            ignore_initial,
            verbose,
            trace,
            color,
            passthrough_copy,
            passthrough_copy_globs,
            passthrough_copy_globs_string_form,
            init,
            post_processing_typ,
            literal_paths,
            file_listing,
            file_listing_extra_args,
            compilation_extra_args,
            disable_incremental,
            project_root,
            content_relpath,
            output_relpath,
            template_relpath,
        })
    }

    fn get_project_root() -> Result<PathBuf> {
        let mut root = std::env::current_dir()?;

        loop {
            let candidate = root.join(CONFIG_FNAME);

            if candidate.exists() {
                return Ok(root);
            }

            if !root.pop() {
                return Err(anyhow!(
                    "Couldn't find a configuration file (looking for {CONFIG_FNAME}) in the current directory or any parent directories."
                ));
            }
        }
    }

    fn compile_globs(
        string_globs: &[String],
        project_root: &Path,
        content_root: &Path,
    ) -> Result<(PassthroughCopyGlobs, Vec<String>)> {
        let mut compiled_globs = Vec::new();
        let mut compiled_globs_string_form = Vec::new();

        for glob in string_globs {
            let string_glob = project_root
                .join(content_root)
                .join(glob)
                .to_str()
                .context(anyhow!("{glob} not utf8"))?
                .to_owned();
            let compiled_glob = string_glob.parse::<Pattern>()?;

            compiled_globs.push(compiled_glob);
            compiled_globs_string_form.push(string_glob);
        }

        let compiled_globs = PassthroughCopyGlobs(compiled_globs);

        Ok((compiled_globs, compiled_globs_string_form))
    }

    /// Destructively convert a toml value to an array of Strings.
    ///
    /// Do not rely on the array passed in after using this function.
    /// We take a mutable reference to the input, and avoid allocating by
    /// [`std::mem::take`]ing the strings instead of cloning them.
    ///
    /// Errors if the given value was not a SimpleArray, or contained non-strings.
    fn toml_to_strs(arr: &mut Toml) -> Result<Vec<String>> {
        match arr {
            Toml::SimpleArray(tomls) => {
                // not sure if this is more or less readable with map
                let mut result = Vec::with_capacity(tomls.len());
                for toml in tomls {
                    match toml {
                        Toml::Str(s) => result.push(std::mem::take(s)),
                        _ => return Err(anyhow!("toml array contained non-string: {:?}", toml)),
                    }
                }
                Ok(result)
            }
            _ => Err(anyhow!("toml value was not an array: {:?}", arr)),
        }
    }

    fn get_configfile(project_root: &Path) -> Result<ConfigFile> {
        const PROJ_ROOT_REPLACEE: &str = "$PROJECT_ROOT";

        let file = project_root.join(CONFIG_FNAME);
        let contents = fs::read_to_string(&file)
            .context(anyhow!("Couldn't find file {file:?}"))?
            .replace("\r\n", "\n"); // nanoserde can't handle windows?
        let mut given =
            TomlParser::parse(&contents).context(anyhow!("Trying to parse {file:?} failed."))?;

        let mut config = ConfigFile::default();

        macro_rules! load_strs_field {
            ($name:ident) => {
                if let Some($name) = given.get_mut(stringify!($name)) {
                    config.$name = Self::toml_to_strs($name)?;
                }
            };
        }

        load_strs_field!(passthrough_copy);
        load_strs_field!(init);
        load_strs_field!(post_processing_typ);
        if let Some(literal_paths) = given.get_mut("literal_paths") {
            match literal_paths {
                Toml::Bool(literal_paths) => config.literal_paths = *literal_paths,
                _ => return Err(anyhow!("toml value was not a bool: {:?}", literal_paths)),
            }
        }
        if let Some(file_listing) = given.get_mut("file_listing") {
            match file_listing {
                Toml::Str(file_listing) => {
                    config.file_listing = std::mem::take(file_listing).parse()?
                }
                _ => return Err(anyhow!("toml value was not a string: {:?}", file_listing)),
            }
        }
        load_strs_field!(file_listing_extra_args);
        load_strs_field!(compilation_extra_args);
        if let Some(disable_incremental) = given.get_mut("disable_incremental") {
            match disable_incremental {
                Toml::Bool(disable_incremental) => {
                    config.disable_incremental = *disable_incremental
                }
                _ => {
                    return Err(anyhow!(
                        "toml value was not a bool: {:?}",
                        disable_incremental
                    ));
                }
            }
        }

        for arg in [] // appease rustfmt
            .iter_mut()
            .chain(config.init.iter_mut())
            .chain(config.post_processing_typ.iter_mut())
        {
            *arg = arg.replace(PROJ_ROOT_REPLACEE, &project_root.to_string_lossy());
        }

        Ok(config)
    }
}