2024-02-16 22:28:13 -05:00
|
|
|
defmodule SloaneSH.Context do
|
|
|
|
@moduledoc """
|
|
|
|
A SloaneSH build context containing configuration and reference to content
|
|
|
|
files.
|
|
|
|
"""
|
|
|
|
use TypedStruct
|
2024-02-24 13:16:56 -05:00
|
|
|
require Logger
|
2024-02-16 22:28:13 -05:00
|
|
|
|
|
|
|
alias SloaneSH.Config
|
2024-02-24 13:16:56 -05:00
|
|
|
alias SloaneSH.Asset
|
|
|
|
alias SloaneSH.Assets.Page
|
|
|
|
alias SloaneSH.Assets.Post
|
2024-02-24 19:52:57 -05:00
|
|
|
alias SloaneSH.Assets.Image
|
2024-02-16 22:28:13 -05:00
|
|
|
alias __MODULE__
|
|
|
|
|
|
|
|
typedstruct do
|
|
|
|
field :config, Config.t(), enforce: true
|
2024-02-24 13:16:56 -05:00
|
|
|
field :pages, [Asset.t()], default: []
|
|
|
|
field :posts, [Asset.t()], default: []
|
2024-02-24 19:52:57 -05:00
|
|
|
field :images, [Asset.t()], default: []
|
2024-02-16 22:28:13 -05:00
|
|
|
end
|
|
|
|
|
2024-02-24 13:16:56 -05:00
|
|
|
def new(cfg \\ Config.default()) do
|
|
|
|
pages = load_assets(cfg, Page, cfg.pages_dir)
|
|
|
|
posts = load_assets(cfg, Post, cfg.posts_dir)
|
2024-02-24 19:52:57 -05:00
|
|
|
images = load_assets(cfg, Image, cfg.images_dir)
|
2024-02-16 22:28:13 -05:00
|
|
|
|
2024-02-24 19:52:57 -05:00
|
|
|
%Context{config: cfg, pages: pages, posts: posts, images: images}
|
2024-02-16 22:28:13 -05:00
|
|
|
end
|
|
|
|
|
2024-02-24 13:16:56 -05:00
|
|
|
defp load_assets(cfg, mod, src_dir) do
|
|
|
|
exts = mod.extensions(cfg)
|
|
|
|
|
|
|
|
for src <- collect_src_files(src_dir, exts) do
|
|
|
|
contents = File.read!(src)
|
|
|
|
|
|
|
|
case mod.attrs(cfg, src, contents) do
|
|
|
|
{:ok, attrs, src_contents} ->
|
|
|
|
%Asset{mod: mod, src: src, src_contents: src_contents, attrs: attrs}
|
2024-02-16 22:28:13 -05:00
|
|
|
|
2024-02-24 13:16:56 -05:00
|
|
|
{:ok, attrs} ->
|
|
|
|
%Asset{mod: mod, src: src, src_contents: contents, attrs: attrs}
|
2024-02-16 22:28:13 -05:00
|
|
|
|
2024-02-24 13:16:56 -05:00
|
|
|
_ ->
|
|
|
|
Logger.warning("Failed to parse attrs for #{inspect(src)}")
|
|
|
|
%Asset{mod: mod, src: src, src_contents: contents, attrs: %{}}
|
2024-02-16 22:28:13 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2024-02-24 13:16:56 -05:00
|
|
|
defp collect_src_files(src_dir, exts) do
|
|
|
|
files = src_dir |> File.ls!() |> Enum.map(&Path.join(src_dir, &1))
|
|
|
|
{src_files, rest} = Enum.split_with(files, &String.ends_with?(&1, exts))
|
2024-02-16 22:28:13 -05:00
|
|
|
|
2024-02-24 13:16:56 -05:00
|
|
|
other_dirs = Enum.filter(rest, &File.dir?/1)
|
2024-02-16 22:28:13 -05:00
|
|
|
|
2024-02-24 13:16:56 -05:00
|
|
|
src_files ++ Enum.flat_map(other_dirs, &collect_src_files(&1, exts))
|
2024-02-16 22:28:13 -05:00
|
|
|
end
|
|
|
|
end
|