Skip to content
Snippets Groups Projects
writer.gleam 2.26 KiB
Newer Older
Mikko Ahlroth's avatar
Mikko Ahlroth committed
//// The writer takes rendered content and writes it into the filesystem.

import gleam/dict
Mikko Ahlroth's avatar
Mikko Ahlroth committed
import gleam/list
import gleam/result
import gleam/string
import lustre/ssg
Mikko Ahlroth's avatar
Mikko Ahlroth committed
import scriptorium/config.{type Configuration, WriteError}
import scriptorium/rendering/database.{type RenderDatabase} as _
import scriptorium/utils/priv
Mikko Ahlroth's avatar
Mikko Ahlroth committed
/// Write the rendered content into the filesystem using lustre_ssg.
pub fn write(db: RenderDatabase, config: Configuration) {
  let site =
    ssg.new(config.output_path)
    |> ssg.add_static_dir(priv.path() <> "/assets")

  let single_posts =
    db.single_posts
    |> list.map(fn(post) {
      let path = config.paths.single_post(post.orig)
      #(path, post.content)
    })

  let assert [index, ..rest] = db.index_pages

  let site = ssg.add_static_route(site, "/", index.content)

  let site =
    list.fold(rest, site, fn(acc, page) {
      let path = config.paths.list_page(config.paths.index, page.page)
      ssg.add_static_route(acc, path, page.content)
    })

  let site =
    dict.fold(db.tag_pages, site, fn(acc, tag, posts) {
      list.fold(posts, acc, fn(acc2, page) {
        let path = config.paths.list_page(config.paths.tag(tag), page.page)
        ssg.add_static_route(acc2, path, page.content)
      })
    })

  let site =
    dict.fold(db.year_pages, site, fn(acc, year, posts) {
      list.fold(posts, acc, fn(acc2, page) {
        let path = config.paths.list_page(config.paths.year(year), page.page)
        ssg.add_static_route(acc2, path, page.content)
      })
    })

  let site =
    dict.fold(db.month_pages, site, fn(acc, year_month, posts) {
      let #(year, month) = year_month
      list.fold(posts, acc, fn(acc2, page) {
        let path =
          config.paths.list_page(config.paths.month(year, month), page.page)
        ssg.add_static_route(acc2, path, page.content)
      })
    })

  let site = ssg.add_static_xml(site, config.paths.feed_file, db.feed)
Mikko Ahlroth's avatar
Mikko Ahlroth committed

Mikko Ahlroth's avatar
Mikko Ahlroth committed
  let site =
    list.fold(single_posts, site, fn(acc, item) {
      let #(path, post) = item
      ssg.add_static_route(acc, path, post)
    })

  let site =
    list.fold(db.pages, site, fn(acc, page) {
      ssg.add_static_route(acc, config.paths.page(page.page), page.content)
  site
  |> ssg.build()
  |> result.map_error(fn(err) { WriteError(string.inspect(err)) })