htools: add a machine-readable CLI flag
authorIustin Pop <iustin@google.com>
Fri, 8 Jul 2011 11:07:21 +0000 (13:07 +0200)
committerIustin Pop <iustin@google.com>
Tue, 19 Jul 2011 15:17:42 +0000 (17:17 +0200)
This will be used in hspace to toggle between "human" readable
and machine readable output formats.

Signed-off-by: Iustin Pop <iustin@google.com>
Reviewed-by: Guido Trotter <ultrotter@google.com>

htools/Ganeti/HTools/CLI.hs

index 464afe8..605fff6 100644 (file)
@@ -51,6 +51,7 @@ module Ganeti.HTools.CLI
     , oIVcpus
     , oInstMoves
     , oLuxiSocket
+    , oMachineReadable
     , oMaxCpu
     , oMaxSolLength
     , oMinDisk
@@ -115,6 +116,7 @@ data Options = Options
     , optSelInst     :: [String]       -- ^ Instances to be excluded
     , optISpec       :: RSpec          -- ^ Requested instance specs
     , optLuxi        :: Maybe FilePath -- ^ Collect data from Luxi
+    , optMachineReadable :: Bool       -- ^ Output machine-readable format
     , optMaster      :: String         -- ^ Collect data from RAPI
     , optMaxLength   :: Int            -- ^ Stop after this many steps
     , optMcpu        :: Double         -- ^ Max cpu ratio for nodes
@@ -154,6 +156,7 @@ defaultOptions  = Options
  , optSelInst     = []
  , optISpec       = RSpec 1 4096 102400
  , optLuxi        = Nothing
+ , optMachineReadable = False
  , optMaster      = ""
  , optMaxLength   = -1
  , optMcpu        = defVcpuRatio
@@ -277,6 +280,15 @@ oLuxiSocket = Option "L" ["luxi"]
                        fromMaybe defaultLuxiSocket) "SOCKET")
               "collect data via Luxi, optionally using the given SOCKET path"
 
+oMachineReadable :: OptType
+oMachineReadable = Option "" ["machine-readable"]
+          (OptArg (\ f opts -> do
+                     flag <- parseYesNo True f
+                     return $ opts { optMachineReadable = flag }) "CHOICE")
+          "enable machine readable output (pass either 'yes' or 'no' to\
+          \ explicitely control the flag, or without an argument defaults to\
+          \ yes"
+
 oMaxCpu :: OptType
 oMaxCpu = Option "" ["max-cpu"]
           (ReqArg (\ n opts -> Ok opts { optMcpu = read n }) "RATIO")
@@ -416,6 +428,16 @@ oVerbose = Option "v" ["verbose"]
 
 -- * Functions
 
+-- | Helper for parsing a yes\/no command line flag.
+parseYesNo :: Bool         -- ^ Default whalue (when we get a @Nothing@)
+           -> Maybe String -- ^ Parameter value
+           -> Result Bool  -- ^ Resulting boolean value
+parseYesNo v Nothing      = return v
+parseYesNo _ (Just "yes") = return True
+parseYesNo _ (Just "no")  = return False
+parseYesNo _ (Just s)     = fail $ "Invalid choice '" ++ s ++
+                            "', pass one of 'yes' or 'no'"
+
 -- | Usage info.
 usageHelp :: String -> [OptType] -> String
 usageHelp progname =