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
//! Exports the [`build_site`] function which stitches together the high-level
//! steps of building the output static site: parsing the posts
//! ([`crate::post`]), rendering index and post pages ([`crate::write`]), and
//! copying the static source directory into the static output directory.

use crate::config::Config;
use crate::post::{Error as ParseError, Parser as PostParser};
use crate::write::{Error as WriteError, *};
use gtmpl::Template;
use std::fmt;
use std::path::{Path, PathBuf};

/// Builds the site from a [`Config`] object. This calls into
/// [`PostParser::parse_posts`] and [`Writer::write_posts`] which do the
/// heavy-lifting. This function also copies the static assets from source
/// directory to the output directory.
pub fn build_site(config: &Config) -> Result<()> {
    fn rmdir(dir: &Path) -> Result<()> {
        match std::fs::remove_dir_all(dir) {
            Ok(x) => Ok(x),
            Err(e) => match e.kind() {
                std::io::ErrorKind::NotFound => Ok(()),
                _ => Err(Error::Clean {
                    path: dir.to_owned(),
                    err: e,
                }),
            },
        }
    }

    let post_parser = PostParser::new(
        &config.index_url,
        &config.posts_url,
        &config.posts_output_directory,
    );

    // collect all posts
    let posts = post_parser.parse_posts(&config.posts_source_directory)?;

    // Parse the template files.
    let index_template = parse_template(config.index_template.iter())?;
    let posts_template = parse_template(config.posts_template.iter())?;

    // Blow away the old output directories (if they exists) so we don't have any collisions
    rmdir(&config.index_output_directory)?;
    rmdir(&config.posts_output_directory)?;
    rmdir(&config.static_output_directory)?;

    let writer = Writer {
        posts_template: &posts_template,
        index_template: &index_template,
        index_page_size: config.index_page_size,
        index_base_url: &config.index_url,
        index_output_directory: &config.index_output_directory,
        home_page: &config.home_page,
        static_url: &config.static_url,
    };
    writer.write_posts(&posts)?;

    // copy static directory
    copy_dir(
        &config.static_source_directory,
        &config.static_output_directory,
    )
}

fn copy_dir(src: &Path, dst: &Path) -> Result<()> {
    std::fs::create_dir(dst)?;
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        if entry.file_type()?.is_dir() {
            copy_dir(src, &dst.join(entry.file_name()))?;
        } else {
            std::fs::copy(src.join(entry.file_name()), dst.join(entry.file_name()))?;
        }
    }

    Ok(())
}

// Loads the template file contents, appends them to `base_template`, and
// parses the result into a template.
fn parse_template<P: AsRef<Path>>(template_files: impl Iterator<Item = P>) -> Result<Template> {
    let mut contents = String::new();
    for template_file in template_files {
        use std::fs::File;
        use std::io::Read;
        let template_file = template_file.as_ref();
        File::open(&template_file)
            .map_err(|e| Error::OpenTemplateFile {
                path: template_file.to_owned(),
                err: e,
            })?
            .read_to_string(&mut contents)?;
        contents.push(' ');
    }

    let mut template = Template::default();
    template.parse(&contents).map_err(Error::ParseTemplate)?;
    Ok(template)
}

type Result<T> = std::result::Result<T, Error>;

/// The error type for building a site. Errors can be during parsing, writing,
/// cleaning output directories, parsing template files, and other I/O.
#[derive(Debug)]
pub enum Error {
    /// Returned for errors during parsing.
    Parse(ParseError),

    /// Returned for errors writing [`crate::post::Post`]s to disk as HTML files.
    Write(WriteError),

    /// Returned for I/O problems while cleaning output directories.
    Clean { path: PathBuf, err: std::io::Error },

    /// Returned for I/O problems while opening template files.
    OpenTemplateFile { path: PathBuf, err: std::io::Error },

    /// Returned for errors parsing template files.
    ParseTemplate(String),

    /// Returned for other I/O errors.
    Io(std::io::Error),
}

impl fmt::Display for Error {
    /// Implements [`fmt::Display`] for [`Error`].
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::Parse(err) => err.fmt(f),
            Error::Write(err) => err.fmt(f),
            Error::Clean { path, err } => {
                write!(f, "Cleaning directory '{}': {}", path.display(), err)
            }
            Error::OpenTemplateFile { path, err } => {
                write!(f, "Opening template file '{}': {}", path.display(), err)
            }
            Error::ParseTemplate(err) => err.fmt(f),
            Error::Io(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for Error {
    /// Implements [`std::error::Error`] for [`Error`].
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Parse(err) => Some(err),
            Error::Write(err) => Some(err),
            Error::Clean { path: _, err } => Some(err),
            Error::OpenTemplateFile { path: _, err } => Some(err),
            Error::ParseTemplate(_) => None,
            Error::Io(err) => Some(err),
        }
    }
}

impl From<std::io::Error> for Error {
    /// Converts [`std::io::Error`]s into [`Error`]. This allows us to use the
    /// `?` operator.
    fn from(err: std::io::Error) -> Error {
        Error::Io(err)
    }
}

impl From<ParseError> for Error {
    /// Converts [`ParseError`]s into [`Error`]. This allows us to use the `?`
    /// operator.
    fn from(err: ParseError) -> Error {
        Error::Parse(err)
    }
}

impl From<WriteError> for Error {
    /// Converts [`WriteError`]s into [`Error`]. This allows us to use the `?`
    /// operator.
    fn from(err: WriteError) -> Error {
        Error::Write(err)
    }
}