packages feed

papa-0.7.0: src/Papa/Lens/System/IO/Error.hs

{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}

-- | 'IOException's as optics: lenses on their fields ('errorType',
-- 'location', 'description', 'fileName', 'errno', 'errorHandle') and a prism
-- for each kind of error ('_NoSuchThing', '_PermissionDenied',
-- '_AlreadyExists', '_EOF', …), for the 'IOException' that
-- 'Papa.Base.System.IO.Except.IOExcept' returns.
--
-- > has (errorType . _NoSuchThing)
--
-- "System.IO.Error.Lens"'s @handle@ is exported as 'errorHandle': "Papa"'s
-- 'Papa.Base.Control.Exception.handle' catches.
--
-- @since 0.7.0
module Papa.Lens.System.IO.Error (
  module P,
  errorHandle,
) where

import Control.Exception (IOException)
import Control.Lens (Lens')
import Data.Maybe (Maybe)
import System.IO (Handle)
import System.IO.Error.Lens as P hiding (handle)
import qualified System.IO.Error.Lens as L

-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> import Papa
-- >>> import qualified Papa.Unsafe.IO as U
-- >>> import Hedgehog
-- >>> import qualified Hedgehog.Gen as Gen

-- | The handle of an 'IOException', if it has one: "System.IO.Error.Lens"'s
-- @handle@.
--
-- ==== __Examples__
--
-- >>> the errorHandle (userError "u")
-- Nothing
--
-- >>> do { h <- U.openFile "/dev/null" U.WriteMode; U.hClose h; e <- runExceptT (hFlush h); pure (fmap (the errorHandle) (preview (_Left . _IOException) e) == Just (Just h)) }
-- True
--
-- >>> check $ withTests 10 $ property $ do b <- forAll Gen.bool; let { h = bool Nothing (Just stdout) b }; the errorHandle (set errorHandle h (userError "u")) === h
-- ...passed 10 tests.
-- True
--
-- @since 0.7.0
errorHandle :: Lens' IOException (Maybe Handle)
errorHandle =
  L.handle
{-# INLINE errorHandle #-}