liblawless-0.16.1: Source/Temporary.hs
{-|
Module: Temporary
Description: Temporary file handling.
Copyright: © 2016 All rights reserved.
License: GPL-3
Maintainer: Evan Cofsky <evan@theunixman.com>
Stability: experimental
Portability: POSIX
-}
module Temporary (withTempHandle) where
import Lawless hiding ((<.>))
import qualified System.IO.Temp as T
import Control.Monad.IO.Class
import System.IO
import Control.Monad.Catch
import Path
-- | Run a function with a temporary file handle named after the
-- passed name. Ensures the handle is unbuffered and in binary mode.
withTempHandle ∷ (MonadIO m, MonadMask m) ⇒ RelFile → (Handle → m a) → m a
withTempHandle name f =
T.withSystemTempFile ((toString name) <> "XXXXXXXXXXXXXXXX")
$ \_ h →
-- Make sure the handle is strictly binary with no buffering.
liftIO (hSetBuffering h NoBuffering) >>
liftIO (hSetBinaryMode h True) >>
f h