{-# LANGUAGE PackageImports #-}
-- |Domain independent functions used by the haskell-debian package.
module Debian.Extra.Files
    ( withTemporaryFile
    ) where

import "mtl" Control.Monad.Trans (MonadIO, liftIO)
import System.Directory (getTemporaryDirectory, removeFile)
import System.IO (hPutStr, hClose, openBinaryTempFile)

withTemporaryFile :: MonadIO m
                  => (FilePath -> m a)  -- ^ The function we want to pass a FilePath to
                  -> String             -- ^ The text that the file should contain
                  -> m a                -- ^ The function's return value
withTemporaryFile :: (FilePath -> m a) -> FilePath -> m a
withTemporaryFile FilePath -> m a
f FilePath
text =
    do FilePath
path <- IO FilePath -> m FilePath
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO IO FilePath
writeTemporaryFile
       a
result <- FilePath -> m a
f FilePath
path
       IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ FilePath -> IO ()
removeFile FilePath
path
       a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return a
result
    where
      writeTemporaryFile :: IO FilePath
writeTemporaryFile =
          do FilePath
dir <- IO FilePath
getTemporaryDirectory
             (FilePath
path, Handle
h) <- FilePath -> FilePath -> IO (FilePath, Handle)
openBinaryTempFile FilePath
dir FilePath
"wtf.tmp"
             Handle -> FilePath -> IO ()
hPutStr Handle
h FilePath
text
             Handle -> IO ()
hClose Handle
h
             FilePath -> IO FilePath
forall (m :: * -> *) a. Monad m => a -> m a
return FilePath
path

-- Example: write the path of the temporary file and its contents into /tmp/result:
-- test =
--   withTemporaryFile f "Some text\n"
--   where f path = readFile path >>= return . (("Contents of " ++ path ++ ":\n") ++) >>= writeFile "/tmp/result"