cliche 1.2.0

Dead simple static site generator.
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
use std::{
    fs::{self, File},
    io::Write,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use clap::Parser;
use fs_extra::dir::{self, CopyOptions};
use handlebars::Handlebars;
use pulldown_cmark::{html::push_html, CowStr, Event, Options, Tag};
use serde_json::Value;
use shellexpand::tilde;
use walkdir::WalkDir;

fn main() {
    let args = Args::parse();
    generate_site(args)
}

/// Command line arguments for the application.
#[derive(clap::Parser, Debug)]
#[command(version, about, long_about=None)]
struct Args {
    /// Directory containing the site's content.
    content: String,

    /// Path to the site's header.
    #[arg(long, default_value = "header.md")]
    header: String,

    /// Path to the site's footer.
    #[arg(long, default_value = "footer.md")]
    footer: String,

    /// Path to the site's stylesheet.
    #[arg(long, default_value = "style.css")]
    style: String,

    /// Site output directory. Will be created if it doesn't already exist.
    #[arg(short, long, default_value = "_site")]
    output: String,

    /// The domain of the site, used for generating full URLs in the sitemap. If
    /// not provided, a sitemap will not be generated.
    #[arg(long)]
    domain: Option<String>,

    /// A base url that the site will be served from.
    #[arg(long)]
    base_url: Option<String>,
}

/// Generates the static site using provided command line arguments.
///
/// # Arguments
/// * `args` - Parsed command line arguments.
fn generate_site(args: Args) {
    let content_path = get_content_path(args.content)
        .map_err(|e| eprintln!("Error extracting the content path: {}", e))
        .unwrap_or_else(|_| std::process::exit(1));
    let output_path = get_output_path(args.output)
        .map_err(|e| eprintln!("Error preparing the output path: {}", e))
        .unwrap_or_else(|_| std::process::exit(1));
    let base_url = args.base_url.as_deref();

    copy_static_assets(&content_path, &output_path)
        .map_err(|e| eprintln!("Error copying static assets: {}", e))
        .unwrap_or_else(|_| std::process::exit(1));

    let style = load_style(&args.style);
    let header = load_header(&args.header, &content_path, base_url);
    let footer = load_footer(&args.footer, &content_path, base_url);
    let mut sitemap_entries = Vec::new();

    for entry in WalkDir::new(&content_path)
        .into_iter()
        .filter_entry(|e| !e.path().starts_with(&content_path.join("static")))
        .filter_map(|e| e.ok())
    {
        if entry.file_type().is_file() && entry.path().extension().map_or(false, |e| e == "md") {
            let html_content = load_html_from_md_file(entry.path(), &content_path, base_url)
                .map_err(|e| eprintln!("Error rendering markdown to HTML: {}", e))
                .unwrap_or_else(|_| std::process::exit(1));

            let relative_path = entry
                .path()
                .strip_prefix(&content_path)
                .unwrap()
                .with_extension("html");
            let output_path = output_path.join(&relative_path);

            if let Some(ref domain) = args.domain {
                let full_url = if let Some(base) = base_url {
                    format!(
                        "{}/{}/{}",
                        domain.trim_end_matches("/"),
                        base.trim_start_matches("/").trim_end_matches("/"),
                        relative_path.to_string_lossy()
                    )
                } else {
                    format!(
                        "{}/{}",
                        domain.trim_end_matches("/"),
                        relative_path.to_string_lossy()
                    )
                };
                sitemap_entries.push(full_url);
            };

            let final_html = render_template(
                style.as_deref(),
                header.as_ref().map(|content| content.html.as_str()),
                footer.as_ref().map(|content| content.html.as_str()),
                html_content,
            )
            .map_err(|e| eprintln!("Error rendering template: {}", e))
            .unwrap_or_else(|_| std::process::exit(1));

            if let Some(parent) = output_path.parent() {
                fs::create_dir_all(parent)
                    .map_err(|e| eprintln!("Error creating content directory: {}", e))
                    .unwrap_or_else(|_| std::process::exit(1));
            }
            fs::write(output_path, final_html)
                .map_err(|e| eprintln!("Error writing generated HTML to file: {}", e))
                .unwrap_or_else(|_| std::process::exit(1));
        }
    }

    if let Some(_) = args.domain {
        generate_sitemap(&output_path, &sitemap_entries)
            .map_err(|e| eprintln!("Error generating sitemap: {}", e))
            .unwrap_or_else(|_| std::process::exit(1));
    }
}

/// Retrieves the absolute path for the content directory, handling expansion of any user variables.
///
/// # Arguments
/// * `content_path` - The path to the content directory.
///
/// # Returns
/// * A `Result<PathBuf>` which is the absolute path of the content directory.
fn get_content_path(content_path: impl AsRef<str>) -> Result<PathBuf> {
    get_absolute_path(content_path)
}

/// Prepares the output directory for the site. If it exists, it is cleared; if not, it is created.
///
/// # Arguments
/// * `output_path` - The path to the output directory.
///
/// # Returns
/// * A `Result<PathBuf>` which is the prepared path of the output directory.
fn get_output_path(output_path: impl AsRef<str>) -> Result<PathBuf> {
    match get_absolute_path(&output_path) {
        Ok(path) => {
            // Path exists and is canonicalized, remove contents
            fs::remove_dir_all(&path)?;
            fs::create_dir_all(&path)?;
            Ok(path)
        }
        Err(_) => {
            // Path does not exist, create it and canonicalize it again
            let output_path = expand_path(output_path);
            fs::create_dir_all(&output_path)?;
            Ok(fs::canonicalize(&output_path)?)
        }
    }
}

/// Copies static assets from the content directory to the output directory.
///
/// # Arguments
/// * `content_path` - Path to the content directory containing static assets.
/// * `output_path` - Path to the output directory where static assets should be copied.
///
/// # Returns
/// * A `Result<()>` indicating the success or failure of the operation.
fn copy_static_assets(content_path: &Path, output_path: &Path) -> Result<()> {
    let static_dir = content_path.join("static");
    let output_static_dir = output_path.join("static");
    if static_dir.exists() {
        fs::create_dir_all(&output_static_dir)?;

        let mut options = CopyOptions::new();
        options.overwrite = true;
        options.content_only = true;
        dir::copy(&static_dir, &output_static_dir, &options)?;
    }
    Ok(())
}

/// Attempts to load the stylesheet from a specified path.
///
/// # Arguments
/// * `style_path` - Path to the stylesheet file.
///
/// # Returns
/// * An `Option<String>` containing the stylesheet content, or `None` if the file could not be read.
fn load_style(style_path: impl AsRef<str>) -> Option<String> {
    get_absolute_path(style_path)
        .ok()
        .and_then(|path| fs::read_to_string(&path).ok())
}

/// Loads and processes the header markdown file into HTML content.
///
/// # Arguments
/// * `header_path` - Path to the header markdown file.
/// * `content_path` - Path to the content directory for resolving relative paths.
///
/// # Returns
/// * An `Option<HTMLContent>` containing the processed header HTML content, or `None` if an error occurs.
fn load_header(
    header_path: impl AsRef<str>,
    content_path: &Path,
    base_url: Option<&str>,
) -> Option<HTMLContent> {
    let header_path = get_absolute_path(header_path).ok()?;
    load_html_from_md_file(&header_path, content_path, base_url).ok()
}

/// Loads and processes the footer markdown file into HTML content.
///
/// # Arguments
/// * `footer_path` - Path to the footer markdown file.
/// * `content_path` - Path to the content directory for resolving relative paths.
///
/// # Returns
/// * An `Option<HTMLContent>` containing the processed footer HTML content, or `None` if an error occurs.
fn load_footer(
    footer_path: impl AsRef<str>,
    content_path: &Path,
    base_url: Option<&str>,
) -> Option<HTMLContent> {
    let footer_path = get_absolute_path(footer_path).ok()?;
    load_html_from_md_file(&footer_path, content_path, base_url).ok()
}

/// Converts a given markdown file's contents to HTML, incorporating the site's layout.
///
/// # Arguments
/// * `path` - Path to the markdown file.
/// * `content_path` - Path to the content directory for resolving relative paths.
/// * base_url - Base url that the site will be served from.
///
/// # Returns
/// * A `Result<HTMLContent>` containing the HTML content or an error if conversion fails.
fn load_html_from_md_file(
    path: &Path,
    content_path: &Path,
    base_url: Option<&str>,
) -> Result<HTMLContent> {
    fs::read_to_string(&path)
        .with_context(|| format!("Failed to read from markdown file: {:?}", path))
        .and_then(|file_content| process_markdown(&file_content))
        .with_context(|| "Failed to process markdown file.")
        .and_then(|markdown_content| {
            let html = markdown_to_html(&markdown_content.markdown, content_path, base_url)
                .with_context(|| "Failed to convert markdown to HTML.")?;
            Ok(HTMLContent {
                front_matter: markdown_content.front_matter,
                html,
            })
        })
}

/// Renders the final HTML content using a template and dynamic parts such as style, header, and footer.
///
/// # Arguments
/// * `style` - Optional stylesheet content.
/// * `header` - Optional header content.
/// * `footer` - Optional footer content.
/// * `content` - Main content of the HTML.
///
/// # Returns
/// * A `Result<String>` containing the final rendered HTML or an error if rendering fails.
fn render_template(
    style: Option<&str>,
    header: Option<&str>,
    footer: Option<&str>,
    content: HTMLContent,
) -> Result<String> {
    let mut handlebars = Handlebars::new();
    handlebars.register_template_string("template", include_str!("./template.html"))?;

    let data = serde_json::json!({
        "title": content.front_matter.as_ref().map_or("", |fm| fm.title.as_deref().unwrap_or("")),
        "description": content.front_matter.as_ref().map_or("", |fm| fm.description.as_deref().unwrap_or("")) ,
        "style": style.as_deref().unwrap_or(""),
        "header": header.as_deref().unwrap_or(""),
        "footer": footer.as_deref().unwrap_or(""),
        "content": content.html
    });

    Ok(handlebars.render("template", &data)?)
}

/// Converts a relative or tilde-expanded path to an absolute path.
///
/// # Arguments
/// * `path` - The path to be expanded and resolved.
///
/// # Returns
/// * A `Result<PathBuf>` containing the absolute path or an error if the path cannot be resolved.
fn get_absolute_path(path: impl AsRef<str>) -> Result<PathBuf> {
    Ok(fs::canonicalize(expand_path(path))?)
}

/// Expands the provided path, handling tilde notation for the home directory.
///
/// # Arguments
/// * `path` - The path to expand.
///
/// # Returns
/// * An expanded `PathBuf`.
fn expand_path(path: impl AsRef<str>) -> String {
    tilde(path.as_ref()).into_owned()
}

/// Data structure for holding front matter extracted from markdown.
struct FrontMatter {
    title: Option<String>,
    description: Option<String>,
}

/// Data structure for holding markdown content, potentially including extracted front matter.
struct MarkdownContent {
    front_matter: Option<FrontMatter>,
    markdown: String,
}

/// Data structure for holding HTML content, potentially including metadata from front matter.
struct HTMLContent {
    front_matter: Option<FrontMatter>,
    html: String,
}

/// Processes markdown content, extracting front matter if present, and converts it to structured content.
///
/// # Arguments
/// * content - The markdown content to process.
///
/// # Returns
/// * A Result<MarkdownContent> containing structured markdown and extracted front matter.
fn process_markdown(content: &str) -> Result<MarkdownContent> {
    // Check if the content starts with front matter delimiters
    if content.starts_with("---") {
        let parts: Vec<&str> = content.splitn(3, "---").collect();

        if parts.len() == 3 {
            // Parse the YAML front matter
            let front_matter_str = parts[1];
            let rest_content = parts[2];

            let front_matter: Value = serde_yaml::from_str(front_matter_str)
                .with_context(|| "Failed to parse YAML front matter.")?;

            // Extract title from front matter, default to empty if not present
            let title = front_matter
                .get("title")
                .and_then(Value::as_str)
                .map(|s| s.to_owned());
            let meta_description = front_matter
                .get("meta_description")
                .and_then(Value::as_str)
                .map(|s| s.to_owned());

            Ok(MarkdownContent {
                front_matter: Some(FrontMatter {
                    title,
                    description: meta_description,
                }),
                markdown: rest_content.trim_start().to_string(),
            })
        } else {
            Ok(MarkdownContent {
                front_matter: None,
                markdown: content.to_string(),
            })
        }
    } else {
        Ok(MarkdownContent {
            front_matter: None,
            markdown: content.to_string(),
        })
    }
}

/// Converts markdown text to HTML format using a specified content directory to resolve paths.
///
/// # Arguments
/// * markdown_input - The markdown text to convert.
/// * content_dir - The content directory used for path resolution in the markdown.
/// * base_url - Base url that the site will be served from.
///
/// # Returns
/// * A Result<String> containing the converted HTML text or an error if the conversion fails.
fn markdown_to_html(
    markdown_input: &str,
    content_dir: &Path,
    base_url: Option<&str>,
) -> Result<String> {
    let parser = pulldown_cmark::Parser::new_ext(markdown_input, Options::all());
    let mut events: Vec<Event> = Vec::new();

    let content_dir_name = content_dir
        .file_name()
        .unwrap_or_default()
        .to_str()
        .unwrap_or("");

    let content_dir_with_slash = format!("/{}", content_dir_name);

    for event in parser {
        match event {
            Event::Start(Tag::Link {
                link_type,
                dest_url,
                title,
                id,
            }) => {
                let mut new_dest = dest_url.to_string();

                if dest_url.starts_with(&content_dir_with_slash)
                    || dest_url.starts_with(content_dir_name)
                {
                    let stripped_url = dest_url
                        .strip_prefix(&content_dir_with_slash)
                        .or_else(|| dest_url.strip_prefix(content_dir_name))
                        .unwrap_or(&dest_url);

                    new_dest = if let Some(base) = base_url {
                        format!(
                            "/{}/{}",
                            base.trim_start_matches("/").trim_end_matches("/"),
                            stripped_url.trim_start_matches("/")
                        )
                        .to_string()
                    } else {
                        stripped_url.to_string()
                    }
                }

                if new_dest.ends_with(".md") {
                    new_dest = new_dest
                        .trim_end_matches("index.md")
                        .replace(".md", ".html");
                }

                // Push the modified or original link event
                events.push(Event::Start(Tag::Link {
                    link_type,
                    dest_url: CowStr::Boxed(new_dest.into_boxed_str()),
                    title,
                    id,
                }));
            }
            _ => events.push(event),
        }
    }

    let mut html_output = String::new();
    push_html(&mut html_output, events.into_iter());
    Ok(html_output)
}

/// Generates the sitemap.xml file with the given entries.
///
/// # Arguments
/// * `output_path` - Path to the output directory.
/// * `entries` - List of relative paths to be included in the sitemap.
///
/// # Returns
/// * A `Result<()>` indicating the success or failure of the operation.
fn generate_sitemap(output_path: &Path, entries: &[String]) -> Result<()> {
    let sitemap_path = output_path.join("sitemap.xml");
    let mut file = File::create(&sitemap_path)?;

    writeln!(file, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>")?;
    writeln!(
        file,
        "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"
    )?;

    for entry in entries {
        let url = format!("<url><loc>{}</loc></url>", entry);
        writeln!(file, "{}", url)?;
    }

    writeln!(file, "</urlset>")?;
    Ok(())
}