summaryrefslogtreecommitdiff
path: root/Utility/TempFile.hs
blob: 6dbea693ab062074efd26b20363222f1a01cb7f5 (plain)
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
{- temp file functions
 -
 - Copyright 2010-2011 Joey Hess <joey@kitenet.net>
 -
 - Licensed under the GNU GPL version 3 or higher.
 -}

module Utility.TempFile where

import Control.Exception (bracket)
import System.IO
import System.Posix.Process
import System.Directory

import Utility.Exception
import Utility.Path
import System.FilePath

{- 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

type Template = String

{- Runs an action with a temp file, then removes the file. -}
withTempFile :: Template -> (FilePath -> Handle -> IO a) -> IO a
withTempFile template a = bracket create remove use
  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

{- 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
  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