Add logWarningIfBad, a utility function similar to exitIfBad, that logs a
warning and returns a default value instead of just crashing the program if
the unpacked value is Bad.

Signed-off-by: Michele Tartara <[email protected]>
---
 src/Ganeti/Utils.hs |   10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/src/Ganeti/Utils.hs b/src/Ganeti/Utils.hs
index 51aa671..026db21 100644
--- a/src/Ganeti/Utils.hs
+++ b/src/Ganeti/Utils.hs
@@ -43,6 +43,7 @@ module Ganeti.Utils
   , exitErr
   , exitWhen
   , exitUnless
+  , logWarningIfBad
   , rStripSpace
   , newUUID
   , getCurrentTime
@@ -69,6 +70,7 @@ import Debug.Trace
 
 import Ganeti.BasicTypes
 import qualified Ganeti.Constants as C
+import Ganeti.Logging
 import Ganeti.Runtime
 import System.IO
 import System.Exit
@@ -252,6 +254,14 @@ exitWhen False _  = return ()
 exitUnless :: Bool -> String -> IO ()
 exitUnless cond = exitWhen (not cond)
 
+-- | Unwraps a 'Result', logging a warning message and then returning a default
+-- value if it is a 'Bad' value, otherwise returning the actual contained 
value.
+logWarningIfBad :: String -> a -> Result a -> IO a
+logWarningIfBad msg defVal (Bad s) = do
+  logWarning $ msg ++ ": " ++ s
+  return defVal
+logWarningIfBad _ _ (Ok v) = return v
+
 -- | Print a warning, but do not exit.
 warn :: String -> IO ()
 warn = hPutStrLn stderr . (++) "Warning: "
-- 
1.7.10.4

Reply via email to