-
Notifications
You must be signed in to change notification settings - Fork 116
Version Options
Programs regularly have a --version
option, but it's not immediately obvious how one should write it in optparse, and indeed, there are a few different ways in which one can.
The easiest way to add a version option is with infoOption
, which is just a small composition over abortOption
. The benefit of doing it this way is that it doesn't clutter up the cli with another alternative branch.
Some folks prefer to have an alternative case on their ADT for commands for their Version option. In this case, I still recommend going down the route of having the type signature Parser (Command -> Command)
.
data Command
= Base Some Things
| Version
base :: Parser Command
version :: Parser (Command -> Command)
version = option id (const Version) (long "version" <> help "Display version" <> hidden)
opts :: ParserInfo Command
opts = info (base <**> helper <**> version) mempty
Although of course, it is possible to do it with an alternative as well.
To get the value of the version from Cabal, you'll need to import the generated Paths_
module. One can read about this in the Cabal docs.
So you might end up with something like:
import Data.Version (showVersion)
import Paths_your_package_name (version)
versioner :: Parser (a -> a)
versioner = infoOption (showVersion version) (long "version" <> help "Show version" <> hidden)
opts :: Parser Command
opts = info (base <**> helper <**> versioner) idm
> main --help
Usage: main COMMAND
Available options:
-h,--help Show this help text
--version Show version
> main --version
0.1.0.0