Begin working on determining the article argument type.
[dead/lwn-epub.git] / src / CommandLine.hs
1 {-# LANGUAGE DeriveDataTypeable #-}
2
3 module CommandLine (Args(..), apply_args, show_help)
4 where
5
6 -- Get the version from Cabal.
7 import Paths_lwn_epub (version)
8 import Data.Version (showVersion)
9
10 import Data.String.Utils (startswith)
11 import System.Console.CmdArgs (
12 CmdArgs,
13 Data,
14 Mode,
15 Typeable,
16 (&=),
17 argPos,
18 cmdArgsApply,
19 cmdArgsMode,
20 def,
21 details,
22 help,
23 program,
24 typ,
25 typFile,
26 summary
27 )
28
29 import System.Console.CmdArgs.Explicit (process)
30 import System.Environment (getArgs, withArgs)
31 import System.Exit (ExitCode(..), exitWith)
32 import System.IO (hPutStrLn, stderr)
33
34 import ExitCodes
35
36
37
38 data Args =
39 Args { output :: FilePath,
40 article :: String }
41 deriving (Show, Data, Typeable)
42
43
44 description :: String
45 description = "Convert LWN articles to EPUB format."
46
47 program_name :: String
48 program_name = "lwn_epub"
49
50 lwn_epub_summary :: String
51 lwn_epub_summary =
52 program_name ++ "-" ++ (showVersion version)
53
54 output_help :: String
55 output_help = "Output file, defaults to stdout"
56
57 arg_spec :: Mode (CmdArgs Args)
58 arg_spec = cmdArgsMode $
59 Args {
60 output = def &= typFile &= help output_help,
61 article = def &= argPos 0 &= typ "ARTICLE"
62 }
63 &= program program_name
64 &= summary lwn_epub_summary
65 &= details [description]
66
67
68 -- Infix notation won't work, the arguments are backwards!
69 is_missing_arg_error :: String -> Bool
70 is_missing_arg_error s =
71 startswith "Requires at least" s
72
73
74 show_help :: IO (CmdArgs Args)
75 show_help = withArgs ["--help"] parse_args
76
77 parse_args :: IO (CmdArgs Args)
78 parse_args = do
79 x <- getArgs
80 let y = process arg_spec x
81 case y of
82 Right result -> return result
83 Left err ->
84 if (is_missing_arg_error err) then
85 -- Disregard the error message, show help instead.
86 show_help
87 else do
88 hPutStrLn stderr err
89 exitWith (ExitFailure exit_args_parse_failed)
90
91
92 -- | Really get the command-line arguments. This calls 'parse_args'
93 -- first to replace the default "wrong number of arguments" error,
94 -- and then runs 'cmdArgsApply' on the result to do what the
95 -- 'cmdArgs' function usually does.
96 apply_args :: IO Args
97 apply_args =
98 parse_args >>= cmdArgsApply