Safe helpers for accessing and modifying environment variables.
In order to use functions from this package, just import
System.Environment.Extra
module.
>>> :t setEnv
(MonadThrow m, MonadIO m) => Text -> Text -> m ()
>>> setEnv "NAME" "Boris"
>>> setEnv "AGE" "12"
When it comes to reading environment variables there are three functions you should choose from:
getEnv
- the lifted and unsafe version ofSystem.Environment.lookupEnv
that works in anyMonadThrow
andMonadIO
monad and allows one to get anyIsString
value. When variable not found, an exception is thrown.>>> getEnv "NAME" *** Exception: Could not find value of $NAME in environment. >>> getEnv "HOME" "/Users/d12frosted"
envMaybe
- the lifted version ofSystem.Environment.lookupEnv
that returns anyIsString
value.>>> getEnv "NAME" Nothing >>> getEnv "HOME" Just "/Users/d12frosted"
envRead
- the lifted version ofSystem.Environment.lookupEnv
that allows one to provide a parser (reader) for that value.>>> setEnv "AGE" "10" >>> envMaybe "AGE" Just "10" >>> envRead decimal "AGE" Just 10 >>> envRead hexadecimal "AGE" Just 16 >>> envRead hexadecimal "HOME" Nothing
Both getEnv
and envMaybe
return an IsString
value, which can come handy in
many scenarios. In the following example getEnv
accepts Text
value, while
putStrLn
accepts String
value and getEnv
chains in both cases.
>>> setEnv "WHAAT" "HOME"
>>> getEnv "WHAAT"
"HOME"
>>> getEnv "WHAAT" >>= putStrLn
HOME
>>> getEnv "WHAAT" >>= getEnv
"/Users/d12frosted"
Just add env-extra
to stack.yaml
file.
extra-deps:
- git: https://github.com/d12frosted/env-extra
commit: 78eba1d8299be64721a96178425bf6c66776f573