ssg 0.0.38

A Content-First Open Source Static Site Generator (SSG) crafted in Rust.
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
// Copyright © 2023 - 2026 Static Site Generator (SSG). All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Dev server infrastructure for the static site generator.

use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use anyhow::{anyhow, Context, Result};
use http_handle::Server;

use crate::cmd;
use crate::Paths;

/// Pluggable transport that drives the dev server.
///
/// Production code uses [`HttpTransport`] (a thin wrapper around
/// `http_handle::Server`); tests use a test-only `NoopTransport` which
/// records the call without actually binding a port. The trait exists
/// so every line of `serve_site` is unit-testable.
pub trait ServeTransport {
    /// Start serving `root` on `addr`. Implementations may block.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying transport fails to start.
    fn start(&self, addr: &str, root: &str) -> Result<()>;
}

/// Production transport: starts an `http_handle::Server`.
#[derive(Debug, Clone, Copy)]
pub struct HttpTransport;

impl ServeTransport for HttpTransport {
    fn start(&self, addr: &str, root: &str) -> Result<()> {
        let server = Server::new(addr, root);
        let _ = server.start();
        Ok(())
    }
}

/// Resolves a `site_dir` `Path` into the `(addr, root)` pair the
/// transport expects, returning an error if the path contains
/// invalid UTF-8.
///
/// Extracted from `serve_site` so the path-to-string conversion can
/// be unit-tested without invoking a transport.
pub(crate) fn build_serve_address(site_dir: &Path) -> Result<(String, String)> {
    let root = site_dir
        .to_str()
        .ok_or_else(|| {
            anyhow!(
                "Site directory path contains invalid UTF-8: {}",
                site_dir.display()
            )
        })?
        .to_string();
    let addr = format!("{}:{}", cmd::DEFAULT_HOST, cmd::DEFAULT_PORT);
    Ok((addr, root))
}

/// Starts the dev server using a caller-supplied transport.
///
/// Extracted so test code can pass a no-op transport and still
/// exercise the surrounding glue (path validation, address
/// formatting). Production callers use [`serve_site`] which
/// delegates to [`HttpTransport`].
///
/// # Errors
///
/// Returns an error if `site_dir` contains invalid UTF-8 or if the
/// underlying transport fails.
pub fn serve_site_with<T: ServeTransport>(
    site_dir: &Path,
    transport: &T,
) -> Result<()> {
    let (addr, root) = build_serve_address(site_dir)?;
    transport.start(&addr, &root)
}

/// Converts a site directory path to a string and starts an HTTP server.
///
/// This function blocks while the server is running.
///
/// # Errors
///
/// Returns an error if `site_dir` contains invalid UTF-8.
pub fn serve_site(site_dir: &Path) -> Result<()> {
    serve_site_with(site_dir, &HttpTransport)
}

/// Configures and launches the development server.
///
/// Sets up a local server for testing and previewing the generated site.
/// Handles file copying and server configuration for local development.
///
/// # Arguments
///
/// * `log_file` - Reference to the active log file
/// * `date` - Current timestamp for logging
/// * `paths` - All required directory paths
/// * `serve_dir` - Directory to serve content from
///
/// # Returns
///
/// * `Ok(())` - If server starts successfully
/// * `Err` - If server configuration or startup fails
///
/// # Examples
///
/// ```rust,no_run
/// use std::path::PathBuf;
/// use ssg::{Paths, handle_server, create_log_file};
///
/// fn main() -> anyhow::Result<()> {
///     let mut log_file = create_log_file("./server.log")?;
///     let date = ssg::now_iso();
///     let paths = Paths {
///         site: PathBuf::from("public"),
///         content: PathBuf::from("content"),
///         build: PathBuf::from("build"),
///         template: PathBuf::from("templates"),
///     };
///     let serve_dir = PathBuf::from("serve");
///
///     handle_server(&mut log_file, &date, &paths, &serve_dir)?;
///     Ok(())
/// }
/// ```
///
/// # Server Configuration
///
/// * Default port: 8000
/// * Host: 127.0.0.1 (localhost)
/// * Serves static files from the specified directory
pub fn handle_server(
    log_file: &mut fs::File,
    date: &str,
    paths: &Paths,
    serve_dir: &PathBuf,
) -> Result<()> {
    // Log server initialization
    writeln!(log_file, "[{date}] INFO process: Server initialization")?;

    prepare_serve_dir(paths, serve_dir)?;

    let host = cmd::resolve_host();
    let port = cmd::resolve_port();
    let addr = format!("{host}:{port}");

    println!("\nStarting server at http://{addr}");
    println!("Serving content from: {}", serve_dir.display());

    let dir = serve_dir
        .to_str()
        .ok_or_else(|| anyhow::anyhow!("serve dir contains invalid UTF-8"))?
        .to_string();
    let bind = addr;

    let server = Server::new(&bind, &dir);
    let _ = server.start();
    Ok(())
}

/// Generates a root index.html that reads the browser's language
/// preference and redirects to the best matching locale directory.
///
/// The file is written at `site_dir/index.html`. If it already exists
/// and was not generated by this function, it is left untouched.
///
/// # Errors
///
/// Returns an error if the file cannot be written.
pub fn generate_locale_redirect(
    site_dir: &Path,
    available_locales: &[String],
    default_locale: &str,
) -> Result<()> {
    let index_path = site_dir.join("index.html");

    // If an index.html already exists and wasn't generated by us, leave it.
    if index_path.exists() {
        let existing = fs::read_to_string(&index_path).unwrap_or_default();
        if !existing.contains("<!-- ssg-locale-redirect -->") {
            return Ok(());
        }
    }

    let locales_js: Vec<String> = available_locales
        .iter()
        .map(|l| format!("\"{l}\""))
        .collect();
    let locales_array = locales_js.join(",");
    let default_url = format!("/{default_locale}/");

    let html = format!(
        r#"<!DOCTYPE html>
<!-- ssg-locale-redirect -->
<html>
<head>
<meta charset="utf-8">
<script>
(function() {{
  var locales = [{locales_array}];
  var defaultLocale = "{default_locale}";
  var langs = navigator.languages || [navigator.language || defaultLocale];
  for (var i = 0; i < langs.length; i++) {{
    var lang = langs[i].toLowerCase();
    for (var j = 0; j < locales.length; j++) {{
      if (lang === locales[j] || lang.startsWith(locales[j] + "-")) {{
        window.location.replace("/" + locales[j] + "/");
        return;
      }}
    }}
    var prefix = lang.split("-")[0];
    for (var j = 0; j < locales.length; j++) {{
      if (prefix === locales[j]) {{
        window.location.replace("/" + locales[j] + "/");
        return;
      }}
    }}
  }}
  window.location.replace("/" + defaultLocale + "/");
}})();
</script>
<noscript>
<meta http-equiv="refresh" content="0; url={default_url}">
</noscript>
</head>
<body></body>
</html>
"#
    );

    fs::write(&index_path, &html)
        .with_context(|| format!("Failed to write {}", index_path.display()))?;

    println!(
        "[i18n] Generated locale redirect at {}",
        index_path.display()
    );
    Ok(())
}

/// Prepares the serve directory by creating it and copying site files.
pub fn prepare_serve_dir(paths: &Paths, serve_dir: &PathBuf) -> Result<()> {
    fs::create_dir_all(serve_dir)
        .context("Failed to create serve directory")?;

    println!("Setting up server...");
    println!("Source: {}", paths.site.display());
    println!("Serving from: {}", serve_dir.display());

    if serve_dir != &paths.site {
        crate::fs_ops::verify_and_copy_files_async(&paths.site, serve_dir)?;
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {

    use super::*;
    use std::sync::{Arc, Mutex};
    use tempfile::tempdir;

    /// Test transport that records `(addr, root)` and never blocks.
    #[derive(Default)]
    struct RecordingTransport {
        calls: Arc<Mutex<Vec<(String, String)>>>,
        fail: bool,
    }

    impl ServeTransport for RecordingTransport {
        fn start(&self, addr: &str, root: &str) -> Result<()> {
            self.calls
                .lock()
                .unwrap()
                .push((addr.to_string(), root.to_string()));
            if self.fail {
                Err(anyhow!("synthetic transport failure"))
            } else {
                Ok(())
            }
        }
    }

    #[test]
    fn build_serve_address_formats_addr_and_returns_root() {
        let dir = tempdir().unwrap();
        let (addr, root) = build_serve_address(dir.path()).unwrap();
        assert!(
            addr.contains(cmd::DEFAULT_HOST),
            "addr should contain default host: {addr}"
        );
        assert!(
            addr.contains(&cmd::DEFAULT_PORT.to_string()),
            "addr should contain default port: {addr}"
        );
        assert_eq!(root, dir.path().to_str().unwrap());
    }

    #[test]
    fn serve_site_with_invokes_transport_with_resolved_address() {
        let dir = tempdir().unwrap();
        let transport = RecordingTransport::default();
        let calls = transport.calls.clone();
        serve_site_with(dir.path(), &transport).unwrap();
        let recorded = calls.lock().unwrap().clone();
        assert_eq!(recorded.len(), 1);
        let (addr, root) = &recorded[0];
        assert!(addr.contains(cmd::DEFAULT_HOST));
        assert_eq!(root, dir.path().to_str().unwrap());
    }

    #[test]
    fn serve_site_with_propagates_transport_errors() {
        let dir = tempdir().unwrap();
        let transport = RecordingTransport {
            calls: Default::default(),
            fail: true,
        };
        let err = serve_site_with(dir.path(), &transport).unwrap_err();
        assert!(
            err.to_string().contains("synthetic transport failure"),
            "transport error should bubble up, got: {err}"
        );
    }

    #[test]
    fn http_transport_implements_serve_transport() {
        // Smoke test that HttpTransport satisfies the trait. We don't
        // actually call .start() here because that would bind a port.
        let _t: &dyn ServeTransport = &HttpTransport;
    }

    #[test]
    fn generate_locale_redirect_creates_index_with_marker() {
        let dir = tempdir().unwrap();
        generate_locale_redirect(
            dir.path(),
            &["en".to_string(), "fr".to_string(), "de".to_string()],
            "en",
        )
        .unwrap();

        let index = dir.path().join("index.html");
        assert!(index.exists(), "index.html should be written");

        let html = fs::read_to_string(&index).unwrap();
        assert!(html.contains("<!-- ssg-locale-redirect -->"));
        assert!(html.contains("\"en\""));
        assert!(html.contains("\"fr\""));
        assert!(html.contains("\"de\""));
        assert!(html.contains("/en/")); // default fallback
    }

    #[test]
    fn generate_locale_redirect_overwrites_own_marker() {
        let dir = tempdir().unwrap();

        // First call writes the file.
        generate_locale_redirect(dir.path(), &["en".to_string()], "en")
            .unwrap();
        let first = fs::read_to_string(dir.path().join("index.html")).unwrap();

        // Second call with different locales must overwrite.
        generate_locale_redirect(
            dir.path(),
            &["en".to_string(), "fr".to_string()],
            "en",
        )
        .unwrap();
        let second = fs::read_to_string(dir.path().join("index.html")).unwrap();

        assert_ne!(first, second);
        assert!(second.contains("\"fr\""));
    }

    #[test]
    fn generate_locale_redirect_preserves_user_index_html() {
        // If the user wrote their own index.html (no marker), don't overwrite.
        let dir = tempdir().unwrap();
        let user_html = "<html><body>my hand-written page</body></html>";
        fs::write(dir.path().join("index.html"), user_html).unwrap();

        generate_locale_redirect(dir.path(), &["en".to_string()], "en")
            .unwrap();

        let after = fs::read_to_string(dir.path().join("index.html")).unwrap();
        assert_eq!(
            after, user_html,
            "user-authored index.html must not be overwritten"
        );
    }

    #[test]
    fn prepare_serve_dir_creates_dir_when_missing() {
        let dir = tempdir().unwrap();
        let site = dir.path().join("site");
        fs::create_dir_all(&site).unwrap();
        fs::write(site.join("a.html"), "x").unwrap();

        let serve = dir.path().join("serve-out");
        let paths = Paths {
            site: site.clone(),
            content: dir.path().join("content"),
            build: dir.path().join("build"),
            template: dir.path().join("templates"),
        };

        prepare_serve_dir(&paths, &serve).unwrap();

        assert!(serve.exists(), "serve dir should be created");
        assert!(
            serve.join("a.html").exists(),
            "files should be copied from site to serve dir"
        );
    }

    #[test]
    fn prepare_serve_dir_skips_copy_when_serve_equals_site() {
        let dir = tempdir().unwrap();
        let site = dir.path().join("site");
        fs::create_dir_all(&site).unwrap();
        fs::write(site.join("a.html"), "x").unwrap();

        let paths = Paths {
            site: site.clone(),
            content: dir.path().join("content"),
            build: dir.path().join("build"),
            template: dir.path().join("templates"),
        };

        // serve_dir == site — should not re-copy (no-op).
        prepare_serve_dir(&paths, &site).unwrap();
        assert!(site.join("a.html").exists());
    }

    #[test]
    fn build_serve_address_contains_host_and_port() {
        let dir = tempdir().unwrap();
        let (addr, root) = build_serve_address(dir.path()).unwrap();
        assert_eq!(
            addr,
            format!("{}:{}", cmd::DEFAULT_HOST, cmd::DEFAULT_PORT)
        );
        assert_eq!(root, dir.path().to_str().unwrap());
    }

    #[test]
    fn serve_site_with_records_correct_root() {
        let dir = tempdir().unwrap();
        let sub = dir.path().join("deep").join("nested");
        fs::create_dir_all(&sub).unwrap();
        let transport = RecordingTransport::default();
        let calls = transport.calls.clone();
        serve_site_with(&sub, &transport).unwrap();
        let recorded = calls.lock().unwrap();
        assert_eq!(recorded[0].1, sub.to_str().unwrap());
    }

    #[test]
    fn generate_locale_redirect_single_locale() {
        let dir = tempdir().unwrap();
        generate_locale_redirect(dir.path(), &["es".to_string()], "es")
            .unwrap();
        let html = fs::read_to_string(dir.path().join("index.html")).unwrap();
        assert!(html.contains("\"es\""));
        assert!(html.contains("/es/"));
        assert!(html.contains("<!-- ssg-locale-redirect -->"));
    }
}