{-# options_ghc -Wall -Werror #-} module Env where import Data.Maybe (fromMaybe) import qualified System.Environment data LogLevel = DEBUG | INFO | WARN | ERROR deriving (Show, Read) newtype Parser a = Parser { parse :: String -> IO a } filePath :: Parser FilePath filePath = Parser pure logLevel :: Parser LogLevel logLevel = Parser (pure . read) required :: String -> Parser a -> IO a required key parser = do value <- System.Environment.lookupEnv key case value of Nothing -> error $ "missing required key: " <> show key Just input -> parse parser input optional :: String -> Parser a -> IO (Maybe a) optional key parser = do value <- System.Environment.lookupEnv key case value of Nothing -> pure Nothing Just input -> Just <$> parse parser input withDefault :: Functor f => f (Maybe a) -> a -> f a withDefault ma a = fromMaybe a <$> ma infixl 5 `withDefault` data Config = Config { _HOMEPAGE_CONFIG_FILE :: FilePath , _HOMEPAGE_LOG_FILE :: Maybe FilePath , _HOMEPAGE_LOG_LEVEL :: LogLevel } deriving Show main :: IO () main = do config <- Config <$> optional "HOMEPAGE_CONFIG_FILE" filePath `withDefault` "./homepage.json" <*> optional "HOMEPAGE_LOG_FILE" filePath <*> optional "HOMEPAGE_LOG_LEVEL" logLevel `withDefault` DEBUG print config