Skip to content

Instantly share code, notes, and snippets.

@ajhager
Last active August 29, 2015 14:26
Show Gist options
  • Save ajhager/5bc43e89d7a85b72f3fe to your computer and use it in GitHub Desktop.
Save ajhager/5bc43e89d7a85b72f3fe to your computer and use it in GitHub Desktop.
Applicative style API for a flag parsing module in the upcoming github.com/elmcast/elm-node
module Flag where
type Parser a = Parser
parse : Parser a -> Result String a
parseWith : Parser a -> List String -> Dict String String -> Result String a
parsing : (a -> b) -> Parser (a -> b)
withOpt : Parser (a -> b) -> Parser a -> Parser b
withArg : Parser (a -> b) -> Parser a -> Parser b
withEnv : Parser (a -> b) -> Parser a -> Parser b
commands : [(String, Parser a)] -> Parser (Maybe a)
int : String -> Parser (Maybe Int)
bool : String -> Parser (Maybe Bool)
float : String -> Parser (Maybe Float)
string : String -> Parser (Maybe String)
switch : String -> Parser Bool
defaulted : Parser (Maybe a) -> a -> Parser a
command : String -> Parser a -> Parser (Maybe a)
oneOf : [Parser (Maybe a)] -> Parser (Maybe a)
module Main where
import Console
import Process
import Flag exposing (withOpt, withArg, withEnv, defaulted)
type Command
= Server Bool String Int String
| Client Bool String Int (Maybe Float)
| Usage
port main : Task x ()
port main =
case parseFlags Process.args Process.env of
Err err -> Console.fatal err
Ok cmd -> runCommand cmd
runCommand : Command -> Task x ()
runCommand cmd =
case cmd of
Usage ->
Console.log "main usage"
Server help serverHost serverPort filesPath ->
if help
then Console.log "server usage"
else runServer serverPort serverHost filesPath
Client help serverHost serverPort timeout ->
if help
then Console.log "client usage"
else runClient serverPort serverHost timeout
parseFlags : List String -> Dict String String -> Result String Command
parseFlags args env =
let server =
Flag.parsing Server
`withOpt` Flag.switch "help"
`withOpt` Flag.int "port" `defaulted` 8080
`withOpt` Flag.string "host" `defaulted` "localhost"
`withEnv` Flag.string "ELM_PATH" `defaulted` "."
client =
Flag.parsing Client
`withOpt` Flag.switch "help"
`withOpt` Flag.int "port" `defaulted` 8080
`withOpt` Flag.string "host" `defaulted` "localhost"
`withArg` Flag.float "TIMEOUT"
commands =
Flag.oneOf
[ Flag.command "server" server
, Flag.command "client" client
] `defaulted` Flag.parsing Usage
in
Flag.parseWith commands args env
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment