2011-10-16 04:31:25 +00:00
|
|
|
{- temp file functions
|
|
|
|
-
|
|
|
|
- Copyright 2010-2011 Joey Hess <joey@kitenet.net>
|
|
|
|
-
|
|
|
|
- Licensed under the GNU GPL version 3 or higher.
|
|
|
|
-}
|
|
|
|
|
|
|
|
module Utility.TempFile where
|
|
|
|
|
2011-11-26 12:39:47 +00:00
|
|
|
import Control.Exception (bracket)
|
2011-10-16 04:31:25 +00:00
|
|
|
import System.IO
|
|
|
|
import System.Posix.Process hiding (executeFile)
|
|
|
|
import System.Directory
|
|
|
|
|
|
|
|
import Utility.Misc
|
|
|
|
import Utility.Path
|
|
|
|
|
|
|
|
{- Runs an action like writeFile, writing to a temp file first and
|
|
|
|
- then moving it into place. The temp file is stored in the same
|
|
|
|
- directory as the final file to avoid cross-device renames. -}
|
|
|
|
viaTmp :: (FilePath -> String -> IO ()) -> FilePath -> String -> IO ()
|
|
|
|
viaTmp a file content = do
|
|
|
|
pid <- getProcessID
|
|
|
|
let tmpfile = file ++ ".tmp" ++ show pid
|
|
|
|
createDirectoryIfMissing True (parentDir file)
|
|
|
|
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 a = bracket create remove use
|
|
|
|
where
|
|
|
|
create = do
|
2011-11-11 00:24:24 +00:00
|
|
|
tmpdir <- catchDefaultIO getTemporaryDirectory "."
|
2011-10-16 04:31:25 +00:00
|
|
|
openTempFile tmpdir template
|
|
|
|
remove (name, handle) = do
|
|
|
|
hClose handle
|
2011-11-11 00:24:24 +00:00
|
|
|
catchBoolIO (removeFile name >> return True)
|
2011-10-16 04:31:25 +00:00
|
|
|
use (name, handle) = a name handle
|