nani.wtf/static-site-generator/Util/Hakyll/Context.hs

44 lines
1.3 KiB
Haskell

module Util.Hakyll.Context (
updateFieldWith,
defaultConstField,
ifField,
) where
import Hakyll
import Data.Maybe (fromMaybe)
import Control.Applicative (empty)
{- |
Shortcut function for getting an Items Metadata
This is used as a helper function in a lot of places.
-}
getItemMetadata :: Item a -> Compiler Metadata
getItemMetadata = getMetadata . itemIdentifier
{- |
-}
updateFieldWith :: String -> String -> (String -> String) -> Item a -> Compiler String
updateFieldWith field defaultPreviousValue f =
fmap updateField . getMetadata . itemIdentifier
where
updateField :: Metadata -> String
updateField = f . fromMaybe defaultPreviousValue . lookupString field
{- |
This function takes a field name, and a default String value.
If the field is found, it will leave it be, else inject the default value.
Similar to the behaviour of (fromMaybe)
-}
defaultConstField :: String -> String -> Context String
defaultConstField fieldString defaultValue =
field fieldString (fmap f . getItemMetadata)
where
f :: Metadata -> String
f = fromMaybe defaultValue . lookupString fieldString
{-
-}
ifField :: String -> (Item a -> Compiler ContextField) -> Context a
ifField key value = Context $ \k _ i -> if k == key then value i else empty