{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
module Headroom.Variables
(
mkVariables
, dynamicVariables
, parseVariables
, compileVariables
)
where
import Headroom.Meta ( TemplateType )
import Headroom.Template ( Template(..) )
import Headroom.Types ( CurrentYear(..)
, fromHeadroomError
, toHeadroomError
)
import Headroom.Variables.Types ( Variables(..) )
import RIO
import qualified RIO.HashMap as HM
import qualified RIO.Text as T
mkVariables :: [(Text, Text)]
-> Variables
mkVariables = Variables . HM.fromList
dynamicVariables :: CurrentYear
-> Variables
dynamicVariables (CurrentYear year) =
mkVariables [("_current_year", tshow year)]
parseVariables :: MonadThrow m
=> [Text]
-> m Variables
parseVariables variables = fmap mkVariables (mapM parse variables)
where
parse input = case T.split (== '=') input of
[key, value] -> pure (key, value)
_ -> throwM $ InvalidVariable input
compileVariables :: (MonadThrow m)
=> Variables
-> m Variables
compileVariables variables@(Variables kvs) = do
compiled <- mapM compileVariable (HM.toList kvs)
pure $ mkVariables compiled
where
compileVariable (key, value) = do
parsed <- parseTemplate @TemplateType (Just $ "variable " <> key) value
rendered <- renderTemplate variables parsed
pure (key, rendered)
data VariablesError = InvalidVariable !Text
deriving (Eq, Show)
instance Exception VariablesError where
displayException = displayException'
toException = toHeadroomError
fromException = fromHeadroomError
displayException' :: VariablesError -> String
displayException' = T.unpack . \case
InvalidVariable raw -> ("Cannot parse variable key=value from: " <> raw)