module System.IO.Silently (
silently, hSilently, capture, hCapture
) where
import GHC.IO.Handle
import System.IO
import Control.Exception (bracket)
import System.Directory
silently :: IO a -> IO a
silently = hSilently stdout
hSilently :: Handle -> IO a -> IO a
hSilently handle action = do
oldHandle <- hDuplicate handle
bracket (openTempFile "." "silently")
(\(tmpFile, tmpHandle) -> do hDuplicateTo oldHandle handle
hClose tmpHandle
removeFile tmpFile)
(\(_, tmpHandle) -> do hDuplicateTo tmpHandle handle
action)
capture :: IO a -> IO (String, a)
capture = hCapture stdout
hCapture :: Handle -> IO a -> IO (String, a)
hCapture handle action = do
oldHandle <- hDuplicate handle
bracket (openTempFile "." "silently")
(\(tmpFile, tmpHandle) -> do hDuplicateTo oldHandle handle
hClose tmpHandle
removeFile tmpFile)
(\(tmpFile, tmpHandle) -> do hDuplicateTo tmpHandle handle
a <- action
hClose tmpHandle
str <- readFile tmpFile
return (str, a))