optparse-applicative icon indicating copy to clipboard operation
optparse-applicative copied to clipboard

Is it possible to automatically show in help which values are valid for an option?

Open wolverian opened this issue 2 years ago • 3 comments

Given an option of a sum type (Foo in this example):

module Main where

import Options.Applicative

data Opts = Opts
    { flag :: Foo
    , ok :: Bool
    }
    deriving (Show)

data Foo = Bar | Baz | Quux deriving (Read, Show)

opts :: Parser Opts
opts =
    Opts
        <$> option auto (help "how to do it" <> long "flag" <> value Bar <> showDefault)
        <*> option auto (help "is it ok" <> long "ok" <> value True <> showDefault)

main :: IO ()
main = do
    opts' <- execParser (info (opts <**> helper) fullDesc)
    print opts'

This is the help output currently:

Usage: optest [--flag ARG] [--ok ARG]

Available options:
  --flag ARG               how to do it (default: Bar)
  --ok ARG                 is it ok (default: True)
  -h,--help                Show this help text

Instead of --flag ARG how to do it (default: Bar) I would like something like --flag ARG how to do it (default: Bar, allowed values: Foo, Bar, Baz). Can optparse-applicative do this?

wolverian avatar Mar 16 '23 18:03 wolverian

Interesting question. We don't support this natively at the moment, but I think it would be a simple addition to write.

With a Bounded instance on your type, one could imagine something like:

option auto (help "how to do it" <> long "flag" <> value Bar <> showDefault <> boundedPossibilities)

Seeing as all showDefault does is organise the parens and default text to tack onto the end of the help text for the option, you can do it yourself with the help text.

HuwCampbell avatar Mar 16 '23 22:03 HuwCampbell

With a Bounded instance on your type, one could imagine something like:

I think you'd want Enum as well.

Seeing as all showDefault does is organise the parens and default text to tack onto the end of the help text for the option, you can do it yourself with the help text.

Is there a way to add to the help text with a Mod, instead of replacing it altogether?

wolverian avatar Mar 17 '23 14:03 wolverian

I think you'd want Enum as well.

Yes

Is there a way to add to the help text with a Mod, instead of replacing it altogether?

No you would have to just put it in help yourself.

I would be happy to look at a PR for this. My only worry is that one could use it for Int.

HuwCampbell avatar Mar 19 '23 22:03 HuwCampbell