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
//! Markdown rendering.
//!
//! Currently, just uses the `pulldown_cmark` in the simplest of ways.

use std::fs;
use std::io;
use std::path::PathBuf;
use pulldown_cmark::{Parser, html};

/// Encapsulates a markdown file and provides an interface to turn its contents into HTML.
///
pub struct Renderer {
    /// A short, user-friendly path to show in UI.
    pub display_md_path: PathBuf,

    /// The canonicalized path to use in file operations.
    pub canonical_md_path: PathBuf,
}

impl Renderer {
    /// Create a new renderer instance that wraps the given markdown file.
    ///
    pub fn new(md_path: PathBuf) -> Self {
        let canonical_md_path = md_path.canonicalize().
            unwrap_or_else(|_| md_path.clone());
        let display_md_path = md_path;

        Renderer { display_md_path, canonical_md_path }
    }

    /// Turn the current contents of the markdown file into HTML.
    ///
    pub fn run(&self) -> Result<String, io::Error> {
        let markdown = fs::read_to_string(&self.canonical_md_path)?;

        let parser = Parser::new(&markdown);
        let mut output = String::new();
        html::push_html(&mut output, parser);
        Ok(output)
    }
}