Skip to content

Instantly share code, notes, and snippets.

@kayvank
Created November 8, 2022 14:45
Show Gist options
  • Save kayvank/3a3fe3efd9b03530996aba2f8aab1199 to your computer and use it in GitHub Desktop.
Save kayvank/3a3fe3efd9b03530996aba2f8aab1199 to your computer and use it in GitHub Desktop.
optparse-applicative for cli params of Maybne NonEmptyList
#!/usr/bin/env stack
{- stack
script
--resolver lts-18.28
--package async
--package optparse-applicative
--package text
-}
import Data.List.NonEmpty (NonEmpty, fromList)
import Data.Semigroup ((<>))
import Options.Applicative (Alternative (some), Mod, OptionFields,
Parser, auto, execParser, fullDesc,
header, help, helper, info, long, metavar,
option, optional, progDesc, short, str,
(<**>))
data Cli = Cli
{
port :: Int
, hostnames :: Maybe (NonEmpty String)
} deriving (Show)
main :: IO ()
main = execParser clis >>= print
where
clis = info (cli <**> helper )
(fullDesc
<> progDesc "Print a greeting for TARGET"
<> header "hello - a test for optparse-applicative")
cli :: Parser Cli
cli = Cli
<$> option auto ( long "port"
<> short 'p'
<> metavar "PORT"
<> help "port number" )
<*> multiString ( long "hostname"
<> short 'h'
<> metavar "HOSTNAME"
<> help "hostname")
multiString' :: Mod OptionFields [String] -> Parser (NonEmpty String )
multiString' desc = fromList . concat <$> some single
where
single = option (str >>= parseStringList) desc
multiString :: Mod OptionFields [String] -> Parser (Maybe (NonEmpty String))
multiString = optional . multiString'
parseStringList :: Monad m => String -> m [String]
parseStringList = return . words
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment