Created
November 8, 2022 14:45
-
-
Save kayvank/3a3fe3efd9b03530996aba2f8aab1199 to your computer and use it in GitHub Desktop.
optparse-applicative for cli params of Maybne NonEmptyList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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