Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

preserve handle buffering #20

Merged
merged 1 commit into from
Jul 13, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions silently.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ test-suite spec-specific
, silently
, directory
, nanospec
, temporary

-- This tests the generic implementation, that should work on all platforms.
test-suite spec-generic
Expand All @@ -76,3 +77,4 @@ test-suite spec-generic
, deepseq
, directory
, nanospec
, temporary
16 changes: 11 additions & 5 deletions src/System/IO/Silently.hs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,14 @@ hCapture handles action = do
go hs = goBracket go tmpHandle hs

goBracket :: ([Handle] -> IO a) -> Handle -> [Handle] -> IO a
goBracket go tmpHandle (h:hs) = E.bracket (do old <- hDuplicate h
hDuplicateTo tmpHandle h
return old)
(\old -> hDuplicateTo old h >> hClose old)
(\_ -> go hs)
goBracket go tmpHandle (h:hs) = do
buffering <- hGetBuffering h
let redirect = do
old <- hDuplicate h
hDuplicateTo tmpHandle h
return old
restore old = do
hDuplicateTo old h
hSetBuffering h buffering
hClose old
E.bracket redirect restore (\_ -> go hs)
10 changes: 10 additions & 0 deletions test/Spec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import Test.Hspec
import System.IO
import System.IO.Silently
import System.Directory
import System.IO.Temp

import Control.Exception
import Control.Monad

main :: IO ()
main = hspec spec
Expand All @@ -26,3 +28,11 @@ spec = do
describe "capture" $ do
it "captures stdout" $ do
capture (putStr "foo" >> return 23) `shouldReturn` ("foo", 23 :: Int)

describe "hCapture" $ do
forM_ [NoBuffering, LineBuffering, BlockBuffering Nothing] $ \buffering -> do
it ("preserves " ++ show buffering) $ do
withSystemTempFile "silently" $ \_file h -> do
hSetBuffering h buffering
_ <- hCapture [h] (return ())
hGetBuffering h `shouldReturn` buffering