{-|
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 System.FilePath

-- | 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)  FilePath  (Handle  m a)  m a
withTempHandle name f =
    T.withSystemTempFile (name <> "XXXXXXXXXXXXXXXX")
    $ \_ h 
          -- Make sure the handle is strictly binary with no buffering.
          liftIO (hSetBuffering h NoBuffering) >>
          liftIO (hSetBinaryMode h True) >>
          f h