module System.Console.ArgParser.QuickParams (
boolFlag
, reqFlag
, optFlag
, reqPos
, optPos
, reqFlagArgs
, optFlagArgs
, posArgs
, RawRead
) where
import Data.Either (partitionEithers)
import Data.List (unfoldr)
import Control.Applicative
import System.Console.ArgParser.BaseType
import System.Console.ArgParser.Params
readMaybe :: (Read a) => String -> Maybe a
readMaybe s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
class RawRead a where
rawParse :: String -> Maybe (a, String)
instance RawRead Char where
rawParse s = case s of
[] -> Nothing
c:s' -> Just (c, s')
instance RawRead a => RawRead [a] where
rawParse s = Just (unfoldr rawParse s, [])
instance RawRead Float where
rawParse = defaultRawParse
instance RawRead Int where
rawParse = defaultRawParse
defaultRawParse :: Read t => String -> Maybe (t, String)
defaultRawParse s = (\val -> (val , [])) <$> readMaybe s
rawRead :: RawRead a => String -> Maybe a
rawRead s = fst <$> rawParse s
readArg
:: RawRead a
=> Key
-> Arg
-> ParseResult a
readArg key arg = case rawRead arg of
Just val -> Right val
Nothing -> Left $ "Could not parse parameter " ++ key ++ "."
++ "Unable to convert " ++ arg
boolFlag
:: Key
-> FlagParam Bool
boolFlag key = FlagParam Short key id
reqPos
:: RawRead a
=> Key
-> StdArgParam a
reqPos key = StdArgParam Mandatory Pos key (SingleArgParser $ readArg key)
optPos
:: RawRead a
=> a
-> Key
-> StdArgParam a
optPos val key = StdArgParam (Optional val) Pos key (SingleArgParser $ readArg key)
reqFlag
:: RawRead a
=> Key
-> StdArgParam a
reqFlag key = StdArgParam Mandatory Flag key (SingleArgParser $ readArg key)
optFlag
:: RawRead a
=> a
-> Key
-> StdArgParam a
optFlag val key = StdArgParam (Optional val) Flag key (SingleArgParser $ readArg key)
readArgs
:: RawRead a
=> Key
-> b
-> (b -> a -> b)
-> Args
-> ParseResult b
readArgs key initval accum args = case errors of
[] -> Right $ foldl accum initval values
_ -> Left $ unlines errors
where
(errors, values) = partitionEithers $ map (readArg key) args
posArgs
:: RawRead a
=> Key
-> b
-> (b -> a -> b)
-> StdArgParam b
posArgs key initval accum = StdArgParam
Mandatory Pos key (MulipleArgParser $ readArgs key initval accum)
reqFlagArgs
:: RawRead a
=> Key
-> b
-> (b -> a -> b)
-> StdArgParam b
reqFlagArgs key initval accum = StdArgParam
Mandatory Flag key (MulipleArgParser $ readArgs key initval accum)
optFlagArgs
:: RawRead a
=> b
-> Key
-> b
-> (b -> a -> b)
-> StdArgParam b
optFlagArgs val key initval accum = StdArgParam
(Optional val) Flag key (MulipleArgParser $ readArgs key initval accum)