summaryrefslogtreecommitdiff
path: root/src/page.rs
blob: 2ee065a5b32518d9534934d3da91cd07bf09a397 (plain)
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
use serde::Deserialize;
use chrono::NaiveDate;
use std::path::PathBuf;
use std::fs;

#[derive(Deserialize, Debug)]
pub struct Frontmatter {
    pub title: String,
    pub date: NaiveDate,
    #[serde(default)]
    pub draft: bool,
}

#[derive(Debug)]
pub struct Page {
    pub meta: Frontmatter,
    pub source_path: PathBuf,
    pub output_path: PathBuf,
    pub body: String,
    pub html: String,
}

pub fn parse_frontmatter(content: &str) -> Option<Frontmatter> {
    if !content.starts_with("+++\n") {
        return None;
    }
    let rest = &content[4..];
    let end = rest.find("\n+++\n")?;

    let toml_str = &rest[..end];
    let meta: Frontmatter = toml::from_str(toml_str)
        .expect("frontmatter failed parsed");
    Some(meta)
} 

pub fn parse_page(source_path: &PathBuf) -> anyhow::Result<Page> {
    let content = fs::read_to_string(source_path)?;
    let maybe_meta = parse_frontmatter(&content);
    let meta: Frontmatter;
    let body: String;

    if let Some(fm) = maybe_meta {
        let end_post = content.find("\n+++\n").unwrap();
        println!("end_post: {}", end_post);
        meta = fm;
        body = content[(end_post + 5)..].to_string();
    } else {
        let fallback_title = source_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("untitled")
            .to_string();

        meta = Frontmatter {
            title: fallback_title,
            date: chrono::Utc::now().date_naive(),
            draft: true,
        };
        body = content;
    }

    let html = render_markdown(&body);

    let slug = meta.title.to_lowercase().replace(' ', "-");
    let output_path = PathBuf::from("public").join(&slug).join("index.html");
    save_file(&output_path, &html)?;
    Ok (Page {
        meta,
        source_path: source_path.clone(),
        output_path,
        body,
        html,
    })
}

pub fn render_markdown(input: &str) -> String {
    use pulldown_cmark::{Parser, Options, html};

    let mut options = Options::empty();
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TABLES);

    let parser = Parser::new_ext(input, options);
    let mut out = String::new();
    html::push_html(&mut out, parser);
    out
}

pub fn save_file(output_path: &PathBuf, content: &str) -> anyhow::Result<()> {
    if let Some(public) = output_path.parent() {
        fs::create_dir_all(public)?;
    }
    fs::write(output_path, content)?;
    Ok(())
}