File: Files.hs

package info (click to toggle)
haskell-debian 3.64-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 364 kB
  • sloc: haskell: 3,226; ansic: 8; makefile: 3
file content (30 lines) | stat: -rw-r--r-- 1,148 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
-- |Domain independent functions used by the haskell-debian package.
module Debian.Extra.Files
    ( withTemporaryFile
    ) where

import 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 f text =
    do path <- liftIO writeTemporaryFile
       result <- f path
       liftIO $ removeFile path
       return result
    where
      writeTemporaryFile =
          do dir <- getTemporaryDirectory
             (path, h) <- openBinaryTempFile dir "wtf.tmp"
             hPutStr h text
             hClose h
             return 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"