summaryrefslogtreecommitdiff
path: root/Annex/ReplaceFile.hs
blob: f0dfa5b2720cdb46af7866f3e3d03e9ce17e228c (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
{- git-annex file replacing
 -
 - Copyright 2013 Joey Hess <joey@kitenet.net>
 -
 - Licensed under the GNU GPL version 3 or higher.
 -}

module Annex.ReplaceFile where

import Common.Annex
import Annex.Perms

{- Replaces a possibly already existing file with a new version, 
 - atomically, by running an action.
 - 
 - The action is passed a temp file, which it can write to, and once
 - done the temp file is moved into place.
 -}
replaceFile :: FilePath -> (FilePath -> Annex ()) -> Annex ()
replaceFile file a = do
	tmpdir <- fromRepo gitAnnexTmpDir
	createAnnexDirectory tmpdir
	tmpfile <- liftIO $ do
		(tmpfile, h) <- openTempFileWithDefaultPermissions tmpdir $
			takeFileName file
		hClose h
		return tmpfile
	a tmpfile
	liftIO $ do
		r <- tryIO $ rename tmpfile file
		case r of
			Left _ -> do
				createDirectoryIfMissing True $ parentDir file
				rename tmpfile file
			_ -> noop