Created
April 11, 2018 12:47
-
-
Save sarkologist/5dff67cb05759e438f08605de12db4ba to your computer and use it in GitHub Desktop.
free applicative parsing of environment variables
This file contains 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
s3AccessKey :: EnvVar Aws.AccessKey | |
s3AccessKey = mkEnvVar "S3_ACCESS_KEY" (Just . Aws.AccessKey . convertString) Nothing | |
s3SecretKey :: EnvVar Aws.SecretKey | |
s3SecretKey = mkEnvVar "S3_SECRET_KEY" (Just . Aws.SecretKey . convertString) Nothing | |
s3FromKeys :: EnvVar Aws.Credentials | |
s3FromKeys = iI Aws.FromKeys s3AccessKey s3SecretKey Ii |
This file contains 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
{-# LANGUAGE RecordWildCards #-} | |
module Capital.Env | |
( EnvVar | |
, mkEnvVar | |
, getEnvVar | |
) | |
where | |
import Data.Monoid | |
import Data.Functor.Compose | |
import Control.Applicative | |
import Control.Applicative.Free | |
import System.Environment | |
data E a = | |
E { | |
envName :: String | |
, envParse :: String -> Maybe a | |
, envDef :: Maybe a | |
} | |
type EnvVar = Ap E | |
mkEnvVar :: String -> (String -> Maybe a) -> Maybe a -> EnvVar a | |
mkEnvVar n p d = liftAp $ E n p d | |
getEnvVar :: EnvVar a -> IO (Maybe a) | |
getEnvVar = getCompose . runAp phi | |
where | |
phi :: E a -> Compose IO Maybe a | |
phi E{..} = Compose $ do | |
mValue <- lookupEnv envName | |
(<|> envDef) <$> | |
case mValue of | |
Nothing -> Nothing <$ putStrLn ("could not lookup environment variable: " <> envName) | |
Just val -> | |
case envParse val of | |
Nothing -> Nothing <$ putStrLn ("could not parse environment variable " <> envName) | |
Just a -> Just a <$ putStrLn ("parsed environment variable " <> envName) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment