ghcup-hs/lib/GHCup/Prelude.hs

80 lines
2.1 KiB
Haskell
Raw Normal View History

2020-01-14 21:55:34 +00:00
{-# OPTIONS_GHC -Wno-orphans #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module GHCup.Prelude where
import Control.Applicative
2020-01-16 22:27:38 +00:00
import Control.Monad
2020-01-17 22:29:16 +00:00
import Control.Exception.Safe
import qualified Data.Strict.Maybe as S
2020-01-14 21:55:34 +00:00
import Data.Monoid ( (<>) )
2020-01-16 22:27:38 +00:00
import Data.String
import qualified Data.Text.Lazy.Encoding as TLE
import qualified Data.Text.Lazy as TL
import Data.Text ( Text )
import qualified Data.ByteString.Lazy as L
2020-01-17 22:29:16 +00:00
import System.IO.Error
2020-01-16 22:27:38 +00:00
2020-01-14 21:55:34 +00:00
2020-01-17 22:29:16 +00:00
fS :: IsString a => String -> a
2020-01-14 21:55:34 +00:00
fS = fromString
2020-01-17 22:29:16 +00:00
fromStrictMaybe :: S.Maybe a -> Maybe a
fromStrictMaybe = S.maybe Nothing Just
2020-01-14 21:55:34 +00:00
2020-01-17 22:29:16 +00:00
fSM :: S.Maybe a -> Maybe a
2020-01-16 22:27:38 +00:00
fSM = fromStrictMaybe
2020-01-17 22:29:16 +00:00
toStrictMaybe :: Maybe a -> S.Maybe a
toStrictMaybe = maybe S.Nothing S.Just
2020-01-14 21:55:34 +00:00
2020-01-17 22:29:16 +00:00
tSM :: Maybe a -> S.Maybe a
2020-01-16 22:27:38 +00:00
tSM = toStrictMaybe
2020-01-17 22:29:16 +00:00
internalError :: String -> IO a
internalError = fail . ("Internal error: " <>)
2020-01-14 21:55:34 +00:00
2020-01-17 22:29:16 +00:00
iE :: String -> IO a
iE = internalError
2020-01-14 21:55:34 +00:00
-- | Like 'when', but where the test can be monadic.
whenM :: Monad m => m Bool -> m () -> m ()
whenM ~b ~t = ifM b t (return ())
-- | Like 'unless', but where the test can be monadic.
unlessM :: Monad m => m Bool -> m () -> m ()
unlessM ~b ~f = ifM b (return ()) f
-- | Like @if@, but where the test can be monadic.
ifM :: Monad m => m Bool -> m a -> m a -> m a
ifM ~b ~t ~f = do
b' <- b
if b' then t else f
2020-01-16 22:27:38 +00:00
whileM :: Monad m => m a -> (a -> m Bool) -> m a
whileM ~action ~f = do
a <- action
b' <- f a
if b' then whileM action f else pure a
2020-01-14 21:55:34 +00:00
whileM_ :: Monad m => m a -> (a -> m Bool) -> m ()
2020-01-16 22:27:38 +00:00
whileM_ ~action = void . whileM action
guardM :: (Monad m, Alternative m) => m Bool -> m ()
2020-01-17 00:50:12 +00:00
guardM ~f = guard =<< f
2020-01-14 21:55:34 +00:00
2020-01-16 22:27:38 +00:00
lBS2sT :: L.ByteString -> Text
lBS2sT = TL.toStrict . TLE.decodeUtf8
2020-01-17 22:29:16 +00:00
handleIO' :: IOErrorType -> (IOException -> IO ()) -> IO () -> IO ()
handleIO' err handler =
handleIO (\e -> if err == ioeGetErrorType e then handler e else ioError e)
hideError :: IOErrorType -> IO () -> IO ()
hideError err = handleIO (\e -> if err == ioeGetErrorType e then pure () else ioError e)