diff --git a/posix/System/File/Platform.hs b/posix/System/File/Platform.hs index ed35709..a3e3d05 100644 --- a/posix/System/File/Platform.hs +++ b/posix/System/File/Platform.hs @@ -1,5 +1,10 @@ +{-# LANGUAGE LambdaCase #-} + module System.File.Platform where +import GHC.IO +import GHC.IO.Exception +import Control.Exception (try) import System.IO (IOMode(..), Handle) import System.Posix.IO.PosixString ( defaultFileFlags, @@ -30,3 +35,21 @@ openExistingFile fp iomode = fdToHandle =<< case iomode of where open = openFd fp df = defaultFileFlags { noctty = True, nonBlock = True, creat = Nothing } + +withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r +withFile fp im act = + -- Only annotate when setup or teardown of withFile' raised the exception + catchException + (withFile' fp im undefined True (try . act)) + (\e -> ioError (addFilePathToIOError "withFile" fp e)) + >>= \case + Left e -> ioError e + Right x -> pure x + +addFilePathToIOError :: String -> FilePath -> IOException -> IOException +addFilePathToIOError fun fp ioe + = ioe{ ioe_location = fun, ioe_filename = Just fp } + +withFile' :: String -> IOMode -> Bool -> Bool -> (Handle -> IO r) -> IO r +withFile' = undefined +