dillonkearns/elm-cli-options-parser/5.0.0

NOTE: the latest version is 5.0.1

Cli.Program

Building a Config

A Cli.Program.Config is created with Cli.Program.config. Then OptionsParsers are added to it with Cli.Program.add. Finally, you create a Cli.Program.StatelessProgram using stateless or a Cli.Program.StatefulProgram using stateful.

import Cli.Option as Option
import Cli.OptionsParser as OptionsParser
import Cli.Program as Program
import Ports


programConfig : Program.Config GreetOptions
programConfig =
    Program.config
        |> Program.add
            (OptionsParser.build GreetOptions
                |> OptionsParser.with (Option.requiredKeywordArg "name")
                |> OptionsParser.with (Option.optionalKeywordArg "greeting")
            )


type alias GreetOptions =
    { name : String
    , maybeGreeting : Maybe String
    }


init : Flags -> GreetOptions -> Cmd Never
init flags { name, maybeGreeting } =
    maybeGreeting
        |> Maybe.withDefault "Hello"
        |> (\greeting -> greeting ++ " " ++ name ++ "!")
        |> Ports.print


type alias Flags =
    Program.FlagsIncludingArgv {}


main : Program.StatelessProgram Never
main =
    Program.stateless
        { printAndExitFailure = Ports.printAndExitFailure
        , printAndExitSuccess = Ports.printAndExitSuccess
        , init = init
        , config = programConfig
        }

See the examples for some end-to-end examples.

config : Config decodesTo

Create a Config with no OptionsParsers. Use Cli.Program.add to add OptionsParsers.

type Config msg

A Cli.Program.Config is used to build up a set of OptionsParsers for your Command-Line Interface, as well as its meta-data such as version number.

add : OptionsParser msg anything -> Config msg -> Config msg

Add an OptionsParser to your Cli.Program.Config.

Programs

stateless : ProgramOptions msg options flags -> StatelessProgram msg flags

Create a CLI that processes arguments and exits immediately. Use stateful instead if you need to perform Cmds (HTTP, etc.).

type alias ProgramOptions decodesTo options flags =
{ printAndExitFailure : String -> Cmd decodesTo
, printAndExitSuccess : String -> Cmd decodesTo
, init : FlagsIncludingArgv flags -> options -> Cmd decodesTo
, config : Config options
}

Configuration for a stateless CLI program. Pass this record to stateless.

Stateless programs run once and exit - there is no persistent model or update loop. Your init receives the parsed CLI options and returns a Cmd that performs the program's work, then the program is done.

  • printAndExitFailure - Port to print a message and exit with a non-zero status code
  • printAndExitSuccess - Port to print a message and exit with status code 0
  • init - Receives parsed CLI options and returns a Cmd to perform the program's work
  • config - The CLI configuration built with config and add
StatefulOptions msg model cliOptions flags
-> Program
(FlagsIncludingArgv flags)
(StatefulProgramModel model cliOptions)
msg

A stateful program can have a model that it creates and updates via init and update. It also has subscriptions. See the Curl.elm example.

type alias StatefulOptions msg model cliOptions flags =
{ printAndExitFailure : String -> Cmd msg
, printAndExitSuccess : String -> Cmd msg
, init : FlagsIncludingArgv flags -> cliOptions -> ( model, Cmd msg )
, update : cliOptions -> msg -> model -> ( model, Cmd msg )
, subscriptions : cliOptions -> model -> Sub msg
, config : Config cliOptions
}

Configuration for a stateful CLI program. Pass this record to stateful.

Stateful programs work like standard Elm programs with a model, update loop, and subscriptions. Use this when your CLI needs to wait for responses (e.g., HTTP requests) or maintain state across multiple events. The parsed CLI options are passed to both init and update.

  • printAndExitFailure - Port to print a message and exit with a non-zero status code
  • printAndExitSuccess - Port to print a message and exit with status code 0
  • init - Initialize your model with the parsed CLI options
  • update - Handle messages and update your model (also receives CLI options)
  • subscriptions - Subscribe to external events
  • config - The CLI configuration built with config and add
type alias StatelessProgram msg flags =
Program (FlagsIncludingArgv flags) () msg

A program that processes arguments and exits. Use with stateless.

type alias StatefulProgram model msg cliOptions flags =
Program
(FlagsIncludingArgv flags)
(StatefulProgramModel model cliOptions)
msg

A program with a model and update loop. Use with stateful.

type alias FlagsIncludingArgv flagsRecord =
{ flagsRecord
| argv : List String
, versionMessage : String
, colorMode : Bool
}

Flags in Cli Programs can contain any data as long as it is a record at the top-level which contains the required fields. In other words, it must be a record of type FlagsIncludingArgv (if you aren't familiar with them, you can read more about extensible records here).

You pass in the flags like this (see the examples folder for more):

#!/usr/bin/env node

const useColor = process.stdout.isTTY && !process.env.NO_COLOR;

let program = require("./elm.js").Elm.Main.init({
  flags: {
    argv: process.argv,
    versionMessage: "1.2.3",
    colorMode: useColor
  }
});
mapConfig : (a -> b) -> Config a -> Config b

Transform the return type for all of the registered OptionsParser's in the Config.

Help Text and JSON Schema

Generate help text for terminal display, or a JSON Schema for use as an MCP tool inputSchema definition. JSON schemas are generated from the types provided by Cli.Option.Typed constructors.

helpText : String -> Config msg -> String

Generate plain-text help for a Config, suitable for including in machine-readable introspection output.

Uses no ANSI color codes. The programName argument is used as the prefix in the usage synopsis.

import Cli.Option as Option
import Cli.OptionsParser as OptionsParser
import Cli.Program as Program


Program.config
    |> Program.add
        (OptionsParser.build identity
            |> OptionsParser.with (Option.requiredKeywordArg "name")
            |> OptionsParser.with (Option.flag "verbose")
        )
    |> Program.helpText "my-script"
--> "my-script --name <NAME> [--verbose]"
toJsonSchema : String -> Config msg -> Value

Generate a JSON Schema describing the inputs of this CLI configuration.

The schema follows the JSON Schema format. Named options (keyword args, flags, keyword lists) are top-level properties with an x-cli-kind annotation indicating their CLI invocation form. Positional arguments and subcommands go inside a $cli object.

The schema's description field includes a usage synopsis and instructions for how to invoke the command via JSON or traditional CLI flags.

Suitable for use as an MCP tool inputSchema definition.

import Cli.Option as Option
import Cli.OptionsParser as OptionsParser
import Cli.Program as Program


programConfig =
    Program.config
        |> Program.add
            (OptionsParser.build identity
                |> OptionsParser.with (Option.requiredKeywordArg "name")
            )


schema =
    Program.toJsonSchema "my-script" programConfig

The resulting schema has name as a top-level property with "x-cli-kind": "keyword", and a required $cli object as the sentinel for JSON input mode.

Low-Level / Testing

run : Config msg -> List String -> String -> ColorMode -> RunResult msg

Run the CLI parser directly and get back a RunResult. This is useful for testing your CLI configuration without needing to set up the full Platform.Program infrastructure.

import Cli.Program as Program


-- Test that missing required arg shows error (use WithoutColor for tests)
case Program.run myConfig [ "node", "myprog" ] "1.0.0" Program.WithoutColor of
    Program.SystemMessage Program.Failure message ->
        -- Assert on the error message
        String.contains "Missing" message


    _ ->
        False

Note: argv should include the node path and script path as the first two elements, just like process.argv in Node.js.

type RunResult match
= SystemMessage ExitStatus String
| CustomMatch match

The result of running the CLI parser. Useful for testing.

  • SystemMessage exitStatus message - A system message (help, version, or error) with exit status
  • CustomMatch match - Successfully matched and parsed the CLI options
= Success
| Failure

Exit status for CLI programs. Failure means exit code 1, Success means exit code 0.

= WithColor
| WithoutColor

Control whether ANSI color codes are included in output.

  • WithColor - Include ANSI color codes for styled terminal output
  • WithoutColor - Plain text output without any ANSI codes

Used with run for testing, and internally by the CLI infrastructure.