module System.IO.Silently (
silence, hSilence,
capture, hCapture
) where
import GHC.IO.Handle (hDuplicate, hDuplicateTo)
import System.IO (Handle, stdout, hClose, openTempFile)
import Control.Exception (bracket)
import System.Directory (removeFile)
silence :: IO a -> IO a
silence = hSilence [stdout]
hSilence :: [Handle] -> IO a -> IO a
hSilence handles action = do
oldHandles <- mapM hDuplicate handles
bracket (openTempFile "." "silence")
(\(tmpFile, tmpHandle) -> do sequence_ $ zipWith hDuplicateTo oldHandles handles
hClose tmpHandle
removeFile tmpFile)
(\(_, tmpHandle) -> do mapM_ (hDuplicateTo tmpHandle) handles
action)
capture :: IO a -> IO (String, a)
capture = hCapture [stdout]
hCapture :: [Handle] -> IO a -> IO (String, a)
hCapture handles action = do
oldHandles <- mapM hDuplicate handles
bracket (openTempFile "." "capture")
(\(tmpFile, tmpHandle) -> do sequence_ $ zipWith hDuplicateTo oldHandles handles
hClose tmpHandle
removeFile tmpFile)
(\(tmpFile, tmpHandle) -> do mapM_ (hDuplicateTo tmpHandle) handles
a <- action
hClose tmpHandle
str <- readFile tmpFile
return (str, a))