packages feed

monitor-0.1.0: monitor.hs

import Data.List
import System.Environment
import System.FilePath
import System.Process

import System.INotify

uniqDirs :: [FilePath] -> [FilePath]
uniqDirs = nub . map takeDirectory

eventHandler :: String -> [FilePath] -> FilePath -> Event -> IO ()
eventHandler command paths directory (Modified _ (Just file)) =
    if elem path paths
        then system command >> return ()
        else return ()
    where
        path = normalise $ directory </> file
eventHandler _ _ _ _ = return ()

addWatches :: (FilePath -> Event -> IO ()) -> [FilePath] -> IO [WatchDescriptor]
addWatches handler paths = do
    inotify <- initINotify
    mapM (\p -> addWatch inotify [Modify] p (handler p)) (map normalise paths)

wait :: String -> IO ()
wait command = do
    _ <- getLine
    _ <- system command
    wait command

parse :: [String] -> IO ()
parse (command:paths) = do
    _ <- addWatches (eventHandler command paths) $ uniqDirs paths
    wait command
parse [] = print "Usage: monitor 'commands' [file ...]"

main :: IO ()
main = getArgs >>= parse