module Control.Monad.Trans.Either.Exit (
    orDie
  , orDieWithCode
  ) where

import           Data.Text (Text)
import qualified Data.Text as T

import           System.Exit (ExitCode(..), exitWith)
import           System.IO (stderr, hPutStrLn)

import           Control.Monad.Trans.Either

-- | orDieWithCode with an exit code of 1 in case of an error
--
orDie :: (e -> Text) -> EitherT e IO a -> IO a
orDie :: forall e a. (e -> Text) -> EitherT e IO a -> IO a
orDie = forall e a. Int -> (e -> Text) -> EitherT e IO a -> IO a
orDieWithCode Int
1

-- | An idiom for failing hard on EitherT errors.
--
-- *This really dies*. There is no other way to say it.
--
-- The reason it lives with command line parser tooling, is that it is
-- the only valid place to actually exit like this. Be appropriately
-- wary.
--
orDieWithCode :: Int -> (e -> Text) -> EitherT e IO a -> IO a
orDieWithCode :: forall e a. Int -> (e -> Text) -> EitherT e IO a -> IO a
orDieWithCode Int
code e -> Text
render EitherT e IO a
e =
  forall x (m :: * -> *) a. EitherT x m a -> m (Either x a)
runEitherT EitherT e IO a
e forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>=
    forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (\e
err -> (Handle -> String -> IO ()
hPutStrLn Handle
stderr forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> String
T.unpack forall b c a. (b -> c) -> (a -> b) -> a -> c
. e -> Text
render) e
err forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> forall a. ExitCode -> IO a
exitWith (Int -> ExitCode
ExitFailure Int
code)) forall (f :: * -> *) a. Applicative f => a -> f a
pure