yar_site 0.6.0

Library for creating and working with static sites for yar.
Documentation
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
use std::path::{Path, PathBuf};

use chrono::{DateTime, Utc};
use color_eyre::{Result, eyre::ContextCompat};
use rusqlite::Connection;
use url::Url;
use yar_markdown::{Document, Frontmatter};

use crate::{
    asset::Asset,
    page::Page,
    static_file::StaticFile,
    templates::template_page::{Pagination, TPFrontmatter, TemplatePage},
};

#[derive(Debug)]
pub enum DatabaseSource<'a> {
    Memory,
    File(&'a Path),
}

#[allow(clippy::too_many_lines)]
#[allow(clippy::needless_pass_by_value)]
/// Set up sqlite database.
/// Create initial tables if they don't exist and acquire the connection.
pub fn setup_sql(source: DatabaseSource) -> Result<Connection> {
    let conn = match source {
        DatabaseSource::File(p) => Connection::open(p),
        DatabaseSource::Memory => Connection::open_in_memory(),
    }?;

    conn.execute(
        "
        CREATE TABLE IF NOT EXISTS entries (
            path VARCHAR NOT NULL PRIMARY KEY,
            hash TEXT NOT NULL
        )
    ",
        (),
    )?;

    conn.execute(
        "
        CREATE TABLE IF NOT EXISTS pages (
            out_path VARCHAR NOT NULL PRIMARY KEY,
            permalink TEXT NOT NULL,
            date TEXT NOT NULL,
            updated TEXT NOT NULL,
            content TEXT NOT NULL,
            toc JSON NOT NULL,
            summary TEXT NOT NULL,
            title TEXT NOT NULL,
            tags JSON NOT NULL,
            template TEXT,
            slug TEXT,
            draft BOOLEAN NOT NULL,
            requires JSON NOT NULL,
            entry VARCHAR NOT NULL,
            FOREIGN KEY(entry) REFERENCES entries(path)
        )
    ",
        (),
    )?;

    conn.execute(
        "
        CREATE TABLE IF NOT EXISTS assets (
            out_path VARCHAR NOT NULL PRIMARY KEY,
            permalink TEXT NOT NULL,
            content TEXT NOT NULL,
            entry VARCHAR NOT NULL,
            FOREIGN KEY(entry) REFERENCES entries(path)
        )
    ",
        (),
    )?;

    conn.execute(
        "
        CREATE TABLE IF NOT EXISTS static_files (
            out_path VARCHAR NOT NULL PRIMARY KEY,
            permalink TEXT NOT NULL,
            content BLOB NOT NULL,
            entry VARCHAR NOT NULL,
            FOREIGN KEY(entry) REFERENCES entries(path)
        )
    ",
        (),
    )?;

    conn.execute(
        "
        CREATE TABLE IF NOT EXISTS template_pages (
            out_path VARCHAR NOT NULL PRIMARY KEY,
            permalink TEXT NOT NULL,
            content BLOB NOT NULL,
            title TEXT NOT NULL,
            date TEXT NOT NULL,
            updated TEXT NOT NULL,
            slug TEXT,
            draft BOOLEAN NOT NULL,
            dependencies JSON NOT NULL,
            pagination_from TEXT,
            pagination_every INTEGER,
            pagination_name_template TEXT,
            entry VARCHAR NOT NULL,
            FOREIGN KEY(entry) REFERENCES entries(path)
        )
    ",
        (),
    )?;

    conn.execute(
        "
        CREATE TABLE IF NOT EXISTS templates (
            path VARCHAR NOT NULL PRIMARY KEY,
            hash TEXT NOT NULL
        )
    ",
        (),
    )?;

    conn.execute(
        "
        CREATE TABLE IF NOT EXISTS tags (
            name TEXT NOT NULL PRIMARY KEY
        )
    ",
        (),
    )?;

    conn.execute(
        "
        CREATE TABLE IF NOT EXISTS tags_pages (
            tag_name TEXT NOT NULL,
            page_path VARCHAR NOT NULL,
            PRIMARY KEY (tag_name, page_path),
            FOREIGN KEY (tag_name) REFERENCES tags(name),
            FOREIGN KEY (page_path) REFERENCES pages(out_path)
        )
    ",
        (),
    )?;

    Ok(conn)
}

/// Get hashes for a given path.
pub fn get_hashes<P: AsRef<Path>>(conn: &Connection, path: P) -> Result<Vec<String>> {
    let mut stmt = conn.prepare("SELECT hash FROM entries WHERE path = :path")?;
    let path_str = path
        .as_ref()
        .to_str()
        .context("Error while converting path to string")?;

    let hashes_iter = stmt.query_map(&[(":path", path_str)], |row| row.get(0))?;
    let mut hashes: Vec<String> = Vec::new();

    for hash in hashes_iter {
        hashes.push(hash?);
    }

    Ok(hashes)
}

/// Get all pages in the database.
///
/// Excludes any pages with the paths provided.
#[allow(clippy::needless_pass_by_value)]
pub fn get_pages(conn: &Connection, exclusions: Vec<&Path>) -> Result<Vec<Page>> {
    let mut stmt = conn.prepare(
        "
    SELECT out_path, 
        permalink, 
        date, 
        updated, 
        content, 
        toc, 
        summary, 
        title, 
        tags, 
        template, 
        slug, 
        draft,
        requires,
        entry
    FROM pages
    ",
    )?;
    let mut entry_stmt = conn.prepare("SELECT hash FROM entries WHERE path = ?")?;

    let pages_iter = stmt.query_map([], |row| {
        let out_path: String = row.get(0)?;
        let permalink: String = row.get(1)?;
        let tags: String = row.get(8)?;
        let parsed_tags = serde_json::from_str(&tags).expect("JSON should be valid.");
        let toc: String = row.get(5)?;
        let parsed_toc = serde_json::from_str(&toc).expect("JSON should be valid.");
        let requires: String = row.get(12)?;
        let parsed_requires = serde_json::from_str(&requires).expect("JSON should be valid.");

        let frontmatter = Frontmatter {
            title: row.get(7)?,
            tags: parsed_tags,
            template: row.get(9)?,
            date: Some(row.get(2)?),
            updated: Some(row.get(3)?),
            slug: row.get(10)?,
            draft: row.get(11)?,
            requires: parsed_requires,
        };

        let document = Document {
            date: row.get(2)?,
            updated: row.get(3)?,
            content: row.get(4)?,
            toc: parsed_toc,
            summary: row.get(6)?,
            frontmatter,
        };

        let entry_path: String = row.get(13)?;
        let hash = entry_stmt
            .query_map([&entry_path], |row| row.get(0))?
            .next()
            .expect("No corresponding entry for page in database?")?;

        Ok(Page {
            path: PathBuf::from(entry_path),
            source_hash: hash,
            out_path: PathBuf::from(out_path),
            permalink: Url::parse(&permalink).expect("URL should be valid."),
            document,
        })
    })?;

    let mut pages = Vec::new();
    for page in pages_iter {
        let p = page?;
        if !exclusions.contains(&p.path.as_path()) {
            pages.push(p);
        }
    }

    Ok(pages)
}

/// Get all template pages that depend on the given variable
pub fn get_template_pages(conn: &Connection, variable: &str) -> Result<Vec<TemplatePage>> {
    let mut stmt = conn.prepare(
        "
    SELECT out_path, 
        permalink,
        content,
        title,
        date,
        updated,
        slug,
        draft,
        dependencies,
        pagination_from,
        pagination_every,
        pagination_name_template,
        entry
    FROM template_pages
    WHERE pagination_from = ?1
    OR EXISTS (SELECT 1 FROM json_each(dependencies) WHERE value = ?1) 
    ",
    )?;
    let mut entry_stmt = conn.prepare("SELECT hash FROM entries WHERE path = ?")?;

    let templates_iter = stmt.query_map([variable], |row| {
        let out_path: String = row.get(0)?;
        let permalink: String = row.get(1)?;
        let content: String = row.get(2)?;
        let title: String = row.get(3)?;
        let date: DateTime<Utc> = row.get(4)?;
        let updated: DateTime<Utc> = row.get(5)?;
        let slug: Option<String> = row.get(6)?;
        let draft: bool = row.get(7)?;
        let dependencies_str: String = row.get(8)?;
        let dependencies = serde_json::from_str(&dependencies_str).expect("JSON should be valid.");
        let from: Option<String> = row.get(9)?;
        let every: Option<usize> = row.get(10)?;
        let name_template: Option<String> = row.get(11)?;
        let entry_path: String = row.get(12)?;

        let hash = entry_stmt
            .query_map([&entry_path], |row| row.get(0))?
            .next()
            .expect("No corresponding entry for page in database?")?;

        let pagination = if let (Some(f), Some(e)) = (from, every) {
            Some(Pagination {
                from: f,
                every: e,
                name_template,
            })
        } else {
            None
        };

        let frontmatter = TPFrontmatter {
            title,
            date,
            updated,
            slug,
            draft,
            dependencies,
            pagination,
        };

        let template_page = TemplatePage {
            path: PathBuf::from(entry_path),
            source_hash: hash,
            out_path: PathBuf::from(out_path),
            permalink: Url::parse(&permalink).expect("URL should be valid."),
            content,
            frontmatter,
        };

        Ok(template_page)
    })?;

    let mut template_pages = Vec::new();
    for template in templates_iter {
        template_pages.push(template?);
    }

    Ok(template_pages)
}

/// Get all tags in the database
pub fn get_tags(conn: &Connection) -> Result<Vec<String>> {
    let mut stmt = conn.prepare("SELECT name FROM tags")?;
    let mut rows = stmt.query([])?;

    let mut tags = Vec::new();
    while let Some(row) = rows.next()? {
        tags.push(row.get(0)?);
    }

    Ok(tags)
}

/// Insert a page into the database. If it already exists, update the existing entry.
pub fn insert_or_update_page(conn: &Connection, page: &Page) -> Result<()> {
    conn.execute(
        "
        INSERT INTO entries (path, hash) VALUES (?1, ?2)
        ON CONFLICT (path) DO UPDATE SET hash = (?2)
        ",
        (
            &page.path.to_str().context("Path should be valid unicode")?,
            &page.source_hash,
        ),
    )?;

    conn.execute(
        "
        INSERT INTO pages ( 
            out_path, permalink, date, updated, content, toc, summary, title, tags, template, slug, draft, requires, entry
        ) VALUES (
            ?1, ?2, datetime(?3), datetime(?4), ?5, json(?6), ?7, ?8, json(?9), ?10, ?11, ?12, ?13, ?14
        ) ON CONFLICT (out_path) DO UPDATE SET permalink = ?2,
            date = datetime(?3),
            updated = datetime(?4),
            content = ?5,
            toc = json(?6),
            summary = ?7,
            title = ?8,
            tags = json(?9),
            template = ?10,
            slug = ?11,
            draft = ?12,
            requires = ?13
    ",
        (
            &page.out_path.to_str().context("Path should be valid unicode.")?,
            &page.permalink.as_str(),
            &page.document.date,
            &page.document.updated,
            &page.document.content,
            &serde_json::to_string(&page.document.toc)?,
            &page.document.summary,
            &page.document.frontmatter.title,
            &serde_json::to_string(&page.document.frontmatter.tags)?,
            &page.document.frontmatter.template,
            &page.document.frontmatter.slug,
            &page.document.frontmatter.draft,
            &serde_json::to_string(&page.document.frontmatter.requires)?,
            &page.path.to_str().context("Path should be valid unicode.")?,
        ),
    )?;

    Ok(())
}

/// Insert an asset into the database. If it already exists, update the existing entry.
pub fn insert_or_update_asset(conn: &Connection, asset: &Asset) -> Result<()> {
    conn.execute(
        "
        INSERT INTO entries (path, hash) VALUES (?1, ?2)
        ON CONFLICT (path) DO UPDATE SET hash = (?2)
        ",
        (
            &asset
                .path
                .to_str()
                .context("Path should be valid unicode")?,
            &asset.source_hash,
        ),
    )?;

    conn.execute(
        "
        INSERT INTO assets (out_path, permalink, content, entry)
        VALUES (?1, ?2, ?3, ?4)
        ON CONFLICT (out_path) DO UPDATE SET permalink = ?2,
            content = ?3
        ",
        (
            &asset
                .out_path
                .to_str()
                .context("Path should be valid unicode")?,
            &asset.permalink.as_str(),
            &asset.content,
            &asset
                .path
                .to_str()
                .context("Path should be valid unicode")?,
        ),
    )?;

    Ok(())
}

/// Insert a static asset into the database. If it already exists, update the existing entry.
pub fn insert_or_update_static_file(conn: &Connection, static_file: &StaticFile) -> Result<()> {
    conn.execute(
        "
        INSERT INTO entries (path, hash) VALUES (?1, ?2)
        ON CONFLICT (path) DO UPDATE SET hash = (?2)
        ",
        (
            &static_file
                .path
                .to_str()
                .context("Path should be valid unicode")?,
            &static_file.source_hash,
        ),
    )?;

    conn.execute(
        "
        INSERT INTO static_files (out_path, permalink, content, entry)
        VALUES (?1, ?2, ?3, ?4)
        ON CONFLICT (out_path) DO UPDATE SET permalink = ?2,
            content = ?3
        ",
        (
            &static_file
                .out_path
                .to_str()
                .context("Path should be valid unicode")?,
            &static_file.permalink.as_str(),
            &static_file.content,
            &static_file
                .path
                .to_str()
                .context("Path should be valid unicode")?,
        ),
    )?;

    Ok(())
}

/// Insert a template page into the database. If it already exists, update the existing entry.
pub fn insert_or_update_template_page(
    conn: &Connection,
    template_page: &TemplatePage,
) -> Result<()> {
    conn.execute(
        "
        INSERT INTO entries (path, hash) VALUES (?1, ?2)
        ON CONFLICT (path) DO UPDATE SET hash = (?2)
        ",
        (
            &template_page
                .path
                .to_str()
                .context("Path should be valid unicode")?,
            &template_page.source_hash,
        ),
    )?;

    conn.execute(
        "
        INSERT INTO template_pages (
            out_path, permalink, content, title, date, updated, slug, draft, dependencies, pagination_from, pagination_every, pagination_name_template, entry
        )
        VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
        ON CONFLICT (out_path) DO UPDATE SET permalink = ?2,
            content = ?3,
            title = ?4,
            date = ?5,
            updated = ?6,
            slug = ?7,
            draft = ?8,
            dependencies = ?9,
            pagination_from = ?10,
            pagination_every = ?11,
            pagination_name_template = ?12
        ",
        (
            &template_page
                .out_path
                .to_str()
                .context("Path should be valid unicode")?,
            &template_page.permalink.as_str(),
            &template_page.content,
            &template_page.frontmatter.title,
            &template_page.frontmatter.date,
            &template_page.frontmatter.updated,
            &template_page.frontmatter.slug,
            &template_page.frontmatter.draft,
            &serde_json::to_string(&template_page.frontmatter.dependencies)?,
            &template_page.frontmatter.pagination.as_ref().map(|p| &p.from),
            &template_page.frontmatter.pagination.as_ref().map(|p| &p.every),
            &template_page.frontmatter.pagination.as_ref().and_then(|p| p.name_template.as_ref()),
            &template_page
                .path
                .to_str()
                .context("Path should be valid unicode")?,
        ),
    )?;

    Ok(())
}

/// Insert the tag, or if it already exists, do nothing.
pub fn insert_tag(conn: &Connection, tag: &str) -> Result<()> {
    let mut stmt = conn.prepare(
        "
        INSERT INTO tags (name) VALUES (?1)
        ON CONFLICT (name) DO NOTHING
        ",
    )?;

    stmt.execute((tag,))?;

    Ok(())
}

/// Get template hashes.
/// Get hashes for a given path.
pub fn get_template_hashes<P: AsRef<Path>>(conn: &Connection, path: P) -> Result<Vec<String>> {
    let mut stmt = conn.prepare("SELECT hash FROM templates WHERE path = :path")?;
    let path_str = path
        .as_ref()
        .to_str()
        .context("Error while converting path to string")?;

    let hashes_iter = stmt.query_map(&[(":path", path_str)], |row| {
        let hash: String = row.get(0)?;

        Ok(hash)
    })?;
    let mut hashes = Vec::new();

    for hash in hashes_iter {
        hashes.push(hash?);
    }

    Ok(hashes)
}

pub fn get_pages_for_template(conn: &Connection, template: &str) -> Result<Vec<Page>> {
    let mut stmt = conn.prepare(
        "
    SELECT out_path,
        permalink,
        date,
        updated,
        content,
        toc,
        summary,
        title,
        tags,
        template,
        slug,
        draft,
        requires,
        entry
    FROM pages
    WHERE template = ?
        ",
    )?;
    let mut entry_stmt = conn.prepare("SELECT hash FROM entries WHERE path = ?")?;

    let pages_iter = stmt.query_map([template], |row| {
        let out_path: String = row.get(0)?;
        let permalink: String = row.get(1)?;
        let tags: String = row.get(8)?;
        let parsed_tags = serde_json::from_str(&tags).expect("JSON should be valid.");
        let toc: String = row.get(5)?;
        let parsed_toc = serde_json::from_str(&toc).expect("JSON should be valid.");
        let requires: String = row.get(12)?;
        let parsed_requires = serde_json::from_str(&requires).expect("JSON should be valid.");

        let frontmatter = Frontmatter {
            title: row.get(7)?,
            tags: parsed_tags,
            template: row.get(9)?,
            date: Some(row.get(2)?),
            updated: Some(row.get(3)?),
            slug: row.get(10)?,
            draft: row.get(11)?,
            requires: parsed_requires,
        };

        let document = Document {
            date: row.get(2)?,
            updated: row.get(3)?,
            content: row.get(4)?,
            toc: parsed_toc,
            summary: row.get(6)?,
            frontmatter,
        };

        let entry_path: String = row.get(13)?;
        let hash = entry_stmt
            .query_map([&entry_path], |row| row.get(0))?
            .next()
            .expect("No corresponding entry for page in database?")?;

        Ok(Page {
            path: PathBuf::from(entry_path),
            source_hash: hash,
            out_path: PathBuf::from(out_path),
            permalink: Url::parse(&permalink).expect("URL should be valid."),
            document,
        })
    })?;

    let mut pages = Vec::new();
    for page in pages_iter {
        pages.push(page?);
    }

    Ok(pages)
}

/// Insert a template into the database. If it already exists, update the existing database entry.
pub fn insert_or_update_template(conn: &Connection, template: &(PathBuf, String)) -> Result<()> {
    conn.execute(
        "
        INSERT INTO templates (path, hash) VALUES (?1, ?2)
        ON CONFLICT (path) DO UPDATE SET hash = (?2)
        ",
        (
            &template
                .0
                .to_str()
                .context("Path should be valid unicode")?,
            &template.1,
        ),
    )?;

    Ok(())
}