2-- Module : Streamly.Internal.FileSystem.Event.Linux
3-- Copyright : (c) 2020 Composewell Technologies
4-- License : BSD-3-Clause
5-- Maintainer : streamly@composewell.com
6-- Stability : experimental
11-- Use 'watchPaths' with a list of file system paths you want to watch as
12-- argument. It returns a stream of 'Event' representing the file system events
13-- occurring under the watched paths.
16-- Stream.mapM_ (putStrLn . 'showEvent') $ 'watchPaths' [Array.fromCString\# "dir"#]
19-- 'Event' is an opaque type. Accessor functions (e.g. 'showEvent' above)
20-- provided in this module are used to determine the attributes of the event.
22-- Identical successive events may be coalesced into a single event.
26-- For reference documentation see:
28-- * <https://man7.org/linux/man-pages/man7/inotify.7.html inotify man page>
30-- We try to keep the macOS\/Linux/Windows event handling APIs and defaults
31-- semantically and syntactically as close as possible.
35-- When testing on Linux Kernel version @5.3.0-53-generic #47-Ubuntu@, the last
36-- event for the root path seems to be delayed until one more event occurs.
38-- = Differences between macOS and Linux APIs:
40-- 1. macOS watch is based on the path provided to it, if the path is
41-- deleted and recreated it will still be watched, if the path moves to another
42-- path it won't be watched anymore. Whereas Linux watch is based on a handle
43-- to the path, if the path is deleted and recreated it won't be watched, if
44-- the path moves to another it can still be watched (though this is
47-- 2. macOS watches the directory hierarchy recursively, Linux watches only one
48-- level of dir, recursive watch has to be built in user space by watching for
49-- create events and adding the new directories to the watch. Not sure how this
50-- will scale for too many paths.
52-- 3. In macOS the path of the subject of the event is absolute, in Linux the
53-- path is the name of the object inside the dir being watched.
55-- 4. On Linux 'watchPaths' fails if a path does not exist, on macOS it does
60#if HAVE_DECL_IN_EXCL_UNLINK
61module Streamly.Internal.FileSystem.Event.Linux
63 -- * Subscribing to events
65 -- ** Default configuration
79 -- ** Events of Interest
80 -- *** Root Path Events
85 -- *** Item Level Metadata change
88 -- *** Item Level Access
94 -- *** Item CRUD events
108 -- Low level watch APIs
119 -- ** Root Level Events
126 -- ** Item Level Metadata change
129 -- ** Item Level Access
135 -- ** Item Level CRUD events
146 -- ** Exception Conditions
154import Control.Monad (void, when)
155import Control.Monad.IO.Class (MonadIO, liftIO)
156import Data.Bits ((.|.), (.&.), complement)
157import Data.Char (ord)
158import Data.Foldable (foldlM)
159import Data.Functor.Identity (runIdentity)
160import Data.IntMap.Lazy (IntMap)
161import Data.IORef (IORef, newIORef, readIORef, writeIORef, modifyIORef)
162import Data.List.NonEmpty (NonEmpty)
163#if !(MIN_VERSION_base(4,13,0))
164import Data.Semigroup (Semigroup(..))
166import Data.Word (Word8, Word32)
167import Foreign.C.Error (throwErrnoIfMinus1)
168import Foreign.C.String (CString)
169import Foreign.C.Types (CInt(..), CUInt(..))
170import Foreign.Ptr (Ptr)
171import Foreign.Storable (peek, peekByteOff, sizeOf)
172import GHC.IO.Device (IODeviceType(Stream))
173import GHC.IO.FD (fdFD, mkFD)
174import GHC.IO.Handle.FD (mkHandleFromFD)
175import Streamly.Prelude (SerialT)
176import Streamly.Internal.Data.Parser (Parser)
177import Streamly.Internal.Data.Array.Foreign.Type (Array(..), byteLength)
178import System.Directory (doesDirectoryExist)
179import System.IO (Handle, hClose, IOMode(ReadMode))
180import GHC.IO.Handle.FD (handleToFd)
182import qualified Data.IntMap.Lazy as Map
183import qualified Data.List.NonEmpty as NonEmpty
184import qualified Streamly.Internal.Data.Array.Foreign as A
185import qualified Streamly.Internal.Data.Fold as FL
186import qualified Streamly.Internal.Data.Parser as PR
187import qualified Streamly.Internal.Data.Stream.IsStream as S
188import qualified Streamly.Internal.FileSystem.Dir as Dir
189import qualified Streamly.Internal.FileSystem.Handle as FH
190import qualified Streamly.Internal.Unicode.Stream as U
192-------------------------------------------------------------------------------
193-- Subscription to events
194-------------------------------------------------------------------------------
196-- | Watch configuration, used to specify the events of interest and the
197-- behavior of the watch.
203 , createFlags :: Word32
206-------------------------------------------------------------------------------
208-------------------------------------------------------------------------------
210-- | Whether a setting is 'On' or 'Off'.
214data Switch = On | Off deriving (Show, Eq)
216toggle :: Switch -> Switch
220setFlag :: Word32 -> Switch -> Config -> Config
221setFlag mask status cfg@Config{..} =
224 On -> createFlags .|. mask
225 Off -> createFlags .&. complement mask
226 in cfg {createFlags = flags}
228-------------------------------------------------------------------------------
230-------------------------------------------------------------------------------
232-- | Watch the whole directory tree recursively instead of watching just one
233-- level of directory.
239setRecursiveMode :: Switch -> Config -> Config
240setRecursiveMode rec cfg@Config{} = cfg {watchRec = rec == On}
243 "sys/inotify.h value IN_DONT_FOLLOW" iN_DONT_FOLLOW :: Word32
245-- | If the pathname to be watched is a symbolic link then watch the target of
246-- the symbolic link instead of the symbolic link itself.
248-- Note that the path location in the events is through the original symbolic
249-- link path rather than the resolved path.
255setFollowSymLinks :: Switch -> Config -> Config
256setFollowSymLinks s = setFlag iN_DONT_FOLLOW (toggle s)
259 "sys/inotify.h value IN_EXCL_UNLINK" iN_EXCL_UNLINK :: Word32
261-- | If an object moves out of the directory being watched then stop watching
268setUnwatchMoved :: Switch -> Config -> Config
269setUnwatchMoved = setFlag iN_EXCL_UNLINK
271#if HAVE_DECL_IN_MASK_CREATE
273 "sys/inotify.h value IN_MASK_CREATE" iN_MASK_CREATE :: Word32
277 "sys/inotify.h value IN_MASK_ADD" iN_MASK_ADD :: Word32
279-- | What to do if a watch already exists when 'openWatch' or 'addToWatch' is
285 AddIfExists -- ^ Do not set an existing setting to 'Off' only set to 'On'
286 | ReplaceIfExists -- ^ Replace the existing settings with new settings
287#if HAVE_DECL_IN_MASK_CREATE
288 | FailIfExists -- ^ Fail the API
291-- | When adding a new path to the watch, specify what to do if a watch already
292-- exists on that path.
294-- /default: FailIfExists/
298setWhenExists :: WhenExists -> Config -> Config
299setWhenExists val cfg =
301 AddIfExists -> setFlag iN_MASK_ADD On cfg
302 ReplaceIfExists -> setFlag iN_MASK_ADD Off cfg
303#if HAVE_DECL_IN_MASK_CREATE
304 FailIfExists -> setFlag iN_MASK_CREATE On cfg
308 "sys/inotify.h value IN_ONESHOT" iN_ONESHOT :: Word32
310-- | Watch the object only for one event and then remove it from the watch.
316setOneShot :: Switch -> Config -> Config
317setOneShot = setFlag iN_ONESHOT
320 "sys/inotify.h value IN_ONLYDIR" iN_ONLYDIR :: Word32
322-- | Watch the object only if it is a directory. This provides a race-free way
323-- to ensure that the watched object is a directory.
329setOnlyDir :: Switch -> Config -> Config
330setOnlyDir = setFlag iN_ONLYDIR
332-------------------------------------------------------------------------------
333-- Event types that can occur
334-------------------------------------------------------------------------------
337 "sys/inotify.h value IN_DELETE_SELF" iN_DELETE_SELF :: Word32
339-- | Report when the watched path itself gets deleted.
345setRootDeleted :: Switch -> Config -> Config
346setRootDeleted = setFlag iN_DELETE_SELF
349 "sys/inotify.h value IN_MOVE_SELF" iN_MOVE_SELF :: Word32
351-- | Report when the watched root path itself gets renamed.
357setRootMoved :: Switch -> Config -> Config
358setRootMoved = setFlag iN_MOVE_SELF
360-- | Report when the watched root path itself gets deleted or renamed.
366setRootPathEvents :: Switch -> Config -> Config
367setRootPathEvents = setFlag (iN_DELETE_SELF .|. iN_MOVE_SELF)
370 "sys/inotify.h value IN_ATTRIB" iN_ATTRIB :: Word32
372-- | Report when the metadata e.g. owner, permission modes, modifications times
373-- of an object changes.
379setAttrsModified :: Switch -> Config -> Config
380setAttrsModified = setFlag iN_ATTRIB
383 "sys/inotify.h value IN_ACCESS" iN_ACCESS :: Word32
385-- | Report when a file is accessed.
391setAccessed :: Switch -> Config -> Config
392setAccessed = setFlag iN_ACCESS
395 "sys/inotify.h value IN_OPEN" iN_OPEN :: Word32
397-- | Report when a file is opened.
403setOpened :: Switch -> Config -> Config
404setOpened = setFlag iN_OPEN
407 "sys/inotify.h value IN_CLOSE_WRITE" iN_CLOSE_WRITE :: Word32
409-- | Report when a file that was opened for writes is closed.
415setWriteClosed :: Switch -> Config -> Config
416setWriteClosed = setFlag iN_CLOSE_WRITE
419 "sys/inotify.h value IN_CLOSE_NOWRITE" iN_CLOSE_NOWRITE :: Word32
421-- | Report when a file that was opened for not writing is closed.
427setNonWriteClosed :: Switch -> Config -> Config
428setNonWriteClosed = setFlag iN_CLOSE_NOWRITE
431 "sys/inotify.h value IN_CREATE" iN_CREATE :: Word32
433-- | Report when a file is created.
439setCreated :: Switch -> Config -> Config
440setCreated = setFlag iN_CREATE
443 "sys/inotify.h value IN_DELETE" iN_DELETE :: Word32
445-- | Report when a file is deleted.
451setDeleted :: Switch -> Config -> Config
452setDeleted = setFlag iN_DELETE
455 "sys/inotify.h value IN_MOVED_FROM" iN_MOVED_FROM :: Word32
457-- | Report the source of a move.
463setMovedFrom :: Switch -> Config -> Config
464setMovedFrom = setFlag iN_MOVED_FROM
467 "sys/inotify.h value IN_MOVED_TO" iN_MOVED_TO :: Word32
469-- | Report the target of a move.
475setMovedTo :: Switch -> Config -> Config
476setMovedTo = setFlag iN_MOVED_TO
479 "sys/inotify.h value IN_MODIFY" iN_MODIFY :: Word32
481-- | Report when a file is modified.
487setModified :: Switch -> Config -> Config
488setModified = setFlag iN_MODIFY
490-- | Set all tunable events 'On' or 'Off'. Equivalent to setting:
498-- * setNonWriteClosed
507setAllEvents :: Switch -> Config -> Config
515 . setNonWriteClosed s
522-------------------------------------------------------------------------------
524-------------------------------------------------------------------------------
526-- The defaults are set in such a way that the behavior on macOS and Linux is
527-- as much compatible as possible.
529-- | The default configuration settings are:
531-- * 'setFollowSymLinks' 'On'
532-- * 'setUnwatchMoved' 'On'
533-- * 'setOneShot' 'Off'
534-- * 'setOnlyDir' 'Off'
535-- * 'setWhenExists' 'AddIfExists'
537-- The tunable events enabled by default are:
547defaultConfig :: Config
549 setWhenExists AddIfExists
560-------------------------------------------------------------------------------
561-- Open an event stream
562-------------------------------------------------------------------------------
564-- | A handle for a watch.
567 Handle -- File handle for the watch
569 (IntMap -- Key is the watch descriptor
570 ( Array Word8 -- Absolute path of the watch root
571 , Array Word8 -- Path of subdir relative to watch root
576-- Instead of using the watch descriptor we can provide APIs that use the path
577-- itself to identify the watch. That will require us to maintain a map from wd
578-- to path in the Watch handle.
580newtype WD = WD CInt deriving Show
582foreign import ccall unsafe
583 "sys/inotify.h inotify_init" c_inotify_init :: IO CInt
585-- | Create a 'Watch' handle. 'addToWatch' can be used to add paths being
586-- monitored by this watch.
590createWatch :: IO Watch
592 rawfd <- throwErrnoIfMinus1 "createWatch" c_inotify_init
593 -- we could use fdToHandle but it cannot determine the fd type
594 -- automatically for the inotify fd
599 (Just (Stream, 0, 0)) -- (IODeviceType, CDev, CIno)
600 False -- not a socket
601 False -- non-blocking is false
602 let fdString = "<createWatch file descriptor: " ++ show fd ++ ">"
609 True -- use non-blocking IO
610 Nothing -- TextEncoding (binary)
611 emptyMapRef <- newIORef Map.empty
612 return $ Watch h emptyMapRef
614foreign import ccall unsafe
615 "sys/inotify.h inotify_add_watch" c_inotify_add_watch
616 :: CInt -> CString -> CUInt -> IO CInt
618-- XXX we really do not know the path encoding, all we know is that it is "/"
619-- separated bytes. So these may fail or convert the path in an unexpected
620-- manner. We should ultimately remove all usage of these.
622toUtf8 :: MonadIO m => String -> m (Array Word8)
623toUtf8 = A.fromStream . U.encodeUtf8 . S.fromList
625utf8ToString :: Array Word8 -> String
626utf8ToString = runIdentity . S.toList . U.decodeUtf8' . A.toStream
628-- | Add a trailing "/" at the end of the path if there is none. Do not add a
629-- "/" if the path is empty.
631ensureTrailingSlash :: Array Word8 -> Array Word8
632ensureTrailingSlash path =
633 if byteLength path /= 0
635 let mx = A.getIndex (byteLength path - 1) path
637 Nothing -> error "ensureTrailingSlash: Bug: Invalid index"
639 if x /= fromIntegral (ord '/')
640 then path <> A.fromCString# "/"#
644removeTrailingSlash :: Array Word8 -> Array Word8
645removeTrailingSlash path =
646 if byteLength path /= 0
648 let n = byteLength path - 1
649 mx = A.getIndex n path
651 Nothing -> error "removeTrailingSlash: Bug: Invalid index"
653 if x == fromIntegral (ord '/')
654 then A.getSliceUnsafe 0 n path
658appendPaths :: Array Word8 -> Array Word8 -> Array Word8
660 | byteLength a == 0 = b
661 | byteLength b == 0 = a
662 | otherwise = ensureTrailingSlash a <> b
664-- | @addToWatch cfg watch root subpath@ adds @subpath@ to the list of paths
665-- being monitored under @root@ via the watch handle @watch@. @root@ must be
666-- an absolute path and @subpath@ must be relative to @root@.
670addToWatch :: Config -> Watch -> Array Word8 -> Array Word8 -> IO ()
671addToWatch cfg@Config{..} watch0@(Watch handle wdMap) root0 path0 = do
672 -- XXX do not add if the path is already added
673 -- XXX if the watch is added by the scan and not via an event we can
674 -- generate a create event assuming that the create may have been lost. We
675 -- can also mark in the map that this entry was added by the scan. So if an
676 -- actual create event later comes and tries to add this again then we can
677 -- ignore that and drop the create event to avoid duplicate create, because
678 -- we have already emitted it.
680 -- When a directory is added by the scan we should also emit create events
681 -- for files that may have got added to the dir. However, such create
682 -- events may get duplicated because of a race between the scan generated
683 -- versus real events.
685 -- Or we may distinguish between scan generated events and real events so
686 -- that the application can assume that other events may been lost and
687 -- handle it. For example, if it is a dir create the application can read
688 -- the dir to scan the files in it.
690 let root = removeTrailingSlash root0
691 path = removeTrailingSlash path0
692 absPath = appendPaths root path
693 putStrLn $ "root = " ++ utf8ToString root ++ " path = " ++ utf8ToString path ++ " absPath = " ++ utf8ToString absPath
695 fd <- handleToFd handle
697 -- XXX we need to tolerate an error where we are adding a watch for a
698 -- non-existing file because the file may have got deleted by the time we
699 -- added the watch. Perhaps we can have a flag in config for this and keep
700 -- the default value to tolerate the error.
702 -- XXX The file may have even got deleted and then recreated which we will
703 -- never get to know, document this.
704 wd <- A.asCStringUnsafe absPath $ \pathPtr ->
705 throwErrnoIfMinus1 ("addToWatch: " ++ utf8ToString absPath) $
706 c_inotify_add_watch (fdFD fd) pathPtr (CUInt createFlags)
708 -- We add the parent first so that we start getting events for any new
709 -- creates and add the new subdirectories on creates while we are adding
711 modifyIORef wdMap (Map.insert (fromIntegral wd) (root, path))
713 -- Now add the children. If we missed any creates while we were adding the
714 -- parent, this will make sure they are added too.
716 -- XXX Ensure that we generate events that we may have missed while we were
717 -- adding the dirs. That may generate spurious events though.
719 -- XXX toDirs currently uses paths as String, we need to convert it
720 -- to "/" separated by byte arrays.
721 pathIsDir <- doesDirectoryExist $ utf8ToString absPath
722 when (watchRec && pathIsDir) $ do
723 S.mapM_ (\p -> addToWatch cfg watch0 root (appendPaths path p))
725 $ Dir.toDirs $ utf8ToString absPath
727foreign import ccall unsafe
728 "sys/inotify.h inotify_rm_watch" c_inotify_rm_watch
729 :: CInt -> CInt -> IO CInt
731-- | Remove an absolute root path from a 'Watch', if a path was moved after
732-- adding you need to provide the original path which was used to add the
737removeFromWatch :: Watch -> Array Word8 -> IO ()
738removeFromWatch (Watch handle wdMap) path = do
739 fd <- handleToFd handle
740 km <- readIORef wdMap
741 wdMap1 <- foldlM (step fd) Map.empty (Map.toList km)
742 writeIORef wdMap wdMap1
746 step fd newMap (wd, v) = do
749 let err = "removeFromWatch: " ++ show (utf8ToString path)
750 rm = c_inotify_rm_watch (fdFD fd) (fromIntegral wd)
751 void $ throwErrnoIfMinus1 err rm
753 else return $ Map.insert wd v newMap
755-- | Given a 'Config' and list of @paths@ ("/" separated byte arrays) start
756-- monitoring the paths for file system events. Returns a 'Watch' handle which
757-- can then be used to read the event stream or to close the watch.
761openWatch :: Config -> NonEmpty (Array Word8) -> IO Watch
762openWatch cfg paths = do
765 (\root -> addToWatch cfg w root (A.fromList []))
766 $ NonEmpty.toList paths
769-- | Close a 'Watch' handle.
773closeWatch :: Watch -> IO ()
774closeWatch (Watch h _) = hClose h
776-------------------------------------------------------------------------------
777-- Raw events read from the watch file handle
778-------------------------------------------------------------------------------
780newtype Cookie = Cookie Word32 deriving (Show, Eq)
782-- | An Event generated by the file system. Use the accessor functions to
789 , eventFlags :: Word32
790 , eventCookie :: Word32
791 , eventRelPath :: Array Word8
792 , eventMap :: IntMap (Array Word8, Array Word8)
793 } deriving (Show, Ord, Eq)
795-- The inotify event struct from the man page/header file:
797-- struct inotify_event {
798-- int wd; /* Watch descriptor */
799-- uint32_t mask; /* Mask describing event */
800-- uint32_t cookie; /* Unique cookie associating related
801-- events (for rename(2)) */
802-- uint32_t len; /* Size of name field */
803-- char name[]; /* Optional null-terminated name */
806-- XXX We can perhaps use parseD monad instance for fusing with parseMany? Need
807-- to measure the perf.
809readOneEvent :: Config -> Watch -> Parser IO Word8 Event
810readOneEvent cfg wt@(Watch _ wdMap) = do
811 let headerLen = sizeOf (undefined :: CInt) + 12
812 arr <- PR.takeEQ headerLen (A.writeN headerLen)
813 (ewd, eflags, cookie, pathLen) <- PR.fromEffect $ A.asPtrUnsafe arr readHeader
814 -- XXX need the "initial" in parsers to return a step type so that "take 0"
815 -- can return without an input. otherwise if pathLen is 0 we will keep
816 -- waiting to read one more char before we return this event.
820 -- XXX takeEndBy_ drops the separator so assumes a null
821 -- terminated path, we should use a takeWhile nested inside a
825 $ FL.takeEndBy_ (== 0)
826 $ FL.take pathLen (A.writeN pathLen)
827 let remaining = pathLen - byteLength pth - 1
828 when (remaining /= 0) $ PR.takeEQ remaining FL.drain
830 else return $ A.fromList []
831 wdm <- PR.fromEffect $ readIORef wdMap
833 case Map.lookup (fromIntegral ewd) wdm of
836 error $ "readOneEvent: "
837 <> "Unknown watch descriptor: "
839 let sub1 = appendPaths sub path
840 -- Check for "ISDIR" first because it is less likely
841 isDirCreate = eflags .&. iN_ISDIR /= 0 && eflags .&. iN_CREATE /= 0
842 when (watchRec cfg && isDirCreate)
843 $ PR.fromEffect $ addToWatch cfg wt root sub1
844 -- XXX Handle IN_DELETE, IN_DELETE_SELF, IN_MOVE_SELF, IN_MOVED_FROM,
846 -- What if a large dir tree gets moved in to our hierarchy? Do we get a
847 -- single event for the top level dir in this case?
849 { eventWd = fromIntegral ewd
850 , eventFlags = eflags
851 , eventCookie = cookie
852 , eventRelPath = sub1
858 readHeader (ptr :: Ptr Word8) = do
859 let len = sizeOf (undefined :: CInt)
861 eflags <- peekByteOff ptr len
862 cookie <- peekByteOff ptr (len + 4)
863 pathLen :: Word32 <- peekByteOff ptr (len + 8)
864 return (ewd, eflags, cookie, fromIntegral pathLen)
866watchToStream :: Config -> Watch -> SerialT IO Event
867watchToStream cfg wt@(Watch handle _) = do
868 -- Do not use too small a buffer. As per inotify man page:
870 -- The behavior when the buffer given to read(2) is too small to return
871 -- information about the next event depends on the kernel version: in
872 -- kernels before 2.6.21, read(2) returns 0; since kernel 2.6.21, read(2)
873 -- fails with the error EINVAL. Specifying a buffer of size
875 -- sizeof(struct inotify_event) + NAME_MAX + 1
877 -- will be sufficient to read at least one event.
878 S.parseMany (readOneEvent cfg wt) $ S.unfold FH.read handle
880-- XXX We should not go across the mount points of network file systems or file
881-- systems that are known to not generate any events.
883-- | Start monitoring a list of file system paths for file system events with
884-- the supplied configuration operation over the 'defaultConfig'. The
885-- paths could be files or directories. When recursive mode is set and the
886-- path is a directory, the whole directory tree under it is watched
887-- recursively. Monitoring starts from the current time onwards. The paths are
888-- specified as UTF-8 encoded 'Array' of 'Word8'.
890-- /Non-existing Paths:/ the API fails if a watch is started on a non-exsting
893-- /Performance:/ Note that recursive watch on a large directory tree could be
894-- expensive. When starting a watch, the whole tree must be read and watches
895-- are started on each directory in the tree. The initial time to start the
896-- watch as well as the memory required is proportional to the number of
897-- directories in the tree.
899-- /Bugs:/ When new directories are created under the tree they are added to
900-- the watch on receiving the directory create event. However, the creation of
901-- a dir and adding a watch for it is not atomic. The implementation takes
902-- care of this and makes sure that watches are added for all directories.
903-- However, In the mean time, the directory may have received more events which
904-- may get lost. Handling of any such lost events is yet to be implemented.
906-- See the Linux __inotify__ man page for more details.
910-- ('setFollowSymLinks' On . 'setUnwatchMoved' Off)
911-- [Array.fromCString\# "dir"#]
916watchWith :: (Config -> Config) -> NonEmpty (Array Word8) -> SerialT IO Event
917watchWith f paths = S.bracket before after (watchToStream cfg)
921 cfg = f defaultConfig
922 before = liftIO $ openWatch cfg paths
923 after = liftIO . closeWatch
925-- | Same as 'watchWith' using 'defaultConfig' and recursive mode.
927-- >>> watchRecursive = watchWith (setRecursiveMode On)
929-- See 'watchWith' for pitfalls and bugs when using recursive watch on Linux.
933watchRecursive :: NonEmpty (Array Word8) -> SerialT IO Event
934watchRecursive = watchWith (setRecursiveMode On)
936-- | Same as 'watchWith' using defaultConfig and non-recursive mode.
938-- >>> watch = watchWith id
942watch :: NonEmpty (Array Word8) -> SerialT IO Event
945-------------------------------------------------------------------------------
946-- Examine event stream
947-------------------------------------------------------------------------------
949-- | Get the watch root corresponding to the 'Event'.
951-- Note that if a path was moved after adding to the watch, this will give the
952-- original path and not the new path after moving.
954-- TBD: we can possibly update the watch root on a move self event.
958getRoot :: Event -> Array Word8
962 case Map.lookup (fromIntegral eventWd) eventMap of
963 Just path -> fst path
965 error $ "Bug: getRoot: No path found corresponding to the "
966 ++ "watch descriptor " ++ show eventWd
969-- XXX should we use a Maybe here?
970-- | Get the file system object path for which the event is generated, relative
971-- to the watched root. The path is a "/" separated array of bytes.
975getRelPath :: Event -> Array Word8
976getRelPath Event{..} = eventRelPath
978-- | Get the absolute file system object path for which the event is generated.
980-- When the watch root is a symlink, the absolute path returned is via the
981-- original symlink and not through the resolved path.
985getAbsPath :: Event -> Array Word8
987 let relpath = getRelPath ev
989 in if byteLength relpath /= 0
990 then ensureTrailingSlash root <> relpath
991 else removeTrailingSlash root
993-- XXX should we use a Maybe?
994-- | Cookie is set when a rename occurs. The cookie value can be used to
995-- connect the 'isMovedFrom' and 'isMovedTo' events, if both the events belong
996-- to the same move operation then they will have the same cookie value.
1000getCookie :: Event -> Cookie
1001getCookie Event{..} = Cookie eventCookie
1003-------------------------------------------------------------------------------
1005-------------------------------------------------------------------------------
1007getFlag :: Word32 -> Event -> Bool
1008getFlag mask Event{..} = eventFlags .&. mask /= 0
1010-------------------------------------------------------------------------------
1012-------------------------------------------------------------------------------
1015 "sys/inotify.h value IN_Q_OVERFLOW" iN_Q_OVERFLOW :: Word32
1017-- XXX rename to isQOverflowed or hasOverflowed?
1019-- macOS overflow API is more specific, it tells which paths have lost the
1020-- events due to overflow.
1022-- | Event queue overflowed (WD is invalid for this event) and we may have lost
1023-- some events.. The user application must scan everything under the watched
1024-- paths to know the current state.
1028isEventsLost :: Event -> Bool
1029isEventsLost = getFlag iN_Q_OVERFLOW
1031-------------------------------------------------------------------------------
1032-- Events affecting the watched path only
1033-------------------------------------------------------------------------------
1036 "sys/inotify.h value IN_IGNORED" iN_IGNORED :: Word32
1038-- Compare with isRootChanged on macOS. isRootChanged includes all these cases.
1040-- | A path was removed from the watch explicitly using 'removeFromWatch' or
1041-- automatically (file was deleted, or filesystem was unmounted).
1043-- Note that in recursive watch mode all the subdirectories are watch roots,
1044-- therefore, they will all generate this event.
1046-- /Occurs only for a watched path/
1050isRootUnwatched :: Event -> Bool
1051isRootUnwatched = getFlag iN_IGNORED
1053-- | Watched file/directory was itself deleted. (This event also occurs if an
1054-- object is moved to another filesystem, since mv(1) in effect copies the file
1055-- to the other filesystem and then deletes it from the original filesystem.)
1056-- In addition, an 'isRootUnwatched' event will subsequently be generated
1057-- for the watch descriptor.
1059-- Note that in recursive watch mode all the subdirectories are watch roots,
1060-- therefore, they will all generate this event.
1062-- /Occurs only for a watched path/
1066isRootDeleted :: Event -> Bool
1067isRootDeleted = getFlag iN_DELETE_SELF
1069-- | Watched file/directory was itself moved within the file system.
1071-- Note that in recursive watch mode all the subdirectories are watch roots,
1072-- therefore, they will all generate this event.
1074-- /Occurs only for a watched path/
1078isRootMoved :: Event -> Bool
1079isRootMoved = getFlag iN_MOVE_SELF
1082 "sys/inotify.h value IN_UNMOUNT" iN_UNMOUNT :: Word32
1084-- | Filesystem containing watched object was unmounted. In addition, an
1085-- 'isRootUnwatched' event will subsequently be generated for the watch
1088-- /Occurs only for a watched path/
1092isRootUnmounted :: Event -> Bool
1093isRootUnmounted = getFlag iN_UNMOUNT
1095-- | Determine whether the event indicates a change of path of the monitored
1096-- object itself. Note that the object may become unreachable or deleted after
1099-- /Occurs only for a watched path/
1103isRootPathEvent :: Event -> Bool
1104isRootPathEvent = getFlag (iN_DELETE_SELF .|. iN_MOVE_SELF .|. iN_UNMOUNT)
1106-------------------------------------------------------------------------------
1107-- Metadata change Events
1108-------------------------------------------------------------------------------
1110-- macOS has multiple APIs for metadata change for different metadata.
1112-- | Determine whether the event indicates inode metadata change for an object
1113-- contained within the monitored path.
1115-- Metadata change may include, permissions (e.g., chmod(2)), timestamps
1116-- (e.g., utimensat(2)), extended attributes (setxattr(2)), link count (since
1117-- Linux 2.6.25; e.g., for the target of link(2) and for unlink(2)), and
1118-- user/group ID (e.g., chown(2)).
1120-- /Can occur for watched path or a file inside it/
1124isAttrsModified :: Event -> Bool
1125isAttrsModified = getFlag iN_ATTRIB
1127-------------------------------------------------------------------------------
1129-------------------------------------------------------------------------------
1131-- | File was accessed (e.g. read, execve).
1133-- /Occurs only for a file inside the watched directory/
1137isAccessed :: Event -> Bool
1138isAccessed = getFlag iN_ACCESS
1140-- | File or directory was opened.
1142-- /Occurs only for a file inside the watched directory/
1146isOpened :: Event -> Bool
1147isOpened = getFlag iN_OPEN
1149-- | File opened for writing was closed.
1151-- /Occurs only for a file inside the watched directory/
1155isWriteClosed :: Event -> Bool
1156isWriteClosed = getFlag iN_CLOSE_WRITE
1158-- XXX what if it was opened for append? Does NOWRITE mean all cases where the
1159-- mode was not write? A dir open comes in this category?
1161-- | File or directory opened for read but not write was closed.
1163-- /Can occur for watched path or a file inside it/
1167isNonWriteClosed :: Event -> Bool
1168isNonWriteClosed = getFlag iN_CLOSE_NOWRITE
1170-------------------------------------------------------------------------------
1172-------------------------------------------------------------------------------
1174-- On macOS this is not generated on hard linking but on Linux it is.
1176-- | File/directory created in watched directory (e.g., open(2) O_CREAT,
1177-- mkdir(2), link(2), symlink(2), bind(2) on a UNIX domain socket).
1179-- /Occurs only for an object inside the watched directory/
1183isCreated :: Event -> Bool
1184isCreated = getFlag iN_CREATE
1186-- | File/directory deleted from watched directory.
1188-- /Occurs only for an object inside the watched directory/
1192isDeleted :: Event -> Bool
1193isDeleted = getFlag iN_DELETE
1195-- XXX what if an object is moved in from outside or moved out of the monitored
1198-- | Generated for the original path when an object is moved from under a
1199-- monitored directory.
1201-- /Occurs only for an object inside the watched directory/
1205isMovedFrom :: Event -> Bool
1206isMovedFrom = getFlag iN_MOVED_FROM
1208-- | Generated for the new path when an object is moved under a monitored
1211-- /Occurs only for an object inside the watched directory/
1215isMovedTo :: Event -> Bool
1216isMovedTo = getFlag iN_MOVED_TO
1218-- | Generated for a path that is moved from or moved to the monitored
1221-- >>> isMoved ev = isMovedFrom ev || isMovedTo ev
1223-- /Occurs only for an object inside the watched directory/
1227isMoved :: Event -> Bool
1228isMoved ev = isMovedFrom ev || isMovedTo ev
1230-- | Determine whether the event indicates modification of an object within the
1231-- monitored path. This event is generated only for files and not directories.
1233-- /Occurs only for an object inside the watched directory/
1237isModified :: Event -> Bool
1238isModified = getFlag iN_MODIFY
1240-------------------------------------------------------------------------------
1241-- Information about path type (applicable only when 'setFileEvents' is 'On')
1242-------------------------------------------------------------------------------
1245 "sys/inotify.h value IN_ISDIR" iN_ISDIR :: Word32
1247-- | Determine whether the event is for a directory path.
1251isDir :: Event -> Bool
1252isDir = getFlag iN_ISDIR
1254-------------------------------------------------------------------------------
1256-------------------------------------------------------------------------------
1258-- | Convert an 'Event' record to a String representation.
1259showEvent :: Event -> String
1260showEvent ev@Event{..} =
1261 "--------------------------"
1262 ++ "\nWd = " ++ show eventWd
1263 ++ "\nRoot = " ++ show (utf8ToString $ getRoot ev)
1264 ++ "\nPath = " ++ show (utf8ToString $ getRelPath ev)
1265 ++ "\nCookie = " ++ show (getCookie ev)
1266 ++ "\nFlags " ++ show eventFlags
1268 ++ showev isEventsLost "Overflow"
1270 ++ showev isRootUnwatched "RootUnwatched"
1271 ++ showev isRootDeleted "RootDeleted"
1272 ++ showev isRootMoved "RootMoved"
1273 ++ showev isRootUnmounted "RootUnmounted"
1275 ++ showev isAttrsModified "AttrsModified"
1277 ++ showev isAccessed "Accessed"
1278 ++ showev isOpened "Opened"
1279 ++ showev isWriteClosed "WriteClosed"
1280 ++ showev isNonWriteClosed "NonWriteClosed"
1282 ++ showev isCreated "Created"
1283 ++ showev isDeleted "Deleted"
1284 ++ showev isModified "Modified"
1285 ++ showev isMovedFrom "MovedFrom"
1286 ++ showev isMovedTo "MovedTo"
1288 ++ showev isDir "Dir"
1291 where showev f str = if f ev then "\n" ++ str else ""
1293#warning "Disabling module Streamly.Internal.FileSystem.Event.Linux. Does not support kernels older than 2.6.36."
1294module Streamly.Internal.FileSystem.Event.Linux () where
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list