corny
corny

Reputation: 7852

Haskell, combining subcommands with other parsing option in optparse-generic

I'm using optparse-generic to parse the command line arguments of a program called example. I am combining labeled and unlabeled datatypes (as asked before).

data Labeled = Labeled { foo :: Maybe Int <?> "Help about foo" } deriving (Generic, Show)

instance ParseRecord Labeled

data Unlabeled = Unlabeled (String <?> "Help about the mandatory last argument.") deriving (Generic, Show)

instance ParseRecord Unlabeled

data Mixed = Mixed Labeled Unlabeled deriving (Show)

instance ParseRecord Mixed where
    parseRecord = Mixed <$> parseRecord <*> parseRecord

It generates the following help text.

Usage: example [--foo INT] STRING

Available options:
  -h,--help                Show this help text
  --foo INT                Help about foo 
  STRING                   Help about the mandatory last argument.

Now I would like to extend example to support different modular tasks. For example, as shown in the documentation, let's assume example can perform a Create and a Kill task. Each task may need different command line options.

data ExampleTasks
    = Create { name :: Text, duration :: Maybe Int }
    | Kill   { name :: Text }
    deriving (Generic, Show)

Question 1: I would like to combine these things such that a user can now additionally select the task which will be performed by example. How can this be achieved?

For example, I want to be able to call example as follows:

./example --foo 42 --task kill --name=foo "the last mandatory argument"

or

./example --task create --name=foo --duration 60 /bin/bash

The help text should look similar to something like the following (or maybe a nicer and clearer structure):

Usage: example [--foo INT] (--task TASKNAME TASKOPTIONS) STRING

Available options:
  -h,--help                Show this help text
  --foo INT                Help about foo 
  STRING                   Help about the mandatory last argument.

Available tasks:
  create                   Help about create
  kill                     Help about kill

Available taskoptions for create:
  --name STRING            Help about the name in create
  --duration ...           In seconds

Available taskoptions for kill
  --name STRING            Help about the name

Question 2: Can the whole --task argument and its parameters be optional? For example, I'd like to call:

./example --foo 42 "the last mandatory argument"

Upvotes: 1

Views: 256

Answers (0)

Related Questions