ssg 0.0.35

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
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
// Copyright © 2023 - 2026 Static Site Generator (SSG). All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Project scaffolding.
//!
//! Generates a complete starter project structure when `ssg --new`
//! is invoked, including content, templates, config, and static assets.

use anyhow::{Context, Result};
use std::{fs, path::Path};

/// Generates a new project with the given name in the current directory.
pub fn scaffold_project(name: &str) -> Result<()> {
    let cwd = std::env::current_dir()?;
    scaffold_project_at(name, &cwd)
}

/// Generates a new project at the given base directory.
pub fn scaffold_project_at(name: &str, base: &Path) -> Result<()> {
    let root = base.join(name);
    if root.exists() {
        anyhow::bail!("Directory '{name}' already exists");
    }

    // Create directory structure
    let dirs = [
        "",
        "content",
        "content/blog",
        "templates/tera",
        "static/css",
        "data",
    ];
    for dir in &dirs {
        fail::fail_point!("scaffold::create-dir", |_| {
            anyhow::bail!("injected: scaffold::create-dir")
        });
        fs::create_dir_all(root.join(dir))
            .with_context(|| format!("Failed to create {name}/{dir}"))?;
    }

    // config.toml
    fail::fail_point!("scaffold::write-config", |_| {
        anyhow::bail!("injected: scaffold::write-config")
    });
    fs::write(
        root.join("config.toml"),
        format!(
            r#"site_name = "{name}"
content_dir = "content"
output_dir = "public"
template_dir = "templates"
base_url = "http://127.0.0.1:8000"
site_title = "{name}"
site_description = "A site built with SSG"
language = "en-GB"
"#
        ),
    )?;

    // content/index.md
    fail::fail_point!("scaffold::write-index", |_| {
        anyhow::bail!("injected: scaffold::write-index")
    });
    fs::write(
        root.join("content/index.md"),
        format!(
            r"---
title: Welcome to {name}
description: A fast, accessible static site built with SSG
layout: index
---

# Welcome

This is your new SSG site. Edit `content/index.md` to get started.

## Features

- Tera templating with inheritance
- WCAG 2.1 AA accessibility by default
- JSON-LD structured data for SEO
- Syntax highlighting for code blocks
- Responsive image optimisation
- Client-side search
"
        ),
    )?;

    // content/about.md
    fail::fail_point!("scaffold::write-about", |_| {
        anyhow::bail!("injected: scaffold::write-about")
    });
    fs::write(
        root.join("content/about.md"),
        r"---
title: About
description: About this site
layout: page
---

# About

This page was generated by [SSG](https://shokunin.one).
",
    )?;

    // content/blog/first-post.md
    fail::fail_point!("scaffold::write-post", |_| {
        anyhow::bail!("injected: scaffold::write-post")
    });
    fs::write(
        root.join("content/blog/first-post.md"),
        format!(
            r#"---
title: First Post
description: My first blog post
layout: post
date: 2026-01-01
author: {name} Team
tags:
  - welcome
  - getting-started
categories:
  - blog
---

# First Post

Welcome to **{name}**! This is your first blog post.

## Code Example

```rust
fn main() {{
    println!("Hello from {name}!");
}}
```

{{{{< tip >}}}}
Edit this file at `content/blog/first-post.md`.
{{{{< /tip >}}}}
"#
        ),
    )?;

    // templates/tera/base.html
    fail::fail_point!("scaffold::write-base", |_| {
        anyhow::bail!("injected: scaffold::write-base")
    });
    fs::write(
        root.join("templates/tera/base.html"),
        r##"<!DOCTYPE html>
<html lang="{{ site.language | default(value='en') }}">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{% block title %}{{ page.title | default(value="Untitled") }}{% if site.title %} — {{ site.title }}{% endif %}{% endblock %}</title>
  {% if page.description %}<meta name="description" content="{{ page.description }}">{% endif %}
  <link rel="stylesheet" href="/css/style.css">
  {% block head_extra %}{% endblock %}
</head>
<body>
  <a href="#main-content" class="sr-only">Skip to main content</a>
  <header role="banner">
    <nav aria-label="Main navigation">
      <a href="/">{{ site.name | default(value="Home") }}</a>
      <a href="/about.html">About</a>
    </nav>
  </header>
  <main id="main-content" role="main">
    {% block content %}{% endblock %}
  </main>
  <footer role="contentinfo">
    <p>&copy; {{ site.name | default(value="") }}. Built with <a href="https://shokunin.one">SSG</a>.</p>
  </footer>
</body>
</html>
"##,
    )?;

    // templates/tera/page.html
    fail::fail_point!("scaffold::write-page-tpl", |_| {
        anyhow::bail!("injected: scaffold::write-page-tpl")
    });
    fs::write(
        root.join("templates/tera/page.html"),
        r#"{% extends "base.html" %}
{% block content %}{{ page.content | safe }}{% endblock %}
"#,
    )?;

    // templates/tera/post.html
    fail::fail_point!("scaffold::write-post-tpl", |_| {
        anyhow::bail!("injected: scaffold::write-post-tpl")
    });
    fs::write(
        root.join("templates/tera/post.html"),
        r#"{% extends "base.html" %}
{% block content %}
<article>
  <header>
    <h1>{{ page.title | default(value="") }}</h1>
    {% if page.date %}<time datetime="{{ page.date }}">{{ page.date }}</time>{% endif %}
    {% if page.author %}<span class="author">by {{ page.author }}</span>{% endif %}
    {% if page.content %}<span class="reading-time">{{ page.content | reading_time }}</span>{% endif %}
  </header>
  <div class="post-body">{{ page.content | safe }}</div>
  {% if page.tags %}
  <footer>
    <ul class="tags" aria-label="Tags">
      {% for tag in page.tags %}<li><a href="/tags/{{ tag | slugify }}/">{{ tag }}</a></li>{% endfor %}
    </ul>
  </footer>
  {% endif %}
</article>
{% endblock %}
"#,
    )?;

    // templates/tera/index.html
    fail::fail_point!("scaffold::write-index-tpl", |_| {
        anyhow::bail!("injected: scaffold::write-index-tpl")
    });
    fs::write(
        root.join("templates/tera/index.html"),
        r#"{% extends "base.html" %}
{% block title %}{{ site.title | default(value="Home") }}{% endblock %}
{% block content %}
<section>{{ page.content | safe }}</section>
{% endblock %}
"#,
    )?;

    // static/css/style.css
    fail::fail_point!("scaffold::write-css", |_| {
        anyhow::bail!("injected: scaffold::write-css")
    });
    fs::write(
        root.join("static/css/style.css"),
        r#"/* SSG Default Styles */
:root {
  --text: #1a1a2e;
  --bg: #ffffff;
  --accent: #0066cc;
  --muted: #6b7280;
  --border: #e5e7eb;
  --radius: 6px;
}
@media (prefers-color-scheme: dark) {
  :root {
    --text: #e6edf3;
    --bg: #0d1117;
    --accent: #58a6ff;
    --muted: #8b949e;
    --border: #30363d;
  }
}
*, *::before, *::after { box-sizing: border-box; }
body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  color: var(--text);
  background: var(--bg);
  line-height: 1.6;
  max-width: 48rem;
  margin: 0 auto;
  padding: 1rem 1.5rem;
}
a { color: var(--accent); }
nav { display: flex; gap: 1rem; padding: 1rem 0; border-bottom: 1px solid var(--border); }
main { padding: 2rem 0; }
footer { border-top: 1px solid var(--border); padding: 1rem 0; color: var(--muted); font-size: 0.875rem; }
pre { background: #f6f8fa; border: 1px solid var(--border); border-radius: var(--radius); padding: 1em; overflow-x: auto; }
@media (prefers-color-scheme: dark) { pre { background: #161b22; } }
code { font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; font-size: 0.875em; }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; }
.admonition { border-left: 4px solid var(--accent); padding: 0.75rem 1rem; margin: 1rem 0; border-radius: var(--radius); }
.admonition-title { font-weight: 600; margin-bottom: 0.25rem; }
.tags { list-style: none; padding: 0; display: flex; gap: 0.5rem; }
.tags li a { background: var(--border); padding: 0.25rem 0.5rem; border-radius: var(--radius); text-decoration: none; font-size: 0.875rem; }
article time, article .author, article .reading-time { color: var(--muted); font-size: 0.875rem; margin-right: 1rem; }
"#,
    )?;

    // data/nav.toml
    fail::fail_point!("scaffold::write-nav", |_| {
        anyhow::bail!("injected: scaffold::write-nav")
    });
    fs::write(
        root.join("data/nav.toml"),
        r#"[[links]]
name = "Home"
url = "/"

[[links]]
name = "About"
url = "/about.html"

[[links]]
name = "Blog"
url = "/blog/"
"#,
    )?;

    println!("Created new project: {name}");
    println!("  cd {name}");
    println!("  ssg -f config.toml");

    Ok(())
}

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

    // -------------------------------------------------------------------
    // scaffold_project_at — directory layout
    // -------------------------------------------------------------------

    #[test]
    fn scaffold_project_at_creates_complete_directory_structure() {
        let dir = tempdir().unwrap();
        let name = "test-site";
        let project = dir.path().join(name);
        scaffold_project_at(name, dir.path()).unwrap();

        // Every directory in the `dirs` array must exist.
        for sub in [
            "",
            "content",
            "content/blog",
            "templates/tera",
            "static/css",
            "data",
        ] {
            assert!(
                project.join(sub).exists(),
                "subdirectory `{sub}` should have been created"
            );
        }
    }

    #[test]
    fn scaffold_project_at_writes_all_expected_files() {
        let dir = tempdir().unwrap();
        let name = "demo";
        let project = dir.path().join(name);
        scaffold_project_at(name, dir.path()).unwrap();

        for file in [
            "config.toml",
            "content/index.md",
            "content/about.md",
            "content/blog/first-post.md",
            "templates/tera/base.html",
            "templates/tera/page.html",
            "templates/tera/post.html",
            "templates/tera/index.html",
            "static/css/style.css",
            "data/nav.toml",
        ] {
            assert!(
                project.join(file).exists(),
                "file `{file}` should have been scaffolded"
            );
        }
    }

    // -------------------------------------------------------------------
    // scaffold_project_at — content-template personalisation
    // -------------------------------------------------------------------

    #[test]
    fn scaffold_project_at_injects_project_name_into_config() {
        let dir = tempdir().unwrap();
        let name = "my-cool-site";
        scaffold_project_at(name, dir.path()).unwrap();

        let config =
            fs::read_to_string(dir.path().join(name).join("config.toml"))
                .unwrap();
        assert!(config.contains(&format!(r#"site_name = "{name}""#)));
        assert!(config.contains(&format!(r#"site_title = "{name}""#)));
        assert!(config.contains(r#"language = "en-GB""#));
    }

    #[test]
    fn scaffold_project_at_injects_project_name_into_index_md() {
        let dir = tempdir().unwrap();
        let name = "hello";
        scaffold_project_at(name, dir.path()).unwrap();

        let index =
            fs::read_to_string(dir.path().join(name).join("content/index.md"))
                .unwrap();
        assert!(index.contains(&format!("title: Welcome to {name}")));
        assert!(index.contains("layout: index"));
    }

    #[test]
    fn scaffold_project_at_injects_project_name_into_first_post() {
        let dir = tempdir().unwrap();
        let name = "projectx";
        scaffold_project_at(name, dir.path()).unwrap();

        let post = fs::read_to_string(
            dir.path().join(name).join("content/blog/first-post.md"),
        )
        .unwrap();
        assert!(post.contains(&format!("author: {name} Team")));
        assert!(post.contains(&format!("Welcome to **{name}**")));
        assert!(post.contains(&format!(r#"println!("Hello from {name}!");"#)));
    }

    #[test]
    fn scaffold_project_at_static_assets_include_dark_mode_block() {
        // Guards the prefers-color-scheme media query in style.css —
        // accessibility regression tripwire.
        let dir = tempdir().unwrap();
        scaffold_project_at("a", dir.path()).unwrap();
        let css = fs::read_to_string(
            dir.path().join("a").join("static/css/style.css"),
        )
        .unwrap();
        assert!(css.contains("@media (prefers-color-scheme: dark)"));
        assert!(css.contains(".sr-only"));
    }

    #[test]
    fn scaffold_project_at_base_template_has_accessibility_landmarks() {
        let dir = tempdir().unwrap();
        scaffold_project_at("x", dir.path()).unwrap();
        let base = fs::read_to_string(
            dir.path().join("x").join("templates/tera/base.html"),
        )
        .unwrap();
        assert!(base.contains(r#"role="banner""#));
        assert!(base.contains(r#"role="main""#));
        assert!(base.contains(r#"role="contentinfo""#));
        assert!(base.contains(r#"aria-label="Main navigation""#));
        assert!(base.contains(r#"class="sr-only""#));
    }

    #[test]
    fn scaffold_project_at_nav_toml_has_three_default_links() {
        let dir = tempdir().unwrap();
        scaffold_project_at("y", dir.path()).unwrap();
        let nav =
            fs::read_to_string(dir.path().join("y").join("data/nav.toml"))
                .unwrap();
        assert_eq!(nav.matches("[[links]]").count(), 3);
        assert!(nav.contains(r#"name = "Home""#));
        assert!(nav.contains(r#"name = "About""#));
        assert!(nav.contains(r#"name = "Blog""#));
    }

    // -------------------------------------------------------------------
    // scaffold_project_at — failure paths
    // -------------------------------------------------------------------

    #[test]
    fn scaffold_project_at_refuses_to_overwrite_existing_directory() {
        // The `anyhow::bail!` at line 22 protects user content from
        // being silently overwritten.
        let dir = tempdir().unwrap();
        let name = "existing";
        fs::create_dir(dir.path().join(name)).unwrap();

        let err = scaffold_project_at(name, dir.path()).unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("already exists"),
            "error should mention `already exists`: {msg}"
        );
    }

    #[test]
    fn scaffold_project_at_refuses_to_overwrite_existing_file() {
        // Same guard, but the pre-existing entry is a file, not a
        // directory — both trigger the `root.exists()` check.
        let dir = tempdir().unwrap();
        let name = "blocker";
        fs::write(dir.path().join(name), "i exist").unwrap();

        assert!(scaffold_project_at(name, dir.path()).is_err());
    }

    // -------------------------------------------------------------------
    // scaffold_project — default wrapper around CWD
    // -------------------------------------------------------------------

    #[test]
    fn scaffold_project_uses_current_working_directory() {
        // Exercises the `scaffold_project` entry point at line 13,
        // which wraps `scaffold_project_at` with env::current_dir().
        // We pushd into a tempdir so we don't pollute the repo root.
        let dir = tempdir().unwrap();
        let prev = std::env::current_dir().expect("read current dir");
        std::env::set_current_dir(&dir).expect("pushd");

        let result = scaffold_project("from-cwd");

        // Always restore cwd, even if the call failed.
        std::env::set_current_dir(&prev).expect("popd");

        result.expect("scaffold should succeed in a fresh cwd");
        assert!(dir.path().join("from-cwd").join("config.toml").exists());
    }
}