summaryrefslogtreecommitdiff
path: root/Utility/Kqueue.hs
blob: aabea7d0384700dfd06125b57cc2ad787573380d (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
{- BSD kqueue file modification notification interface
 -
 - Copyright 2012 Joey Hess <joey@kitenet.net>
 -
 - Licensed under the GNU GPL version 3 or higher.
 -}

{-# LANGUAGE ForeignFunctionInterface #-}

module Utility.Kqueue (
	waitChange,
	scanRecursive
) where

import Common

import System.Posix.Types
import Foreign.C.Types
import Foreign.C.Error
import Foreign.Ptr
import Foreign.Marshal
import qualified Data.Map as M

type DirMap = M.Map Fd FilePath

foreign import ccall unsafe "libkqueue.h waitchange" c_waitchange
	:: Ptr Fd -> IO Fd

waitChange :: DirMap -> IO (Maybe FilePath)
waitChange dirmap = withArray (M.keys dirmap) $ \c_fds -> do
	changed <- c_waitchange c_fds
	ifM (safeErrno <$> getErrno)
		( return $ M.lookup changed dirmap
		, return Nothing
		)
	where
		safeErrno (Errno v) = v == 0

scanRecursive :: FilePath -> (FilePath -> Bool) -> IO DirMap
scanRecursive dir prune = M.fromList <$> (mapM opendir =<< dirTree dir prune)
	where
		opendir d = (,)
			<$> openFd d ReadOnly Nothing defaultFileFlags
			<*> pure d