silently 0.0.1 → 0.0.2
raw patch · 2 files changed
+37/−10 lines, 2 files
Files
- silently.cabal +3/−3
- src/System/IO/Silently.hs +34/−7
silently.cabal view
@@ -1,5 +1,5 @@ name: silently-version: 0.0.1+version: 0.0.2 cabal-version: -any build-type: Simple license: BSD3@@ -11,8 +11,8 @@ homepage: https://github.com/trystan/silently package-url: https://github.com/trystan/silently bug-reports: https://github.com/trystan/silently/issues-synopsis: Prevent writing to stdout in Haskel.-description: Prevent writing to stdout in Haskel.+synopsis: Prevent or capture writing to stdout.+description: Prevent or capture writing to stdout, or any given handle. category: author: Trystan Spangler tested-with: GHC ==7.0
src/System/IO/Silently.hs view
@@ -1,21 +1,48 @@ +-- | Need to prevent output to the terminal or stderr? Need to capture it and use it for your own means? Now you can, with 'silently' and 'capture'.+ module System.IO.Silently (- silently, hSilently+ silently, hSilently, capture, hCapture ) where import GHC.IO.Handle import System.IO-import Control.Exception (finally)+import Control.Exception (bracket) import System.Directory --- | Run an IO action while ignoring all output to stdout.+-- | Run an IO action while preventing all output to stdout.+-- This will, as a side effect, create and delete a temp file in the current directory. silently :: IO a -> IO a silently = hSilently stdout --- | Run an IO action while ignoring all output to the given handle.+-- | Run an IO action while preventing all output to the given handle.+-- This will, as a side effect, create and delete a temp file in the current directory. hSilently :: Handle -> IO a -> IO a hSilently handle action = do oldHandle <- hDuplicate handle- (tmpFile, tmpHandle) <- openTempFile "." "silently"- hDuplicateTo tmpHandle handle- finally action (hDuplicateTo oldHandle handle >> hClose tmpHandle >> removeFile tmpFile)+ bracket (openTempFile "." "silently")+ (\(tmpFile, tmpHandle) -> do hDuplicateTo oldHandle handle+ hClose tmpHandle+ removeFile tmpFile)+ (\(_, tmpHandle) -> do hDuplicateTo tmpHandle handle+ action)++-- | Run an IO action while preventing and capturing all output to stdout.+-- This will, as a side effect, create and delete a temp file in the current directory.+capture :: IO a -> IO (String, a)+capture = hCapture stdout++-- | Run an IO action while preventing and capturing all output to the given handle.+-- This will, as a side effect, create and delete a temp file in the current directory.+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))