aboutsummaryrefslogtreecommitdiff
path: root/code/src/main.rs
blob: 09ce3d8581b34bb4867aac91f4b1f43924935b67 (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
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
use std::{
    fs::{read_to_string, File},
    io::{BufRead, BufReader, Write},
    path::PathBuf,
};

use clap::{Parser, Subcommand};
use laby::{html, internal::Buffer, iter, li, raw, ul, Render};
use markdown::{Block, Span};

#[derive(Parser)]
struct Args {
    #[clap(short, long)]
    output: Option<String>,
    #[clap(subcommand)]
    action: ArgAction,
}

#[derive(Subcommand)]
enum ArgAction {
    RenderArticle { input: String },
    RenderIndex { root: String },
}

fn main() {
    let args = Args::parse();
    match args.action {
        ArgAction::RenderArticle { input } => {
            let md_source = read_to_string(input).unwrap();
            let mut out = Buffer::new();
            article(md_source).render(&mut out);
            write_output(&args.output, out.into_string());
        }
        ArgAction::RenderIndex { root } => {
            let mut out = Buffer::new();
            index(root).render(&mut out);
            write_output(&args.output, out.into_string());
        }
    }
}

fn write_output(t: &Option<String>, o: String) {
    if let Some(f) = t {
        let mut f = File::create(f).unwrap();
        f.write_fmt(format_args!("{o}")).unwrap()
    } else {
        println!("{o}")
    }
}

fn scaffold(title: String, body: impl Render) -> impl Render {
    html!(
        head!(title!(title)),
        body!(
            nav!(h2!("metamuffin's blog"), a!(href = "./index.html", "index")),
            article!(body)
        )
    )
}

fn index(root: String) -> impl Render {
    scaffold(
        "index".to_string(),
        ul!(iter!(std::fs::read_dir(root)
            .unwrap()
            .map(|e| e.unwrap())
            .map(|e| (
                e.file_name().to_str().unwrap().to_string(),
                article_title(e.path())
            ))
            .map(|(path, title)| li!(
                path.as_str()[0..10].to_string(),
                ": ",
                a!(href = format!("./{}", path.replace(".md", ".html")), title)
            )))),
    )
}

fn article_title(path: PathBuf) -> String {
    let f = File::open(path).unwrap();
    let mut f = BufReader::new(f);
    let mut buf = String::new();
    f.read_line(&mut buf).unwrap(); // assume the 1st line has the title
    String::from(&buf[2..])
}

fn article(md_source: String) -> impl Render {
    scaffold(
        "blub".to_string(),
        raw!(blocks_to_html(markdown::tokenize(&md_source))),
    )
}

fn span_to_html(ss: Vec<Span>) -> String {
    let mut out = String::new();
    for s in ss {
        out += match s {
            Span::Break => format!("<br/>"),
            Span::Text(t) => escape(&t),
            Span::Code(c) => format!("<pre><code>{}</code></pre>", escape(&c)),
            Span::Link(text, url, _) => {
                format!("<a href=\"{}\">{}</a>", escape(&url), escape(&text))
            }
            Span::Image(_, _, _) => todo!(),
            Span::Emphasis(c) => format!("<i>{}</i>", span_to_html(c)),
            Span::Strong(c) => format!("<b>{}</b>", span_to_html(c)),
        }
        .as_str()
    }
    out
}
fn blocks_to_html(blocks: Vec<Block>) -> String {
    let mut out = String::new();
    for e in blocks {
        out += match e {
            markdown::Block::Header(text, level) => {
                format!("<h{level}>{}</h{level}>", span_to_html(text))
            }
            markdown::Block::Paragraph(p) => format!("<p>{}</p>", span_to_html(p)),
            markdown::Block::Blockquote(q) => format!("<quote>{}</quote>", blocks_to_html(q)),
            markdown::Block::CodeBlock(_syntax, content) => {
                format!("<pre><code>{}</code></pre>", escape(&content)) // TODO syntax highlighting
            }
            markdown::Block::OrderedList(_, _) => todo!(),
            markdown::Block::UnorderedList(_) => todo!(),
            markdown::Block::Raw(r) => r,
            markdown::Block::Hr => format!("<hr/>"),
        }
        .as_str();
    }
    out
}

fn escape(text: &str) -> String {
    text.replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace("'", "&#8217;")
        .replace("\"", "&quot;")
}