JDbP
JDbP

Reputation: 61

Haskell. Parsing command line arguments

I am learning Haskell programming language. Now I am studying IO. I'd like to write simple command line util. The util take two files (JSON or YAML), compare them and output the result of compare (JSON, YAML, Plain text).

I think, the interface of my util would be that:

my_util "path to first file" "path to second file" -- format JSON. 

I decided to use CmdArgs. But now, my interface show so:

my_util -f="path to first file" -s="path to second file" -- format JSON.

What I was done.

data Gendiff = Gendiff
    {first_file ::  String
    ,second_file :: String
    ,format :: String
    }
    deriving (Data,Typeable,Show,Eq)
 
gendiff = Gendiff
    {first_file  = def &=  name "f" &= typDir  &= help "path to first file to compare"  &= typ "String"
    ,second_file = def &=  name "s" &=  typDir  &= help  "path to second file to compare" &= typ "String"
    ,format =  &= opt "JSON" &= help "set format of output"  &= typ "String"
    } &=
    verbosity &=
    help "Compares two configuration files and shows a difference." &=
    summary " Gendiff v0.0.1, (C) dosart"
 
main = print =<< cmdArgs gendif

How I can make first variant? How to set the format flag default value?

Upvotes: 1

Views: 192

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152707

I guess you would use args. Something like this:

data Gendiff = Gendiff
    { format :: String
    , files :: [String]
    }

gendiff = Gendiff
    { format = def &= -- same as before
    , files = def &= args
    } &= -- same as before

main = do
    args <- cmdArgs gendiff
    case args of
        Gendiff { files = [first, second] } -> -- success path
        _ -> -- print an error

Upvotes: 1

Related Questions