Created
August 17, 2014 16:06
-
-
Save yogthos/911e6aba9802ceacd83c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns file-watcher | |
(:require [clojure.set :refer [rename-keys]] | |
[clojure.java.io :refer [file]]) | |
(:import | |
[java.nio.file | |
FileSystems | |
Path | |
Paths | |
StandardWatchEventKinds])) | |
(defn register-events! [dir watch-service opts] | |
(.register dir watch-service | |
(-> opts | |
(select-keys [StandardWatchEventKinds/ENTRY_CREATE | |
StandardWatchEventKinds/ENTRY_MODIFY | |
StandardWatchEventKinds/ENTRY_DELETE | |
StandardWatchEventKinds/OVERFLOW]) | |
(keys) | |
(into-array)))) | |
(defn rename-event-keys [opts] | |
(rename-keys opts | |
{:create StandardWatchEventKinds/ENTRY_CREATE | |
:modify StandardWatchEventKinds/ENTRY_MODIFY | |
:delete StandardWatchEventKinds/ENTRY_DELETE | |
:overflow StandardWatchEventKinds/OVERFLOW})) | |
(defn watch-loop [watch-service opts] | |
(loop [] | |
(let [k (.take watch-service)] | |
(doseq [event (.pollEvents k)] | |
(if-let [handler (get opts (.kind event))] | |
(handler event))) | |
(when (.reset k) (recur))))) | |
(defn watch [path opts] | |
(let [dir (-> path (file) (.toURI) (Paths/get)) | |
opts (rename-event-keys opts)] | |
(with-open [watch-service (.newWatchService (FileSystems/getDefault))] | |
(register-events! dir watch-service opts) | |
(watch-loop watch-service opts)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@slipset had to make a few small changes to get it to work. You have to run
watch
in a thread and use>!!
in thewatch-loop
. Turns out you can also set a sensitivity modifier for improved polling on OS X.