summaryrefslogtreecommitdiff
path: root/Annex/LockPool.hs
blob: 5fc167d2878a4c230c9ba69d347e4280315bca72 (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
59
60
{- git-annex lock pool
 -
 - Copyright 2012, 2014 Joey Hess <joey@kitenet.net>
 -
 - Licensed under the GNU GPL version 3 or higher.
 -}

{-# LANGUAGE CPP #-}

module Annex.LockPool where

import Common.Annex
import Annex
import Types.LockPool

import qualified Data.Map as M

#ifndef mingw32_HOST_OS
import Annex.Perms
#else
import Utility.WinLock
#endif

{- Create a specified lock file, and takes a shared lock. -}
lockFile :: FilePath -> Annex ()
lockFile file = go =<< fromPool file
  where
	go (Just _) = noop -- already locked
	go Nothing = do
#ifndef mingw32_HOST_OS
		mode <- annexFileMode
		lockhandle <- liftIO $ noUmask mode $
			openFd file ReadOnly (Just mode) defaultFileFlags
		liftIO $ waitToSetLock lockhandle (ReadLock, AbsoluteSeek, 0, 0)
#else
		lockhandle <- liftIO $ waitToLock $ lockShared file
#endif
		changePool $ M.insert file lockhandle

unlockFile :: FilePath -> Annex ()
unlockFile file = maybe noop go =<< fromPool file
  where
	go lockhandle = do
#ifndef mingw32_HOST_OS
		liftIO $ closeFd lockhandle
#else
		liftIO $ dropLock lockhandle
#endif
		changePool $ M.delete file

getPool :: Annex LockPool
getPool = getState lockpool

fromPool :: FilePath -> Annex (Maybe LockHandle)
fromPool file = M.lookup file <$> getPool

changePool :: (LockPool -> LockPool) -> Annex ()
changePool a = do
	m <- getPool
	changeState $ \s -> s { lockpool = a m }