Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace file watcher #8

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

- Fix typo in the README's example and one in doc-string

- Use native `java.nio.file.WatchService` for monitoring project folder changes.

## Added

## Fixed
Expand Down
11 changes: 4 additions & 7 deletions deps.edn
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
{:paths ["src" "resources"]

:deps
{rewrite-clj/rewrite-clj {:mvn/version "1.0.682-alpha"}
org.clojure/tools.deps.alpha {:mvn/version "0.12.1030"}
com.lambdaisland/shellutils {:mvn/version "0.0.10"}
org.clojure/java.classpath {:mvn/version "1.0.0"}
com.nextjournal/beholder {:mvn/version "1.0.0"}}}
:deps {rewrite-clj/rewrite-clj {:mvn/version "1.0.682-alpha"}
org.clojure/tools.deps.alpha {:mvn/version "0.12.1030"}
com.lambdaisland/shellutils {:mvn/version "0.0.10"}
org.clojure/java.classpath {:mvn/version "1.0.0"}}}
100 changes: 76 additions & 24 deletions src/lambdaisland/classpath/watch_deps.clj
Original file line number Diff line number Diff line change
@@ -1,25 +1,77 @@
(ns lambdaisland.classpath.watch-deps
"Watch deps.edn for changes"
(:require [clojure.java.classpath :as cp]
[clojure.string :as str]
[clojure.tools.deps.alpha :as deps]
[lambdaisland.classpath :as licp]
[nextjournal.beholder :as beholder]))

(def watcher (atom nil))

(defn- on-event [opts {:keys [type path]}]
(when (and (= :modify type)
;; On Mac the path will be absolute and include the watched dir,
;; e.g. `/Users/x/project/./deps.edn`
;; On other systems it seems to be relative, like `./deps.edn`
(str/ends-with? (str path) "./deps.edn"))
(println "✨ Reloading deps.edn ✨")
(let [new-paths (remove (set (map str (cp/system-classpath)))
(:classpath-roots (deps/create-basis opts)))]
(doseq [path new-paths]
(println "- " path))
(licp/install-priority-loader! new-paths))))
[lambdaisland.classpath :as licp])
(:import (java.nio.file FileSystems StandardWatchEventKinds WatchEvent$Kind)
(java.util Timer TimerTask)))

(def ^:private watcher (atom nil))

(def ^:private deps-hash (atom nil))

;; lifted from https://gist.github.com/oliyh/0c1da9beab43766ae2a6abc9507e732a
(defn- debounce
"Returns a debounced `f` that will execute after `timeout` and cancel pending
invocations if called again before `timeout` has elapsed"
[f timeout]
(let [timer (Timer.)
task (atom nil)]
(fn [& args]
(when-let [t ^TimerTask @task]
(.cancel t))
(let [new-task (proxy [TimerTask] []
(run []
(apply f args)
(.purge timer)
(reset! task nil)))]
(reset! task new-task)
(.schedule timer new-task timeout)))))

(defn- maybe-reload-deps
[opts]
(let [current-hash (hash (slurp "deps.edn"))
last-hash @deps-hash]
(when (not= last-hash current-hash)
(println "✨ Reloading deps.edn ✨")
(try
(let [new-paths (remove (set (map str (cp/system-classpath)))
(:classpath-roots (deps/create-basis opts)))]
(doseq [path new-paths]
(println "- " path))
(licp/install-priority-loader! new-paths))
(catch Exception e
(println "Failed to reload deps.edn:" (.getMessage e))))
(reset! deps-hash current-hash))))

(def ^:private reload-deps (debounce maybe-reload-deps 250))

(defn- watch-project-root
"Registers a `WatchService` on the project root and waits for `ENTRY_MODIFY`
events for deps.edn"
[opts]
(let [file-system (FileSystems/getDefault)
project-root (.getPath file-system "." (into-array String []))
watch-service (.newWatchService file-system)]
(future
(try
(loop [watch-key (.register project-root
watch-service
(into-array WatchEvent$Kind [StandardWatchEventKinds/ENTRY_MODIFY]))]

(when (some #(= "deps.edn" (.toString (.context %)))
(.pollEvents watch-key))
(reload-deps opts))
(.reset watch-key)
(recur
(.take watch-service)))
(catch InterruptedException _
(println "Watcher stopped."))
(catch Exception e
(println "Watcher error:" (.getMessage e)))
(finally
(.close watch-service)
(println "WatchService closed."))))))

(defn start!
"Start a file system watcher to pick up changes in `deps.edn'
Expand All @@ -36,18 +88,18 @@
(fn [w]
(when w
(println "Stopping existing `deps.edn' watcher")
(beholder/stop w))
(beholder/watch (partial on-event opts) "."))))
(future-cancel w))
(watch-project-root opts))))

(defn stop!
"Stop a previously started watcher"
[opts]
[]
(swap! watcher
(fn [w]
(when w
(beholder/stop w))
(future-cancel w))
nil)))


(comment
(start! {:aliases [:dev]}))
(start! {:aliases [:dev]})
(stop!))