Last active
April 12, 2022 03:55
-
-
Save LightAndLight/66d73ba8261ba5243432c406b0d0f78d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment