Environment Variables in Elm

import Html exposing (text)
import Platform.Cmd as Cmd
import Platform.Sub as Sub
import Task
import Process


main =
    Platform.worker
        { init = init
        , update = update
        , subscriptions = \_ -> Sub.none
        }


type Msg
    = PrintEnvironment
    | PrintComplete


init : () -> ( (), Cmd Msg )
init _ =
    ( (), Task.perform (\_ -> PrintEnvironment) (Process.sleep 0) )


update : Msg -> () -> ( (), Cmd Msg )
update msg _ =
    case msg of
        PrintEnvironment ->
            ( ()
            , Cmd.batch
                [ printEnvironmentVariables
                , Task.perform (\_ -> PrintComplete) (Process.sleep 0)
                ]
            )

        PrintComplete ->
            ( (), Cmd.none )


printEnvironmentVariables : Cmd Msg
printEnvironmentVariables =
    let
        printVar key =
            case key of
                "FOO" ->
                    Debug.log "FOO:" "1"

                "BAR" ->
                    Debug.log "BAR:" ""

                _ ->
                    Debug.log key ""
    in
    Cmd.batch
        (List.map (\key -> Task.perform (\_ -> ()) (Task.succeed (printVar key)))
            [ "FOO"
            , "BAR"
            , "TERM_PROGRAM"
            , "PATH"
            , "SHELL"
            ]
        )

Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to simulate setting, getting, and listing environment variables in Elm.

In Elm, we don’t have direct access to environment variables as we do in languages that run directly on the operating system. Instead, we’ll simulate this behavior using a Platform.worker program.

The init function simulates setting an environment variable by initializing our program state. In a real-world scenario, you might fetch these values from flags or an HTTP request.

To get a value for a key, we use pattern matching in the printVar function. This will return the value if the key is present, or an empty string if it’s not.

To list all key/value pairs, we simulate this by manually listing some common environment variables in the printEnvironmentVariables function.

When you run this program, it will output:

FOO: 1
BAR: 
TERM_PROGRAM: 
PATH: 
SHELL: 

Note that in Elm, we don’t have a direct equivalent to os.Environ(). In a real-world Elm application, environment variables would typically be passed to the Elm program as flags when it’s initialized, or fetched from a server via HTTP request.

This example demonstrates how to work with key-value pairs in Elm, which is conceptually similar to working with environment variables in other languages. However, it’s important to understand that this is a simulation and not actual interaction with the system’s environment variables.