ba16766e4f98c344585d669ff64f4826cceadb5e
[ganeti-local] / Ganeti / HTools / CLI.hs
1 {-| Implementation of command-line functions.
2
3 This module holds the common cli-related functions for the binaries,
4 separated into this module since Utils.hs is used in many other places
5 and this is more IO oriented.
6
7 -}
8
9 module Ganeti.HTools.CLI
10     (
11       parseOpts
12     , showVersion
13     ) where
14
15 import System.Console.GetOpt
16 import System.IO
17 import System.Info
18 import System
19 import Monad
20 import Text.Printf (printf)
21 import qualified Data.Version
22
23 import qualified Ganeti.HTools.Version as Version(version)
24
25 -- | Command line parser, using the 'options' structure.
26 parseOpts :: [String]            -- ^ The command line arguments
27           -> String              -- ^ The program name
28           -> [OptDescr (b -> b)] -- ^ The supported command line options
29           -> b                   -- ^ The default options record
30           -> (b -> Bool)         -- ^ The function which given the options
31                                  -- tells us whether we need to show help
32           -> IO (b, [String])    -- ^ The resulting options a leftover
33                                  -- arguments
34 parseOpts argv progname options defaultOptions fn =
35     case getOpt Permute options argv of
36       (o, n, []) ->
37           do
38             let resu@(po, _) = (foldl (flip id) defaultOptions o, n)
39             when (fn po) $ do
40               putStr $ usageInfo header options
41               exitWith ExitSuccess
42             return resu
43       (_, _, errs) ->
44           ioError (userError (concat errs ++ usageInfo header options))
45       where header = printf "%s %s\nUsage: %s [OPTION...]"
46                      progname Version.version progname
47
48
49 -- | Return a version string for the program
50 showVersion :: String -- ^ The program name
51             -> String -- ^ The formatted version and other information data
52 showVersion name =
53     printf "%s %s\ncompiled with %s %s\nrunning on %s %s\n"
54            name Version.version
55            compilerName (Data.Version.showVersion compilerVersion)
56            os arch