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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
/*
    This file is part of Dokkoo.

    Dokkoo is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Dokkoo is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Dokkoo.  If not, see <https://www.gnu.org/licenses/>.
*/
/*
lib.rs - Handling Mokk Files (.mokkf)
File:
    Term for a document or page written in accordance to the Mokk specification
*/
use anyhow::Context;
use chrono::DateTime;
use liquid::*;
use pulldown_cmark::{html, Options, Parser};
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::fs;
use std::path::Path;
use std::{collections::HashMap, fmt};

#[derive(Clone, Debug, Serialize, Deserialize)]
/// A File's date-time metadata
pub struct Date {
    /// Year with four digits
    pub year: String,
    /// Year without the century (00..99)
    pub short_year: String,
    /// Month (01..12)
    pub month: String,
    /// Month without leading zeros
    pub i_month: String,
    /// Three-letter month abbreviation, e.g. “Jan”
    pub short_month: String,
    /// Full month name, e.g. “January”
    pub long_month: String,
    /// Day of the month (01..31)
    pub day: String,
    /// Day of the month without leading zeros
    pub i_day: String,
    /// Ordinal day of the year, with leading zeros. (001..366)
    pub y_day: String,
    /// Week year which may differ from the month year for up to three days at the start of January and end of December
    pub w_year: String,
    /// Week number of the current year, starting with the first week having a majority of its days in January (01..53)
    pub week: String,
    /// Day of the week, starting with Monday (1..7)
    pub w_day: String,
    /// Three-letter weekday abbreviation, e.g. “Sun”
    pub short_day: String,
    /// Weekday name, e.g. “Sunday”
    pub long_day: String,
    /// Hour of the day, 24-hour clock, zero-padded (00..23)
    pub hour: String,
    /// Minute of the hour (00..59)
    pub minute: String,
    /// Second of the minute (00..59)
    pub second: String,
    /// A File's date-time metadata, formatted per the RFC 3339 standard
    pub rfc_3339: String,
    /// A File's date-time metadata, formatted per the RFC 2822 standard
    pub rfc_2822: String,
}

/// Handle conversion of a Date object into a string of characters
impl fmt::Display for Date {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.rfc_3339)
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
/// Generated data regarding a Mokk File
pub struct Page {
    /// A File's contextual data, represented as YAML at the head/front of the file
    pub data: HashMap<String, serde_yaml::Value>,
    /// A File's contents following the frontmatter
    pub content: String,
    /// Data representing the output path of a File.
    /// This is defined in a File's frontmatter
    pub permalink: String,
    /// A File's date-time metadata, formatted per the RFC 3339 standard.
    /// This is defined in a File's frontmatter
    pub date: Date,
    /// Path to the File, not including the File itself
    pub directory: String,
    /// The File's base filename
    pub name: String,
    /// The output path of a file; a processed `permalink` value
    pub url: String,
    /// Whether a File is intended to be marked-up in Markdown (intended for when a different markup language [HTML, XML, et cetera], or none at all, is more appropriate)
    pub markdown: bool,
}

/// Returns an expanded permalink value, for when shorthand is used
///
/// # Arguments
///
/// * `permalink` - A string slice that represents the permalink value specified in the File
///
/// # Shorthand
///
/// * `date` → `/{{ page.data.collection }}/{{ page.date.year }}/{{ page.date.month }}/{{ page.date.day }}/{{ page.data.title }}.html`
///
/// * `pretty` → `/{{ page.data.collection }}/{{ page.date.year }}/{{ page.date.month }}/{{ page.date.day }}/{{ page.data.title }}.html`
///
/// * `ordinal` → `/{{ page.data.collection }}/{{ page.date.year }}/{{ page.date.y_day }}/{{ page.data.title }}.html`
///
/// * `weekdate` → `/{{ page.data.collection }}/{{ page.date.year }}/W{{ page.date.week }}/{{ page.date.short_day }}/{{ page.data.title }}.html`
///
/// * `none` → `/{{ page.data.collection }}/{{ page.data.title }}.html`
#[inline(always)]
pub fn get_permalink(permalink: &str) -> String {
    match &*permalink {
        "date" => {
            "/{{ page.data.collection }}/{{ page.date.year }}/{{ page.date.month }}/{{ page.date.day }}/{{ page.data.title }}.html".to_owned()
        }
        "pretty" => {
            "/{{ page.data.collection }}/{{ page.date.year }}/{{ page.date.month }}/{{ page.date.day }}/{{ page.data.title }}.html".to_owned()
        }
        "ordinal" => {
            "/{{ page.data.collection }}/{{ page.date.year }}/{{ page.date.y_day }}/{{ page.data.title }}.html"
                .to_owned()
        }
        "weekdate" => {
            "/{{ page.data.collection }}/{{ page.date.year }}/W{{ page.date.week }}/{{ page.date.short_day }}/{{ page.data.title }}.html".to_owned()
        }
        "none" => {
            "/{{ page.data.collection }}/{{ page.data.title }}.html".to_owned()
        }
        _ => {
            permalink.to_string()
        }
    }
}

/// Returns a tuple with a File's frontmatter and contents, in that order
///
/// # Arguments
///
/// * `page_text` - The `.mokkf` file's data as a `String`
#[inline(always)]
pub fn split_frontmatter(page_text: String) -> (String, String) {
    let mut begin = false;
    let mut end = false;
    let mut frontmatter = String::new();
    let mut contents = String::new();

    for line in page_text.lines() {
        if !begin && line == "---" {
            begin = true;
        } else if begin && line == "---" && !end {
            end = true;
        } else if begin && !end {
            frontmatter.push_str(&format!("{}\n", &line));
        } else {
            contents.push_str(&format!("{}\n", &line));
        }
    }

    if frontmatter.trim().is_empty() {
        frontmatter = "empty: true".to_owned();
    }

    (frontmatter, contents)
}

/// Returns an object with a Page's context
///
/// # Arguments
///
/// * `page_path` - The `.mokkf` file's path as a `String`
///
/// * `conditions` - Prints conditions information
#[inline(always)]
pub fn get_page_object(page_path: String, collections: &HashMap<String, Vec<Page>>) -> Page {
    // Define variables which we'll use to create our Document, which we'll use to generate the Page context
    let split_page = split_frontmatter(fs::read_to_string(&page_path).unwrap()); // See file::split_frontmatter
    let frontmatter: HashMap<String, serde_yaml::Value> =
        serde_yaml::from_str(&split_page.0).unwrap(); // Parse frontmatter as HashMap (collection of key-value pairs)
    let permalink = frontmatter.get("permalink"); // Get the key-value pair of the 'permalink' key from the frontmatter
    let date = frontmatter.get("date"); // Get the key-value pair of the 'date' key from the frontmatter
    let markdown = frontmatter.get("markdown"); // Get the key-value pair of the 'markdown' key from the frontmatter

    let permalink_string: String;
    let markdown_bool: bool;

    match permalink {
        Some(_) => {
            permalink_string = permalink.unwrap().as_str().unwrap().to_string();
        }
        None => {
            permalink_string = String::new();
        }
    }

    match markdown {
        Some(_) => {
            markdown_bool = markdown.unwrap().as_bool().unwrap();
        }
        None => {
            markdown_bool = true;
        }
    }

    let date_object;
    match date {
        Some(_) => {
            let datetime = DateTime::parse_from_rfc3339(date.unwrap().as_str().unwrap()); // Turn the date-time into a DateTime object for easy manipulation (to generate temporal Page metadata)
            let global_file = fs::read_to_string("./_global.yml");
            let global: HashMap<String, serde_yaml::Value>;

            match global_file {
                Ok(_) => {
                    global = serde_yaml::from_str(&global_file.unwrap()).unwrap();
                    // Defined as variable as it required a type annotation
                }
                Err(_) => {
                    global = serde_yaml::from_str("locale: \"en_US\"").unwrap();
                    // Defined as variable as it required a type annotation
                }
            }

            let locale_key = global.get("locale");
            let locale_value;

            match locale_key {
                Some(_) => {
                    locale_value = locale_key.unwrap().as_str().unwrap();
                }
                None => {
                    locale_value = "en_US";
                }
            }

            let locale: chrono::Locale = chrono::Locale::try_from(locale_value).unwrap(); // Get locale from Global context

            date_object = Date {
                year: format!("{}", datetime.unwrap().format_localized("%Y", locale)),
                short_year: format!("{}", datetime.unwrap().format_localized("%y", locale)),
                month: format!("{}", datetime.unwrap().format_localized("%m", locale)),
                i_month: format!("{}", datetime.unwrap().format_localized("%-m", locale)),
                short_month: format!("{}", datetime.unwrap().format_localized("%b", locale)),
                long_month: format!("{}", datetime.unwrap().format_localized("%B", locale)),
                day: format!("{}", datetime.unwrap().format_localized("%d", locale)),
                i_day: format!("{}", datetime.unwrap().format_localized("%-d", locale)),
                y_day: format!("{}", datetime.unwrap().format_localized("%j", locale)),
                w_year: format!("{}", datetime.unwrap().format_localized("%G", locale)),
                week: format!("{}", datetime.unwrap().format_localized("%U", locale)),
                w_day: format!("{}", datetime.unwrap().format_localized("%u", locale)),
                short_day: format!("{}", datetime.unwrap().format_localized("%a", locale)),
                long_day: format!("{}", datetime.unwrap().format_localized("%A", locale)),
                hour: format!("{}", datetime.unwrap().format_localized("%H", locale)),
                minute: format!("{}", datetime.unwrap().format_localized("%M", locale)),
                second: format!("{}", datetime.unwrap().format_localized("%S", locale)),
                rfc_3339: datetime.unwrap().to_rfc3339(),
                rfc_2822: datetime.unwrap().to_rfc2822(),
            }
        }
        None => {
            date_object = Date {
                year: String::new(),
                short_year: String::new(),
                month: String::new(),
                i_month: String::new(),
                short_month: String::new(),
                long_month: String::new(),
                day: String::new(),
                i_day: String::new(),
                y_day: String::new(),
                w_year: String::new(),
                week: String::new(),
                w_day: String::new(),
                short_day: String::new(),
                long_day: String::new(),
                hour: String::new(),
                minute: String::new(),
                second: String::new(),
                rfc_3339: String::new(),
                rfc_2822: String::new(),
            }
        }
    }

    let page_path_io = Path::new(&page_path[..]); // Turn the path into a Path object for easy manipulation (to get page.directory and page.name)

    // Define our Page
    let mut page = Page {
        data: serde_yaml::from_str(&split_page.0).unwrap(),
        content: split_page.1,
        permalink: permalink_string,
        date: date_object,
        directory: page_path_io.parent().unwrap().to_str().unwrap().to_owned(),
        name: page_path_io
            .file_stem()
            .unwrap()
            .to_str()
            .unwrap()
            .to_owned(),
        url: String::new(),
        markdown: markdown_bool,
    };

    match &page.permalink[..] {
        "" => {}
        _ => {
            // Render the URL once the Page metadata has been generated
            page.url = render(
                &page,
                &get_permalink(permalink.unwrap().as_str().unwrap()),
                true,
                collections,
            );
        }
    }

    page
}

/// Returns a Liquid object with a Page's Liquid contexts
///
/// # Arguments
///
/// * `page` - The `.mokkf` file's context as a Page
///
/// * `conditions` - Prints conditions information
#[inline(always)]
pub fn get_contexts(page: &Page, collections: &HashMap<String, Vec<Page>>) -> Object {
    let global_file = fs::read_to_string("./_global.yml");
    let global: HashMap<String, serde_yaml::Value>;
    match global_file {
        Ok(_) => {
            global = serde_yaml::from_str(&global_file.unwrap()).unwrap(); // Defined as variable as it required a type annotation
        }
        Err(_) => {
            global = serde_yaml::from_str("locale: \"en_US\"").unwrap(); // Defined as variable as it required a type annotation
        }
    }

    /*
    Layouts
    */
    let layout_name = page.data.get("layout");
    let layout: HashMap<String, serde_yaml::Value>;

    // Import layout context if Page has a layout
    match layout_name {
        None => {
            layout = HashMap::new();
        }
        Some(_) => {
            layout = serde_yaml::from_str(
                &split_frontmatter(
                    fs::read_to_string(format!(
                        "./layouts/{}.mokkf",
                        layout_name.unwrap().as_str().unwrap().to_string()
                    ))
                    .unwrap(),
                )
                .0,
            )
            .unwrap();
        }
    }

    let contexts = object!({
        "global": global,
        "page": page,
        "layout": layout,
        "collections": collections,
    });

    contexts
}

/// Returns a String with a &str's File rendered
///
/// # Arguments
///
/// * `page` - A `.mokkf` file's context as a Page
///
/// * `text_to_render` - The text to be rendered
///
/// * `only_context` - Whether or not to only render the contexts of a File
///
/// * `collections` - Collection store of this build
#[inline(always)]
pub fn render(
    page: &Page,
    text_to_render: &str,
    only_context: bool,
    collections: &HashMap<String, Vec<Page>>,
) -> String {
    match only_context {
        true => {
            let template = create_liquid_parser()
                .parse(text_to_render)
                .with_context(|| {
                    format!(
                        "Could not parse the Mokk file at {}/{}.mokkf",
                        page.directory, page.name
                    )
                })
                .unwrap();
            template
                .render(&get_contexts(page, collections))
                .with_context(|| {
                    format!(
                        "Could not render the Mokk file at {}/{}.mokkf",
                        page.directory, page.name
                    )
                })
                .unwrap()
        }
        false => {
            let template = create_liquid_parser()
                .parse(text_to_render)
                .with_context(|| {
                    format!(
                        "Could not parse the Mokk file at {}/{}.mokkf",
                        page.directory, page.name
                    )
                })
                .unwrap();
            let liquid_render = template
                .render(&get_contexts(page, collections))
                .with_context(|| {
                    format!(
                        "Could not render the Mokk file at {}/{}.mokkf",
                        page.directory, page.name
                    )
                })
                .unwrap();
            render_markdown(liquid_render)
        }
    }
}

/// Compiles a Mokk File; renders, makes note of the File (when, or if, the need arises)
///
/// # Arguments
///
/// * `page` - The `.mokkf` file's context as a Page
///
/// * `collections` - Collection store of this build
#[inline(always)]
pub fn compile(
    mut page: Page,
    mut collections: HashMap<String, Vec<Page>>,
) -> (String, HashMap<String, Vec<Page>>) {
    let compiled_page;
    let layout_name = &page.data.get("layout");
    let collection_name = &page.data.get("collection");

    // If Page has a layout, render with layout(s)
    // Otherwise, render with Page's contents
    page.content = render(&page, &page.content, !page.markdown, &collections);
    match layout_name {
        None => {
            compiled_page = page.content.to_owned();
        }
        Some(_) => {
            let layout_object = get_page_object(
                format!(
                    "./layouts/{}.mokkf",
                    layout_name.unwrap().as_str().unwrap().to_string()
                ),
                &collections,
            );
            let layouts = render_layouts(&page, layout_object, &collections); // Embed page in layout
            compiled_page = render(&page, &layouts, true, &collections);
            // Final render, to capture whatever layouts & snippets introduce
        }
    }

    // When within a collection, append embeddable page to list of collection's entries
    match collection_name {
        None => {}
        Some(_) => {
            let collection_name_str = collection_name.unwrap().as_str().unwrap();
            match collections.contains_key(&collection_name_str.to_string()) {
                true => {
                    (*collections.get_mut(collection_name_str).unwrap()).push(page);
                }
                false => {
                    collections.insert(collection_name_str.to_owned(), vec![page]);
                }
            }
        }
    }

    (compiled_page, collections)
}

/// Render the layout(s) of a post recursively (should a layout have a layout of its own)
///
/// # Arguments
///
/// * `page` - The `.mokkf` file's context as a Page
///
/// * `layout` - The File's layout's context as a Page
///
/// * `collections` - Collection store of this build
#[inline(always)]
pub fn render_layouts(
    sub: &Page,
    layout: Page,
    collections: &HashMap<String, Vec<Page>>,
) -> String {
    // Take layout's text, render it with sub's context
    let rendered: String;

    let super_layout = layout.data.get("layout");
    match super_layout {
        Some(_) => {
            let super_layout_object = get_page_object(
                format!(
                    "./layouts/{}.mokkf",
                    super_layout.unwrap().as_str().unwrap().to_string()
                ),
                collections,
            );
            rendered = render_layouts(&layout, super_layout_object, collections);
        }
        None => {
            rendered = render(&sub, &layout.content, !layout.markdown, collections);
        }
    }

    rendered
}

/// Creates a Liquid parser
pub fn create_liquid_parser() -> liquid::Parser {
    let mut partial = liquid::partials::InMemorySource::new();
    let snippets = fs::read_dir("./snippets");
    if snippets.is_ok() {
        for snippet in snippets.unwrap() {
            let unwrapped_snippet = snippet.unwrap();
            let file_name = &unwrapped_snippet.file_name().into_string().unwrap();
            let path = &unwrapped_snippet.path();
            partial.add(file_name, &fs::read_to_string(path).unwrap());
        }
    }
    let partial_compiler = liquid::partials::EagerCompiler::new(partial);
    liquid::ParserBuilder::with_stdlib()
        .tag(liquid_lib::jekyll::IncludeTag)
        .filter(liquid_lib::jekyll::ArrayToSentenceString)
        .filter(liquid_lib::jekyll::Pop)
        .filter(liquid_lib::jekyll::Push)
        .filter(liquid_lib::jekyll::Shift)
        .filter(liquid_lib::jekyll::Slugify)
        .filter(liquid_lib::jekyll::Unshift)
        .filter(liquid_lib::shopify::Pluralize)
        .filter(liquid_lib::extra::DateInTz)
        .partials(partial_compiler)
        .build()
        .unwrap()
}

/// Render Markdown as HTML
///
/// # Arguments
///
/// * `text_to_render` - The Markdown text to render into HTML
#[inline(always)]
pub fn render_markdown(text_to_render: String) -> String {
    let mut markdown_options = Options::empty();
    markdown_options.insert(Options::ENABLE_TABLES);
    markdown_options.insert(Options::ENABLE_FOOTNOTES);
    markdown_options.insert(Options::ENABLE_STRIKETHROUGH);
    markdown_options.insert(Options::ENABLE_TASKLISTS);
    markdown_options.insert(Options::ENABLE_SMART_PUNCTUATION);
    let markdown_parser = Parser::new_ext(&text_to_render, markdown_options);
    let mut rendered_markdown = String::new();
    html::push_html(&mut rendered_markdown, markdown_parser);

    rendered_markdown
}