Combine ArticlePage and FullPage into one Page type.
[dead/lwn-epub.git] / src / CommandLine.hs
1 {-# LANGUAGE DeriveDataTypeable #-}
2
3 module CommandLine (Args(..), apply_args)
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 parse_args :: IO (CmdArgs Args)
75 parse_args = do
76 x <- getArgs
77 let y = process arg_spec x
78 case y of
79 Right result -> return result
80 Left err ->
81 if (is_missing_arg_error err) then
82 -- Disregard the error message, show help instead.
83 withArgs ["--help"] parse_args
84 else do
85 hPutStrLn stderr err
86 exitWith (ExitFailure exit_args_parse_failed)
87
88
89 -- | Really get the command-line arguments. This calls 'parse_args'
90 -- first to replace the default "wrong number of arguments" error,
91 -- and then runs 'cmdArgsApply' on the result to do what the
92 -- 'cmdArgs' function usually does.
93 apply_args :: IO Args
94 apply_args =
95 parse_args >>= cmdArgsApply