aboutsummaryrefslogtreecommitdiff
path: root/src/templates.rs
blob: 84a00072b9a63d551418bb173087779f32843753 (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
use askama::Template;

use crate::state::State;

#[derive(Template)]
#[template(path = "index.html")]
pub struct Index<'a> {
    pub state: &'a State,
}

#[derive(Template)]
#[template(path = "repo_folder.html")]
pub struct RepoFolder<'a> {
    pub repo: &'a git2::Repository,
    pub repo_path: &'a str,
    pub title: &'a str,
    pub rel_path: &'a str,
    pub tree: git2::Tree<'a>,
}

#[derive(Template)]
#[template(path = "repo_file.html")]
pub struct RepoFile<'a> {
    pub repo_path: &'a str,
    pub title: &'a str,
    pub rel_path: &'a str,
    pub blob: git2::Blob<'a>,
}

mod filters {
    use askama::Result;

    pub fn from_utf8_lossy(utf8: &[u8]) -> Result<String> {
        Ok(String::from_utf8_lossy(utf8).into_owned())
    }

    pub fn markdown(s: &str) -> Result<String> {
        use pulldown_cmark::{Parser, Options, html};

        let mut options = Options::empty();
        options.insert(Options::ENABLE_STRIKETHROUGH);
        options.insert(Options::ENABLE_SMART_PUNCTUATION);
        let parser = Parser::new_ext(s, options);

        let mut result = String::new();
        html::push_html(&mut result, parser);

        Ok(result)
    }

    pub fn highlight(s: &str, file_rel_path: &str) -> Result<String> {
        use std::path::Path;
        use syntect::{parsing::SyntaxSet, highlighting::ThemeSet, html::highlighted_html_for_string};

        let syntax_set = SyntaxSet::load_defaults_newlines();
        let extension = Path::new(file_rel_path).extension();
        let themes = ThemeSet::load_defaults();
        // TODO something idk
        let theme = &themes.themes["base16-ocean.dark"];
        let syntax = extension
            .and_then(|extension| extension.to_str())
            .and_then(|extension| syntax_set.find_syntax_by_extension(extension))
            .unwrap_or_else(|| syntax_set.find_syntax_plain_text());
        let result = highlighted_html_for_string(
            s,
            &syntax_set,
            syntax,
            theme,
        );

        Ok(result)
    }
}