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
|
2012-07-18 19:30:26 +00:00
|
|
|
import System.Posix.Process
|
2011-10-16 04:31:25 +00:00
|
|
|
import System.Directory
|
|
|
|
|
2012-02-03 20:47:24 +00:00
|
|
|
import Utility.Exception
|
2011-10-16 04:31:25 +00:00
|
|
|
import Utility.Path
|
2012-09-10 18:09:13 +00:00
|
|
|
import System.FilePath
|
2011-10-16 04:31:25 +00:00
|
|
|
|
|
|
|
{- 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
|
2012-12-13 04:45:27 +00:00
|
|
|
let tmpfile = file ++ ".tmp" ++ show pid
|
2011-10-16 04:31:25 +00:00
|
|
|
createDirectoryIfMissing True (parentDir file)
|
|
|
|
a tmpfile content
|
|
|
|
renameFile tmpfile file
|
|
|
|
|
2012-01-21 06:24:12 +00:00
|
|
|
type Template = String
|
|
|
|
|
2011-10-16 04:31:25 +00:00
|
|
|
{- Runs an action with a temp file, then removes the file. -}
|
2012-01-21 06:24:12 +00:00
|
|
|
withTempFile :: Template -> (FilePath -> Handle -> IO a) -> IO a
|
2011-10-16 04:31:25 +00:00
|
|
|
withTempFile template a = bracket create remove use
|
2012-11-12 21:43:10 +00:00
|
|
|
where
|
|
|
|
create = do
|
|
|
|
tmpdir <- catchDefaultIO "." getTemporaryDirectory
|
|
|
|
openTempFile tmpdir template
|
|
|
|
remove (name, handle) = do
|
|
|
|
hClose handle
|
|
|
|
catchBoolIO (removeFile name >> return True)
|
|
|
|
use (name, handle) = a name handle
|
2012-09-10 18:09:13 +00:00
|
|
|
|
|
|
|
{- Runs an action with a temp directory, then removes the directory and
|
|
|
|
- all its contents. -}
|
|
|
|
withTempDir :: Template -> (FilePath -> IO a) -> IO a
|
|
|
|
withTempDir template = bracket create remove
|
2012-11-12 21:43:10 +00:00
|
|
|
where
|
|
|
|
remove = removeDirectoryRecursive
|
|
|
|
create = do
|
|
|
|
tmpdir <- catchDefaultIO "." getTemporaryDirectory
|
|
|
|
createDirectoryIfMissing True tmpdir
|
|
|
|
pid <- getProcessID
|
|
|
|
makedir tmpdir (template ++ show pid) (0 :: Int)
|
|
|
|
makedir tmpdir t n = do
|
|
|
|
let dir = tmpdir </> t ++ "." ++ show n
|
|
|
|
r <- tryIO $ createDirectory dir
|
|
|
|
either (const $ makedir tmpdir t $ n + 1) (const $ return dir) r
|