packages feed

delta (empty) → 0.1.0.0

raw patch · 9 files changed

+595/−0 lines, 9 filesdep +basedep +containersdep +deltasetup-changed

Dependencies added: base, containers, delta, directory, filepath, fs-events, sodium, time

Files

+ LICENSE view
@@ -0,0 +1,165 @@+                  GNU LESSER GENERAL PUBLIC LICENSE+                       Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.+++  This version of the GNU Lesser General Public License incorporates+the terms and conditions of version 3 of the GNU General Public+License, supplemented by the additional permissions listed below.++  0. Additional Definitions.++  As used herein, "this License" refers to version 3 of the GNU Lesser+General Public License, and the "GNU GPL" refers to version 3 of the GNU+General Public License.++  "The Library" refers to a covered work governed by this License,+other than an Application or a Combined Work as defined below.++  An "Application" is any work that makes use of an interface provided+by the Library, but which is not otherwise based on the Library.+Defining a subclass of a class defined by the Library is deemed a mode+of using an interface provided by the Library.++  A "Combined Work" is a work produced by combining or linking an+Application with the Library.  The particular version of the Library+with which the Combined Work was made is also called the "Linked+Version".++  The "Minimal Corresponding Source" for a Combined Work means the+Corresponding Source for the Combined Work, excluding any source code+for portions of the Combined Work that, considered in isolation, are+based on the Application, and not on the Linked Version.++  The "Corresponding Application Code" for a Combined Work means the+object code and/or source code for the Application, including any data+and utility programs needed for reproducing the Combined Work from the+Application, but excluding the System Libraries of the Combined Work.++  1. Exception to Section 3 of the GNU GPL.++  You may convey a covered work under sections 3 and 4 of this License+without being bound by section 3 of the GNU GPL.++  2. Conveying Modified Versions.++  If you modify a copy of the Library, and, in your modifications, a+facility refers to a function or data to be supplied by an Application+that uses the facility (other than as an argument passed when the+facility is invoked), then you may convey a copy of the modified+version:++   a) under this License, provided that you make a good faith effort to+   ensure that, in the event an Application does not supply the+   function or data, the facility still operates, and performs+   whatever part of its purpose remains meaningful, or++   b) under the GNU GPL, with none of the additional permissions of+   this License applicable to that copy.++  3. Object Code Incorporating Material from Library Header Files.++  The object code form of an Application may incorporate material from+a header file that is part of the Library.  You may convey such object+code under terms of your choice, provided that, if the incorporated+material is not limited to numerical parameters, data structure+layouts and accessors, or small macros, inline functions and templates+(ten or fewer lines in length), you do both of the following:++   a) Give prominent notice with each copy of the object code that the+   Library is used in it and that the Library and its use are+   covered by this License.++   b) Accompany the object code with a copy of the GNU GPL and this license+   document.++  4. Combined Works.++  You may convey a Combined Work under terms of your choice that,+taken together, effectively do not restrict modification of the+portions of the Library contained in the Combined Work and reverse+engineering for debugging such modifications, if you also do each of+the following:++   a) Give prominent notice with each copy of the Combined Work that+   the Library is used in it and that the Library and its use are+   covered by this License.++   b) Accompany the Combined Work with a copy of the GNU GPL and this license+   document.++   c) For a Combined Work that displays copyright notices during+   execution, include the copyright notice for the Library among+   these notices, as well as a reference directing the user to the+   copies of the GNU GPL and this license document.++   d) Do one of the following:++       0) Convey the Minimal Corresponding Source under the terms of this+       License, and the Corresponding Application Code in a form+       suitable for, and under terms that permit, the user to+       recombine or relink the Application with a modified version of+       the Linked Version to produce a modified Combined Work, in the+       manner specified by section 6 of the GNU GPL for conveying+       Corresponding Source.++       1) Use a suitable shared library mechanism for linking with the+       Library.  A suitable mechanism is one that (a) uses at run time+       a copy of the Library already present on the user's computer+       system, and (b) will operate properly with a modified version+       of the Library that is interface-compatible with the Linked+       Version.++   e) Provide Installation Information, but only if you would otherwise+   be required to provide such information under section 6 of the+   GNU GPL, and only to the extent that such information is+   necessary to install and execute a modified version of the+   Combined Work produced by recombining or relinking the+   Application with a modified version of the Linked Version. (If+   you use option 4d0, the Installation Information must accompany+   the Minimal Corresponding Source and Corresponding Application+   Code. If you use option 4d1, you must provide the Installation+   Information in the manner specified by section 6 of the GNU GPL+   for conveying Corresponding Source.)++  5. Combined Libraries.++  You may place library facilities that are a work based on the+Library side by side in a single library together with other library+facilities that are not Applications and are not covered by this+License, and convey such a combined library under terms of your+choice, if you do both of the following:++   a) Accompany the combined library with a copy of the same work based+   on the Library, uncombined with any other library facilities,+   conveyed under the terms of this License.++   b) Give prominent notice with the combined library that part of it+   is a work based on the Library, and explaining where to find the+   accompanying uncombined form of the same work.++  6. Revised Versions of the GNU Lesser General Public License.++  The Free Software Foundation may publish revised and/or new versions+of the GNU Lesser General Public License from time to time. Such new+versions will be similar in spirit to the present version, but may+differ in detail to address new problems or concerns.++  Each version is given a distinguishing version number. If the+Library as you received it specifies that a certain numbered version+of the GNU Lesser General Public License "or any later version"+applies to it, you have the option of following the terms and+conditions either of that published version or of any later version+published by the Free Software Foundation. If the Library as you+received it does not specify a version number of the GNU Lesser+General Public License, you may choose any version of the GNU Lesser+General Public License ever published by the Free Software Foundation.++  If the Library as you received it specifies that a proxy can decide+whether future versions of the GNU Lesser General Public License shall+apply, that proxy's public statement of acceptance of any version is+permanent authorization for you to choose that version for the+Library.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ delta.cabal view
@@ -0,0 +1,102 @@+-- Initial delta.cabal generated by cabal init.  For further documentation,+--  see http://haskell.org/cabal/users-guide/++-- The name of the package.+name:                delta++-- The package version.  See the Haskell package versioning policy (PVP) +-- for standards guiding when and how versions should be incremented.+-- http://www.haskell.org/haskellwiki/Package_versioning_policy+-- PVP summary:      +-+------- breaking API changes+--                   | | +----- non-breaking API additions+--                   | | | +--- code changes with no API change+version:             0.1.0.0++-- A short (one-line) description of the package.+synopsis:            A library for detecting file changes++-- A longer description of the package.+description:         Delta is a library for detecting file changes in any given+                     directory. The package is written using the sodium FRP library+                     but it also provides a callback based API.++                     The project also contains an executable, delta-cli which+                     runs on the command line and prints detected changes to stdout.++-- URL for the project homepage or repository.+homepage:            https://github.com/kryoxide/delta++-- The license under which the package is released.+license:             LGPL-3++-- The file containing the license text.+license-file:        LICENSE++-- The package author(s).+author:              Christof Schramm++-- An email address to which users can send suggestions, bug reports, and +-- patches.+maintainer:          christof.schramm@campus.lmu.de++-- A copyright notice.+-- copyright:           ++category:            Data++build-type:          Simple++-- Extra files to be distributed with the package, such as examples or a +-- README.+-- extra-source-files:  ++-- Constraint on the version of Cabal needed to build this package.+cabal-version:       >=1.16++source-repository head+  type:              git+  location:          https://github.com/kryoxide/delta/++library+  -- Modules exported by the library.+  exposed-modules:     System.Delta.Base+                     , System.Delta.Poll+                     , System.Delta.Callback+                     , System.Delta.Class+                     , System.Delta+  -- Modules included in this library but not exported.+  -- other-modules:       +  +  -- LANGUAGE extensions used by modules in this package.+  -- other-extensions:    +  +  -- Other library packages from which modules are imported.+  build-depends:       base >=4.6 && <4.9+                     , containers >= 0.5+                     , directory >= 1.2+                     , filepath >= 1.3+                     , time >= 1.5+                     , sodium >= 0.11+                     , fs-events+  +  -- Directories containing source files.+  hs-source-dirs:      src+  +  -- Base language which the package is written in.+  default-language:    Haskell2010++executable delta-cli++  build-depends:       base >= 4.8 && < 4.9+                     , containers >= 0.5+                     , directory >= 1.2+                     , filepath >= 1.3+                     , time >= 1.5+                     , sodium >= 0.11+                     , delta++  hs-source-dirs:      src/delta-cli++  main-is:             Main.hs++  default-language:    Haskell2010
+ src/System/Delta.hs view
@@ -0,0 +1,24 @@+{-# LANGUAGE RankNTypes #-}+module System.Delta ( module System.Delta.Base+                    , module System.Delta.Poll+                    , module System.Delta.Class+                    , module System.Delta.Callback+                    , deltaDir+                    , deltaDirWithCallbacks+                    )where++import System.Delta.Base+import System.Delta.Poll+import System.Delta.Class+import System.Delta.Callback++-- | Build a file watcher+deltaDir :: (FileWatcher a) => FilePath -> IO a+deltaDir path = defaultWatcher path >>= return . watcherId++-- | Build a file watcher that allows to register callbacks+deltaDirWithCallbacks :: (FileWatcher a) => FilePath -> IO (CallbackWatcher a)+deltaDirWithCallbacks path = deltaDir path >>= withCallbacks++watcherId :: (FileWatcher a) => a -> a+watcherId a = a
+ src/System/Delta/Base.hs view
@@ -0,0 +1,28 @@+module System.Delta.Base where++import System.IO.Error+import System.FilePath+import System.Directory+import Data.Time.Clock.POSIX++newtype FileInfo = FileInfo (FilePath,Integer,Bool)+                 deriving (Ord,Eq,Show)++fileInfoPath :: FileInfo -> FilePath+fileInfoPath (FileInfo (path,_,_)) = path++-- | File modification time in milliseconds+fileInfoTimestamp :: FileInfo -> Integer+fileInfoTimestamp (FileInfo (_,time,_)) = time++-- | Is the file a directory+fileInfoIsDir :: FileInfo -> Bool+fileInfoIsDir (FileInfo (_,_,dir)) = dir++mkFileInfo :: FilePath -> IO (FileInfo)+mkFileInfo path  = do+  isDir  <- doesDirectoryExist path+  isFile <- doesFileExist path+  modTime <- getModificationTime path+  let timeMillis = 1000 * (floor $ utcTimeToPOSIXSeconds modTime)+  return $ FileInfo (path, timeMillis, isDir)
+ src/System/Delta/Callback.hs view
@@ -0,0 +1,115 @@+{-# LANGUAGE GADTs #-}+module System.Delta.Callback ( CallbackWatcher+                             , CallbackId+                               +                             -- * Construction+                             , withCallbacks+                               +                             -- * Adding callbacks+                             , withDeleteCallback+                             , withChangedCallback+                             , withNewCallback++                             -- * Removing callbacks+                             , unregisterCallback+                             , removeAllCallbacks++                             -- * Closing the watcher+                             , closeCallbackWatcher+                             )where++import FRP.Sodium+import System.Delta.Base+import System.Delta.Class++import qualified Data.Map as M++import Control.Concurrent.MVar++newtype CallbackId = CallbackId Integer+                   deriving (Eq, Ord)  ++data CallbackWatcher w where+  CallbackWatcher :: FileWatcher w => {+    baseWatcher :: w+  , nextCallbackId :: MVar CallbackId+  , watcherCallbacks :: MVar (M.Map CallbackId (IO ()))+  } -> CallbackWatcher w+++-- | Raise the callback id of a callback watcher+raiseId :: CallbackWatcher w -> IO (CallbackId)+raiseId w = do+  (CallbackId n) <- takeMVar $ nextCallbackId w+  putMVar (nextCallbackId w) (CallbackId $ n+1)+  return (CallbackId n)++-- | Add an action to unregister a callback+addCallbackUnregister :: CallbackWatcher w -> IO () -> IO CallbackId+addCallbackUnregister w removeCallback = do+  newId <- raiseId w+  mp <- takeMVar $ watcherCallbacks w+  putMVar (watcherCallbacks w) (M.insert newId removeCallback mp)+  return newId+  +-- | Wrap a file watcher in a datatype that allows adding callbacks+withCallbacks :: (FileWatcher a) => a -> IO (CallbackWatcher a)+withCallbacks w = do+  nextIdVar <- newMVar (CallbackId 0)+  callbacks <- newMVar (M.empty)+  return $ CallbackWatcher w nextIdVar callbacks++-- | Add a callback that is executed when file deletion is detected+withDeleteCallback :: (FileWatcher a)+                      => CallbackWatcher a+                        -> (FilePath -> IO ()) -- ^ An IO action on the deleted path+                        -> IO (CallbackId)+withDeleteCallback watcher action = do+  unregisterCallback <- callbackOnEvent (deletedFiles $ baseWatcher watcher) action+  addCallbackUnregister watcher unregisterCallback++-- | Add a callback that is executed when file creation is detected+withNewCallback :: (FileWatcher a)+                      => CallbackWatcher a+                        -> (FilePath -> IO ()) -- ^ An IO action on the new path+                        -> IO (CallbackId)+withNewCallback watcher action = do+  unregisterCallback <- callbackOnEvent (newFiles $ baseWatcher watcher) action+  addCallbackUnregister watcher unregisterCallback++-- | Add a callback on a changed file+withChangedCallback :: (FileWatcher a)+                      => CallbackWatcher a+                        -> (FileInfo -> IO ()) -- ^ Action on changed file+                        -> IO (CallbackId)+withChangedCallback watcher action = do+  unregisterCallback <- callbackOnEvent (changedFiles $ baseWatcher watcher) action+  addCallbackUnregister watcher unregisterCallback++-- | Unregister the given CallbackId from the FileWatcher+-- does nothing if the CallbackId is not in the watcher+unregisterCallback :: (FileWatcher a) => CallbackWatcher a -> CallbackId -> IO ()+unregisterCallback watcher cId = do+  mp <- takeMVar $ watcherCallbacks watcher+  case M.lookup cId mp of+    Nothing -> return ()+    Just action -> action+  putMVar (watcherCallbacks watcher) (M.delete cId mp)++-- | Remove all callbacks form the watcher. They will not be called after this+removeAllCallbacks :: (FileWatcher a) => CallbackWatcher a -> IO ()+removeAllCallbacks watcher = do+  mp <- takeMVar $ watcherCallbacks watcher+  putMVar (watcherCallbacks watcher) M.empty+  sequence_ (M.elems mp)++-- | Remove all callbacks and close the underlying FileWatcher+closeCallbackWatcher :: FileWatcher a => CallbackWatcher a -> IO ()+closeCallbackWatcher watcher = do+  removeAllCallbacks watcher+  cleanUpAndClose $ baseWatcher watcher+  ++-- | Add a listener to an event, return the action to unregister the listener+callbackOnEvent :: Event a -> (a -> IO ()) -> IO (IO ())+callbackOnEvent e action = sync $ listen e action
+ src/System/Delta/Class.hs view
@@ -0,0 +1,23 @@+module System.Delta.Class where++import FRP.Sodium+import System.Delta.Base++class FileWatcher a where+  -- | Each type provides a default watcher for a pass+  defaultWatcher  :: FilePath -> IO a++  -- | An event that gives some info on changed files (disjunct from+  -- deleted and new files)+  changedFiles    :: a -> Event FileInfo++  -- | An event that fires for each new file+  newFiles        :: a -> Event FilePath++  -- | An event that fires for each deleted path+  deletedFiles    :: a -> Event FilePath++  -- | Free all possibly used resources. No event will fire after+  -- this.+  cleanUpAndClose :: a -> IO ()+
+ src/System/Delta/Poll.hs view
@@ -0,0 +1,112 @@+module System.Delta.Poll ( PollWatcher+                         , createPollWatcher+                         )where++import Control.Applicative ((<$>))+import Control.Concurrent+import Control.Monad (foldM)++import qualified Data.Map as M+import Data.Maybe (catMaybes)++import FRP.Sodium++import System.Delta.Base+import System.Delta.Class++import System.Directory+import System.FilePath++data PollWatcher = PollWatcher+                     FilePath+                     (Event FileInfo)+                     (Event FilePath)+                     (Event FilePath)+                     ThreadId++instance FileWatcher PollWatcher where+  defaultWatcher = createPollWatcher 15+  changedFiles (PollWatcher _ e _ _ _) = e+  newFiles     (PollWatcher _ _ e _ _) = e+  deletedFiles (PollWatcher _ _ _ e _) = e+  cleanUpAndClose (PollWatcher _ _ _ _ tId) = killThread tId++-- | Watch files in this directory recursively for changes every+-- n seconds.+createPollWatcher :: Int      -- ^ seconds interval+                  -> FilePath -- ^ path to watch+                  -> IO PollWatcher+createPollWatcher secs path = do+  (changedEvent, pushChanged) <- sync $ newEvent+  (deletedEvent, pushDeleted) <- sync $ newEvent+  (newFileEvent, pushNewFile) <- sync $ newEvent+  watcherId <- startWatchThread path pushNewFile pushDeleted pushChanged secs+  return $ PollWatcher path changedEvent newFileEvent deletedEvent watcherId++-- | Recursively traverse a folder, follow symbolic links but don't+-- visit a file twice.+recursiveDescent path = recursiveDescent' M.empty path++-- | Recursively traverse a folder, follows symbolic links,+-- doesn't loop however.+recursiveDescent' :: M.Map FilePath FileInfo+                  -> FilePath+                  -> IO (M.Map FilePath FileInfo)+recursiveDescent' visited path | M.member path visited = return visited+recursiveDescent' visited path = do+  isDir  <- doesDirectoryExist path+  inf <- mkFileInfo path+  let visitedWithCurrent = M.insert path inf visited+  if not isDir+  then return $ visitedWithCurrent+  else do+    contentsUnfiltered <- getDirectoryContents path+    let contentsFiltered = filter (\x -> x /= "." && x /= "..") contentsUnfiltered+        contentsAbs = (combine path) <$> contentsFiltered+    foldM recursiveDescent' visitedWithCurrent contentsAbs+++-- | List all files that have a larger modification time in the second+-- map than in the first+diffChangedFiles :: M.Map FilePath FileInfo +             -> M.Map FilePath FileInfo+             -> [FileInfo]+diffChangedFiles before after =+  catMaybes . M.elems $ M.intersectionWith f before after+  where+    f beforeInfo afterInfo =+      if fileInfoTimestamp beforeInfo < fileInfoTimestamp afterInfo+      then Just afterInfo+      else Nothing++-- | List all files that occur in the second map but not the first+diffNewFiles :: M.Map FilePath FileInfo+             -> M.Map FilePath FileInfo+             -> [FileInfo]+diffNewFiles before after = M.elems $ M.difference after before++-- | List all files that occur in the first map but not the second+diffDeletedFiles :: M.Map FilePath FileInfo+                 -> M.Map FilePath FileInfo+                 -> [FileInfo]+diffDeletedFiles before after = M.elems $ M.difference before after++-- | Fork a thread that continuously polls the given paht and compares+-- the results of two polls.+startWatchThread :: FilePath+                 -> (FilePath -> Reactive ()) -- ^ Push new files / dirs+                 -> (FilePath -> Reactive ()) -- ^ Push deleted files / dirs+                 -> (FileInfo -> Reactive ()) -- ^ Push changed files / dirs+                 -> Int -- ^ Seconds between polls+                 -> IO ThreadId+startWatchThread path pushNew pushDeleted pushChanged secs = do+  curr <- recursiveDescent path+  forkIO $ go curr+  where+    go last = do+      threadDelay $ secs * 1000 * 1000+      curr <- recursiveDescent path+      sync $ mapM_ (pushChanged) (diffChangedFiles last curr)+      sync $ mapM_ (pushNew    ) (fileInfoPath <$> diffNewFiles last curr)+      sync $ mapM_ (pushDeleted) (fileInfoPath <$> diffDeletedFiles last curr)+      go curr
+ src/delta-cli/Main.hs view
@@ -0,0 +1,24 @@+module Main where++import System.Delta+import System.Environment++import Control.Monad+import Control.Concurrent++main = do+  args <- getArgs+  case args of+    [path] -> do+                watcher <- createPollWatcher 1 path >>= withCallbacks+                withNewCallback watcher (\x -> putStrLn $ "new:\t" ++ x)+                withDeleteCallback watcher (\x -> putStrLn $ "del:\t" ++ x)+                withChangedCallback watcher (\(FileInfo(x,_,_)) ->+                                              putStrLn $ "changed:\t" ++ x+                                            )+                forever $ threadDelay (1000 * 1000)+    _      -> putStrLn errorString++errorString = "This is a simple command line interface to the delta\+              \library. Call the program with delta-cli <path>, where path\+              \is the path of the folder / file you want to watch."