haskelloptparse-applicative

optparse-applicative non empty string argument


How can I implement a non empty string argument?

parserStart :: Parser String
parser = strArgument (metavar "EXAMPLE") 

How can prevent it from successfully parsing an empty string - ""?

Having previous experience with Parsec/Attoparsec, I assume I could write my own parser or possibly use something applicative to inspect the value and fail if it's an empty string (I think this won't be possible as I need a Monad for this)?


Solution

  • import Data.String
    import Data.Text
    import Options.Applicative.Types (ReadM, readerAsk)
    
    nonEmptystr :: IsString s => ReadM s
    nonEmptystr = do
      readerAsk >>= \case
        "" -> fail "Invalid argument: Empty string"
        x -> pure $ fromString x
    
    f :: Parser Text
    f = argument nonEmptystr (metavar "task")