module System.IO.Fake where
import Control.DeepSeq
import Control.Exception
import GHC.IO.Handle
import System.Directory
import System.IO
withTempFile
:: FilePath
-> String
-> ((FilePath,Handle) -> IO a)
-> IO a
withTempFile tmpDir base k = bracket
(openTempFile tmpDir base)
(\(file,h) -> hClose h >> removeFile file)
k
withRedirect
:: Handle
-> Handle
-> IO a
-> IO a
withRedirect new old act = bracket
(do buffering <- hGetBuffering old
dupH <- hDuplicate old
hDuplicateTo new old
return (dupH,buffering)
)
(\(dupH,buffering) -> do
hDuplicateTo dupH old
hSetBuffering old buffering
hClose dupH
)
(\_ -> act)
fakeIO
:: IO a
-> String
-> IO String
fakeIO act inp = do
tmpDir <- getTemporaryDirectory
withTempFile tmpDir "fakeInput" $ \(inpFile,inpH) ->
withTempFile tmpDir "fakeOutput" $ \(outFile,outH) -> do
withRedirect outH stdout $
withRedirect inpH stdin $ do
hPutStr inpH inp
hSeek inpH AbsoluteSeek 0
act
hFlush stdout
hSeek outH AbsoluteSeek 0
str <- hGetContents outH
str `deepseq` return str