hauchiwa 0.9.1

Flexible static website generator library with incremental rebuilds and cached image optimization
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
#![doc = include_str!("../README.md")]
#![deny(
    unsafe_code,
    // clippy::unwrap_used,
    // clippy::expect_used,
    clippy::panic,
)]

pub mod error;
mod executor;
mod graph;
pub mod importmap;
pub mod loader;
pub mod page;
mod utils;

use std::{any::type_name, fmt::Debug, sync::Arc};

use camino::Utf8PathBuf;
use graph::TaskDependencies;
use petgraph::{Graph, graph::NodeIndex};

pub use camino;
pub use gitscan as git;

pub use crate::executor::Diagnostics;
pub use crate::graph::Handle;
pub use crate::importmap::ImportMap;
pub use crate::loader::Store;
pub use crate::page::Output;

use crate::graph::{Dynamic, Task, TypedTask};

/// 32 bytes length generic hash
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
struct Hash32([u8; 32]);

impl<T> From<T> for Hash32
where
    T: Into<[u8; 32]>,
{
    fn from(value: T) -> Self {
        Hash32(value.into())
    }
}

impl Hash32 {
    fn hash(buffer: impl AsRef<[u8]>) -> Self {
        blake3::Hasher::new()
            .update(buffer.as_ref())
            .finalize()
            .into()
    }

    fn hash_file(path: impl AsRef<std::path::Path>) -> std::io::Result<Self> {
        Ok(blake3::Hasher::new()
            .update_mmap_rayon(path)?
            .finalize()
            .into())
    }

    fn to_hex(self) -> String {
        const HEX: &[u8; 16] = b"0123456789abcdef";
        let mut acc = vec![0u8; 64];

        for (i, &byte) in self.0.iter().enumerate() {
            acc[i * 2] = HEX[(byte >> 4) as usize];
            acc[i * 2 + 1] = HEX[(byte & 0xF) as usize];
        }

        String::from_utf8(acc).unwrap()
    }
}

impl Debug for Hash32 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Hash32({})", self.to_hex())
    }
}

/// The mode in which the site generator is running.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    /// A one-time build.
    Build,
    /// A continuous watch mode for development.
    Watch,
}

/// Global configuration and state available to all tasks.
///
/// This struct allows you to share global data (like configuration options or
/// shared state) across your entire task graph.
///
/// # Type Parameters
///
/// * `G`: The type of the user-defined global data. Must be `Send + Sync`.
#[derive(Clone)]
pub struct Environment<D: Send + Sync = ()> {
    /// The name of the generator (defaults to "hauchiwa").
    pub generator: &'static str,
    /// The current build mode (Build or Watch).
    pub mode: Mode,
    /// The port of the development server (if running).
    pub port: Option<u16>,
    /// User-defined global data.
    pub data: D,
}

impl<G: Send + Sync> Environment<G> {
    /// Returns a JavaScript snippet to enable live-reloading.
    ///
    /// If the site is running in `Watch` mode and a port is configured, this returns
    /// a script that connects to the WebSocket server to listen for reload events.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use hauchiwa::{Blueprint, task};
    /// # let mut config = Blueprint::<()>::default();
    /// # task!(config, |ctx| {
    /// let script = ctx.env.get_refresh_script();
    /// if let Some(s) = script {
    ///     // Inject `s` into your HTML <head> or <body>
    /// }
    /// # Ok(())
    /// # });
    /// ```
    pub fn get_refresh_script(&self) -> Option<String> {
        self.port.map(|port| {
            format!(
                r#"
const socket = new WebSocket("ws://localhost:{port}");
socket.addEventListener("message", event => {{
    window.location.reload();
}});
"#
            )
        })
    }
}

/// The context passed to every task execution.
///
/// `TaskContext` provides access to global settings and the aggregated import
/// map from all dependencies. It is immutable during task execution.
pub struct TaskContext<'a, G: Send + Sync = ()> {
    /// Access to global configuration and data.
    pub env: &'a Environment<G>,
    /// The current import map, containing JavaScript module mappings from all
    /// upstream dependencies.
    pub importmap: &'a ImportMap,
}

#[derive(Debug)]
pub struct FileMetadata {
    pub file: Utf8PathBuf,
    pub area: Utf8PathBuf,
    pub info: Option<crate::git::GitInfo>,
}

struct TaskNode<G, R, D, F>
where
    G: Send + Sync,
    R: Send + Sync + 'static,
    D: TaskDependencies,
    F: for<'a> Fn(&TaskContext<'a, G>, D::Output<'a>) -> anyhow::Result<R> + Send + Sync,
{
    name: &'static str,
    dependencies: D,
    callback: F,
    _phantom: std::marker::PhantomData<G>,
}

impl<G, R, D, F> TypedTask<G> for TaskNode<G, R, D, F>
where
    G: Send + Sync + 'static,
    R: Send + Sync + 'static,
    D: TaskDependencies + Send + Sync,
    F: for<'a> Fn(&TaskContext<'a, G>, D::Output<'a>) -> anyhow::Result<R> + Send + Sync + 'static,
{
    type Output = R;

    fn get_name(&self) -> String {
        self.name.to_string()
    }

    fn dependencies(&self) -> Vec<NodeIndex> {
        self.dependencies.dependencies()
    }

    fn execute(
        &self,
        context: &TaskContext<G>,
        _: &mut Store,
        dependencies: &[Dynamic],
    ) -> anyhow::Result<Self::Output> {
        let dependencies = self.dependencies.resolve(dependencies);
        (self.callback)(context, dependencies)
    }
}

/// The blueprint for your static site.
///
/// `Blueprint` is used to define the Task graph of your website. You add tasks
/// (including loaders) to the config, and wire them together using their
/// [`Handle`]s.
///
/// Once configured, you convert this into a [`Website`] to execute the build.
///
/// # Example
///
/// ```rust,no_run
/// use hauchiwa::Blueprint;
///
/// let mut config: Blueprint<()> = Blueprint::new();
/// // Add tasks here...
/// ```
pub struct Blueprint<G: Send + Sync = ()> {
    graph: Graph<Arc<dyn Task<G>>, ()>,
}

impl<G: Send + Sync + 'static> Blueprint<G> {
    /// Creates a new, empty configuration.
    pub fn new() -> Self {
        Self {
            graph: Graph::new(),
        }
    }

    pub fn finish(self) -> Website<G> {
        Website { graph: self.graph }
    }

    /// Adds a custom task to the graph.
    ///
    /// This is the low-level method for adding tasks. For a more ergonomic
    /// experience, consider using the [`task!`](crate::task!) macro.
    ///
    /// # Arguments
    ///
    /// * `dependencies` - A tuple of handles to tasks that must run before this one.
    /// * `callback` - The closure that executes the task. It receives the
    ///   `Context` and the resolved outputs of the dependencies.
    ///
    /// # Returns
    ///
    /// A [`Handle`] representing the future result of this task.
    pub fn add_task<D, F, R>(&mut self, dependencies: D, callback: F) -> graph::Handle<R>
    where
        D: TaskDependencies + Send + Sync + 'static,
        F: for<'a> Fn(&TaskContext<'a, G>, D::Output<'a>) -> anyhow::Result<R>
            + Send
            + Sync
            + 'static,
        R: Send + Sync + 'static,
    {
        self.add_task_opaque(TaskNode {
            name: type_name::<F>(),
            dependencies,
            callback,
            _phantom: std::marker::PhantomData,
        })
    }

    pub(crate) fn add_task_opaque<O, T>(&mut self, task: T) -> graph::Handle<O>
    where
        O: 'static,
        T: TypedTask<G, Output = O> + 'static,
    {
        let dependencies = task.dependencies();
        let index = self.graph.add_node(Arc::new(task));

        for dependency in dependencies {
            self.graph.add_edge(dependency, index, ());
        }

        graph::Handle::new(index)
    }
}

impl<G: Send + Sync + 'static> Default for Blueprint<G> {
    fn default() -> Self {
        Self::new()
    }
}

impl<G> std::fmt::Display for Blueprint<G>
where
    G: Send + Sync + 'static,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "graph LR")?;

        for index in self.graph.node_indices() {
            let task = &self.graph[index];
            let name = task.get_name().replace('"', "\\\""); // Simple escape
            writeln!(f, "    {:?}[\"{}\"]", index.index(), name)?;

            if task.is_output() {
                writeln!(f, "    {:?} --> Output", index.index())?;
            }
        }

        writeln!(f, "    Output[Output]")?;

        for edge in self.graph.edge_indices() {
            let (source, target) = self.graph.edge_endpoints(edge).unwrap();
            let source_task = &self.graph[source];
            let type_name = source_task
                .get_output_type_name()
                .replace('<', "&lt;")
                .replace('>', "&gt;");
            writeln!(
                f,
                "    {:?} -- \"{}\" --> {:?}",
                source.index(),
                type_name,
                target.index()
            )?;
        }

        Ok(())
    }
}

/// Represents the configured site and provides methods for building and serving
/// it with a development server.
///
/// A [`Website`] is created from a [`Blueprint`] and is the primary interface
/// for executing the build process.
pub struct Website<G: Send + Sync = ()> {
    graph: Graph<Arc<dyn Task<G>>, ()>,
}

impl<G> Website<G>
where
    G: Send + Sync + 'static,
{
    pub fn design() -> Blueprint<G> {
        Blueprint::default()
    }

    /// Runs the build process once.
    ///
    /// This will:
    /// 1. Clean the `dist` directory.
    /// 2. Copy static files.
    /// 3. Execute the task graph in parallel.
    /// 4. Save the generated [`Output`]s to `dist`.
    ///
    /// # Arguments
    ///
    /// * `data` - The global user data to pass to all tasks.
    pub fn build(&mut self, data: G) -> anyhow::Result<Diagnostics> {
        let globals = Environment {
            generator: "hauchiwa",
            mode: Mode::Build,
            port: None,
            data,
        };

        utils::clear_dist().expect("Failed to clear dist directory");
        utils::clone_static().expect("Failed to copy static files");

        let (_, pages, diagnostics) = crate::executor::run_once_parallel(self, &globals)?;

        crate::page::save_pages_to_dist(&pages).expect("Failed to save pages");

        Ok(diagnostics)
    }

    /// Starts the development server in watch mode.
    ///
    /// This will perform an initial build and then watch for file changes.
    /// When a file changes, only the affected tasks are re-run.
    ///
    /// # Arguments
    ///
    /// * `data` - The global user data to pass to all tasks.
    #[cfg(feature = "live")]
    pub fn watch(&mut self, data: G) -> anyhow::Result<()> {
        utils::clear_dist().expect("Failed to clear dist directory");
        utils::clone_static().expect("Failed to copy static files");

        crate::executor::watch(self, data)?;

        Ok(())
    }
}

/// A convenient macro for defining tasks.
///
/// To avoid manual tuple destructuring of dependencies, the `task!` macro
/// provides a DSL that makes dependencies look like standard function
/// arguments. It compiles down to the standard `Blueprint::add_task` call but
/// hides the tuple boilerplate.
///
/// # Syntax
///
/// ```rust,no_run
/// # use hauchiwa::{Blueprint, task};
/// # let mut config = Blueprint::<()>::default();
/// # let dep1 = config.load_documents::<()>("content/posts/*.md").unwrap();
/// # let dep2 = config.load_documents::<()>("content/posts/*.md").unwrap();
/// task!(config, |context, dep1, dep2| {
///     // body
///     # Ok(())
/// });
/// ```
///
/// # Example
///
/// ```rust,no_run
/// # use hauchiwa::{Blueprint, task};
/// # let mut config: Blueprint<()> = Blueprint::new();
/// // Assume `dep_a` and `dep_b` are Handles from previous tasks.
/// // let dep_a = ...;
/// // let dep_b = ...;
///
/// # let dep_a = config.add_task((), |_, _| Ok(()));
/// # let dep_b = config.add_task((), |_, _| Ok(()));
///
/// task!(config, |ctx, dep_a, dep_b| {
///     // `dep_a` and `dep_b` here are the *results* of the tasks, not the handles.
///     println!("Task running!");
///     Ok(())
/// });
/// ```
#[macro_export]
macro_rules! task {
    ($config:expr, |$ctx:pat_param $(, $($dep:ident $( : $ty:ty )? ),* )? | $body:block) => {
        $config.add_task(
            ( $( $($dep),* )? ),
            |$ctx, ( $( $($dep),* )? )| {
                // For each `ident: Ty`, emit: `let _: Ty = ident;`
                $( $( $( let _: $ty = $dep; )? )* )?

                $body
            }
        )
    };
}