Created
August 21, 2013 04:35
-
-
Save manicolosi/6290355 to your computer and use it in GitHub Desktop.
Better Clojure code for file system watching...
This file contains 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 manico.utils.fs-watch | |
(:require [clojure.set :as set] | |
[lwjgl-spike.utils.interop :as interop]) | |
(:import [java.nio.file Paths WatchEvent$Kind | |
StandardWatchEventKinds])) | |
(def ^:private keywords->event-kinds | |
{:create StandardWatchEventKinds/ENTRY_CREATE | |
:modify StandardWatchEventKinds/ENTRY_MODIFY | |
:delete StandardWatchEventKinds/ENTRY_DELETE}) | |
(def ^:private event-kinds->keywords (set/map-invert keywords->event-kinds)) | |
(defn- kind [event] | |
(-> event .kind event-kinds->keywords)) | |
(defn- path [event] | |
(-> event .context str)) | |
(defn- descriptor [event] | |
[(kind event) | |
(path event)]) | |
(defn register | |
"Registers for a file system watch. Path should be a string. | |
Valid kinds are :create, :modify, and :delete." | |
[path & kinds] | |
(let [path (Paths/get path (interop/string-array [])) | |
kinds (map keywords->event-kinds kinds) | |
watch (-> path (.getFileSystem) (.newWatchService))] | |
(.register path watch (into-array WatchEvent$Kind kinds)) | |
watch)) | |
(defn poll | |
"Poll for file system events for watch. Returns a vector of event | |
descriptors. Each event descriptor is a vector of the event kind | |
and the event path." | |
[watch] | |
(if-let [watch-key (.poll watch)] | |
(let [events (doall (map descriptor (.pollEvents watch-key)))] | |
(.reset watch-key) | |
events) | |
[])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment