module Darcs.Util.Exception
( firstJustIO
, catchall
, clarifyErrors
, prettyException
, prettyError
, die
) where
import Prelude ()
import Darcs.Prelude
import Control.Exception ( SomeException, Exception(fromException), catch )
import Data.Maybe ( isJust )
import System.Exit ( exitFailure )
import System.IO ( stderr, hPutStrLn )
import System.IO.Error ( isUserError, ioeGetErrorString
, isDoesNotExistError, ioeGetFileName )
import Darcs.Util.SignalHandler ( catchNonSignal )
catchall :: IO a
-> IO a
-> IO a
a `catchall` b = a `catchNonSignal` (\_ -> b)
firstJustM :: Monad m
=> [m (Maybe a)]
-> m (Maybe a)
firstJustM [] = return Nothing
firstJustM (e:es) = e >>= (\v -> if isJust v then return v else firstJustM es)
firstJustIO :: [IO (Maybe a)]
-> IO (Maybe a)
firstJustIO = firstJustM . map (`catchall` return Nothing)
clarifyErrors :: IO a
-> String
-> IO a
clarifyErrors a e = a `catch` (\x -> die $ unlines [prettyException x,e])
prettyException :: SomeException
-> String
prettyException e | Just ioe <- fromException e, isUserError ioe = ioeGetErrorString ioe
prettyException e | Just ioe <- fromException e, isDoesNotExistError ioe =
case ioeGetFileName ioe of
Just f -> f ++ " does not exist"
Nothing -> show e
prettyException e = show e
prettyError :: IOError -> String
prettyError e | isUserError e = ioeGetErrorString e
| otherwise = show e
die :: String -> IO a
die msg = hPutStrLn stderr msg >> exitFailure