Skip to content

Safe helpers for accessing and modifying environment variables

License

Notifications You must be signed in to change notification settings

d12frosted/env-extra

Repository files navigation

env-extra

https://github.com/d12frosted/env-extra/workflows/CI/badge.svg https://img.shields.io/hackage/v/env-extra.svg

Safe helpers for accessing and modifying environment variables.

In order to use functions from this package, just import System.Environment.Extra module.

Setting environment variables

>>> :t setEnv
(MonadThrow m, MonadIO m) => Text -> Text -> m ()
>>> setEnv "NAME" "Boris"
>>> setEnv "AGE" "12"

Reading environment variables

When it comes to reading environment variables there are three functions you should choose from:

  • getEnv - the lifted and unsafe version of System.Environment.lookupEnv that works in any MonadThrow and MonadIO monad and allows one to get any IsString 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 of System.Environment.lookupEnv that returns any IsString value.
    >>> getEnv "NAME"
    Nothing
    >>> getEnv "HOME"
    Just "/Users/d12frosted"
        
  • envRead - the lifted version of System.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"

Using with stack

Just add env-extra to stack.yaml file.

extra-deps:
- git: https://github.com/d12frosted/env-extra
  commit: 78eba1d8299be64721a96178425bf6c66776f573

About

Safe helpers for accessing and modifying environment variables

Resources

License

Stars

Watchers

Forks

Packages

No packages published