add withTempFile

This is essentially the same as withSystemTempFile from System.IO.Temp,
but that library is not packaged for Debian, and may not be widely used.
I see various other withTempFile implementations here and there, none canonical.
Sigh.
This commit is contained in:
Joey Hess 2011-08-16 20:45:58 -04:00
parent cfcd7805b4
commit 354c5f349b

View file

@ -23,6 +23,7 @@ module Utility (
unsetFileMode,
readMaybe,
viaTmp,
withTempFile,
dirContains,
dirContents,
myHomeDir,
@ -38,6 +39,7 @@ module Utility (
prop_relPathDirToFile_basics
) where
import IO (bracket)
import System.IO
import System.Exit
import qualified System.Posix.Process
@ -253,6 +255,18 @@ viaTmp a file content = do
a tmpfile content
renameFile tmpfile file
{- Runs an action with a temp file, then removes the file. -}
withTempFile :: String -> (FilePath -> Handle -> IO a) -> IO a
withTempFile template action = bracket create remove use
where
create = do
tmpdir <- catch getTemporaryDirectory (const $ return ".")
openTempFile tmpdir template
remove (name, handle) = do
hClose handle
catchBool (removeFile name >> return True)
use (name, handle) = action name handle
{- Lists the contents of a directory.
- Unlike getDirectoryContents, paths are not relative to the directory. -}
dirContents :: FilePath -> IO [FilePath]