packages feed

papa-0.7.0: src/Papa/Base/System/IO/Except.hs

{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}

-- | I/O actions whose expected failures are values, not exceptions.
--
-- An action of type @'IOExcept' a@ returns its failure as a
-- 'Data.Either.Left' of 'Control.Monad.Trans.Except.runExceptT': an
-- 'IOFailure', which is either the 'IOException' of the operating system
-- (file not found, permission denied, a closed handle, …) or the
-- 'UnicodeException' of bytes that are not UTF-8.
--
-- The prism '_IOFailed' (or 'Control.Exception.Lens._IOException') and the
-- classy prisms of "System.IO.Error.Lens" ('System.IO.Error.Lens.errorType',
-- 'System.IO.Error.Lens._NoSuchThing', …) take an 'IOException' apart;
-- '_DecodeFailed' a decoding failure.
--
-- It catches only 'IOException', which is synchronous: asynchronous
-- exceptions ('Control.Exception.killThread', 'System.Timeout.timeout') pass
-- through, as they must.
--
-- @since 0.7.0
module Papa.Base.System.IO.Except (
  -- * Failure
  IOFailure (IOFailed, DecodeFailed),
  _IOFailed,
  _DecodeFailed,

  -- * Classy optics
  GetIOFailure (getIOFailure),
  HasIOFailure (setIOFailure, ioFailure),
  ReviewIOFailure (reviewIOFailure),
  AsIOFailure (matchIOFailure, _IOFailure),

  -- * Actions
  IOExcept,
  exceptIO,
) where

import Control.Category (id)
import Control.Exception (Exception (displayException, fromException, toException), IOException, SomeException, try)
import Control.Exception.Lens (AsIOException (_IOException))
import Control.Lens (Getter, Lens', Prism', Review, lens, prism, prism', review, unto, view)
import Control.Monad.Trans.Except (ExceptT (ExceptT))
import Data.Bifunctor (first)
import Data.Either (Either (Left, Right), either)
import Data.Eq (Eq)
import Data.Function (flip, (.))
import Data.Functor (fmap)
import Data.Maybe (Maybe (Just, Nothing))
import Data.Monoid ((<>))
import Data.Text.Encoding.Error (UnicodeException)
import Data.Tuple (uncurry)
import GHC.Generics (Generic)
import System.IO (FilePath, Handle, IO)
import Text.Show (Show (show))

-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> import Papa
-- >>> import qualified System.IO as IO
-- >>> import qualified System.IO.Error as IO
-- >>> import Data.Text.Encoding.Error (UnicodeException (DecodeError))

-- | The failure of an I/O action: an 'IOException' of the operating system,
-- or bytes that are not UTF-8, read from a handle or a file.
--
-- ==== __Examples__
--
-- >>> runExceptT (exceptIO (IO.readFile "/nonexistent/papa"))
-- Left (IOFailed /nonexistent/papa: openFile: does not exist (No such file or directory))
--
-- >>> displayException (DecodeFailed (Right "f.txt") (DecodeError "bad" Nothing))
-- "f.txt: Cannot decode input: bad"
--
-- @since 0.7.0
data IOFailure
  = -- | An 'IOException' of the operating system.
    IOFailed IOException
  | -- | Bytes that are not UTF-8, read from a handle ('Left') or a file
    -- ('Right').
    DecodeFailed (Either Handle FilePath) UnicodeException
  deriving stock (Eq, Show, Generic)

-- | 'displayException' is that of the 'IOException', or the handle or file and the
-- decoding error.
--
-- @since 0.7.0
instance Exception IOFailure where
  displayException (IOFailed e) =
    displayException e
  displayException (DecodeFailed w e) =
    either show id w <> ": " <> displayException e

-- | The 'IOException' of an 'IOFailure'.
--
-- ==== __Examples__
--
-- >>> either (preview _IOFailed) (const Nothing) <$> runExceptT (exceptIO (IO.readFile "/nonexistent/papa"))
-- Just /nonexistent/papa: openFile: does not exist (No such file or directory)
--
-- >>> preview _IOFailed (DecodeFailed (Right "f.txt") (DecodeError "bad" Nothing))
-- Nothing
--
-- @since 0.7.0
_IOFailed :: Prism' IOFailure IOException
_IOFailed =
  prism'
    IOFailed
    ( \case
        IOFailed e -> Just e
        DecodeFailed _ _ -> Nothing
    )
{-# INLINE _IOFailed #-}

-- | The handle or file, and the decoding error, of an 'IOFailure'.
--
-- ==== __Examples__
--
-- >>> preview _DecodeFailed (DecodeFailed (Right "f.txt") (DecodeError "bad" Nothing))
-- Just (Right "f.txt",Cannot decode input: bad)
--
-- @since 0.7.0
_DecodeFailed :: Prism' IOFailure (Either Handle FilePath, UnicodeException)
_DecodeFailed =
  prism
    (uncurry DecodeFailed)
    ( \x -> case x of
        DecodeFailed w e -> Right (w, e)
        IOFailed _ -> Left x
    )
{-# INLINE _DecodeFailed #-}

-- | An 'IOFailure' is an 'IOException' by '_IOFailed', so that the classy
-- prisms of "System.IO.Error.Lens" apply to it.
--
-- ==== __Examples__
--
-- >>> either (anyOf _IOException (\i -> has _NoSuchThing (the errorType i))) (const False) <$> runExceptT (exceptIO (IO.readFile "/nonexistent/papa"))
-- True
--
-- @since 0.7.0
instance AsIOException IOFailure where
  _IOException =
    _IOFailed
  {-# INLINE _IOException #-}

-- | Values from which an 'IOFailure' can be viewed.
--
-- @since 0.7.0
class GetIOFailure s where
  getIOFailure :: Getter s IOFailure

-- | @since 0.7.0
instance GetIOFailure IOFailure where
  getIOFailure =
    id
  {-# INLINE getIOFailure #-}

-- | Values with a lens into an 'IOFailure'.
--
-- @since 0.7.0
class (GetIOFailure s) => HasIOFailure s where
  {-# MINIMAL setIOFailure #-}
  setIOFailure :: IOFailure -> s -> s
  ioFailure :: Lens' s IOFailure
  ioFailure =
    lens (view getIOFailure) (flip setIOFailure)
  {-# INLINE ioFailure #-}

-- | @since 0.7.0
instance HasIOFailure IOFailure where
  setIOFailure x _ =
    x
  {-# INLINE setIOFailure #-}

-- | Values that can be built from an 'IOFailure'.
--
-- @since 0.7.0
class ReviewIOFailure t where
  reviewIOFailure :: Review t IOFailure

-- | @since 0.7.0
instance ReviewIOFailure IOFailure where
  reviewIOFailure =
    unto id
  {-# INLINE reviewIOFailure #-}

-- | @since 0.7.0
instance ReviewIOFailure SomeException where
  reviewIOFailure =
    unto toException
  {-# INLINE reviewIOFailure #-}

-- | Values with a prism into an 'IOFailure': an error type of a program's own
-- with an 'IOFailure' among its cases.
--
-- ==== __Examples__
--
-- >>> matchIOFailure (toException (IOFailed (IO.userError "x")))
-- Just (IOFailed user error (x))
--
-- @since 0.7.0
class (ReviewIOFailure t) => AsIOFailure t where
  {-# MINIMAL matchIOFailure #-}
  matchIOFailure :: t -> Maybe IOFailure
  _IOFailure :: Prism' t IOFailure
  _IOFailure =
    prism' (review reviewIOFailure) matchIOFailure
  {-# INLINE _IOFailure #-}

-- | @since 0.7.0
instance AsIOFailure IOFailure where
  matchIOFailure =
    Just
  {-# INLINE matchIOFailure #-}

-- | @since 0.7.0
instance AsIOFailure SomeException where
  matchIOFailure =
    fromException
  {-# INLINE matchIOFailure #-}

-- | An I/O action that returns its 'IOFailure' instead of throwing it.
--
-- @since 0.7.0
type IOExcept =
  ExceptT IOFailure IO

-- | Return the 'IOException' that an I/O action throws as a
-- 'Data.Either.Left', instead of throwing it. Other exceptions are not
-- caught.
--
-- ==== __Examples__
--
-- >>> runExceptT (exceptIO (IO.readFile "/nonexistent/papa"))
-- Left (IOFailed /nonexistent/papa: openFile: does not exist (No such file or directory))
--
-- >>> either (anyOf _IOException IO.isDoesNotExistError) (const False) <$> runExceptT (exceptIO (IO.readFile "/nonexistent/papa"))
-- True
--
-- >>> runExceptT (exceptIO (pure 3))
-- Right 3
--
-- @since 0.7.0
exceptIO :: IO a -> IOExcept a
exceptIO =
  ExceptT . fmap (first IOFailed) . try
{-# INLINE exceptIO #-}