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