Keep hooks on the task function itself, genius.

Entia non sunt multiplicanda praeter necessitatem.
This commit is contained in:
Phil Hagelberg 2010-06-06 16:51:02 -07:00
parent c725770182
commit 4ff7dab7eb
2 changed files with 15 additions and 13 deletions

View file

@ -38,17 +38,15 @@ alias->task-name mappings on to the leiningen.core/aliases atom:
You can modify the behaviour of built-in tasks to a degree using You can modify the behaviour of built-in tasks to a degree using
hooks. Inspired by clojure.test's fixtures functionality, hooks are hooks. Inspired by clojure.test's fixtures functionality, hooks are
functions which wrap tasks and may alter their behaviour by using functions which wrap tasks and may alter their behaviour by using
binding, altering the functions arguments or return value, only binding, altering the return value, only running the function
running the function conditionally, etc. conditionally, etc. The add-hook function takes a var of the task it's
meant to apply to:
(defn skip-integration-hook [task] (defn skip-integration-hook [task]
(binding [clojure.test/test-var (test-var-skip :integration)] (binding [clojure.test/test-var (test-var-skip :integration)]
(task))) (task)))
(add-hook 'test skip-integration-hook) (add-hook #'leiningen.test/test skip-integration-hook)
The add-hook function takes a symbol for which task it's meant to
apply to. You can also pass in :all to have it apply to every task.
Hooks compose, so be aware that your hook may be running inside Hooks compose, so be aware that your hook may be running inside
another hook. Hooks are loaded by looking for all namespaces under another hook. Hooks are loaded by looking for all namespaces under

View file

@ -66,10 +66,13 @@
(catch java.io.FileNotFoundException e (catch java.io.FileNotFoundException e
error-fn)))) error-fn))))
(def hooks (atom {})) (defn- hookize [v]
(when-not (::hooks (meta @v))
(alter-var-root v vary-meta assoc ::hooks (atom []))))
(defn add-hook [task f] (defn add-hook [task-var f]
(swap! hooks update-in [task] conj f)) (hookize task-var)
(swap! (::hooks (meta @task-var)) conj f))
(defn- load-hooks [task] (defn- load-hooks [task]
(doseq [n (sort (find-namespaces-on-classpath)) (doseq [n (sort (find-namespaces-on-classpath))
@ -85,10 +88,11 @@
(defn run-task (defn run-task
"Run the given task with its hooks activated." "Run the given task with its hooks activated."
[task args] [task-name args]
(load-hooks task) (let [task (resolve-task task-name)]
((join-hooks (concat (@hooks (symbol task)) (@hooks :all))) (load-hooks task-name)
#(apply (resolve-task task) args))) ((join-hooks @(::hooks (meta @task)))
#(apply task args))))
(defn ns->path [n] (defn ns->path [n]
(str (.. (str n) (str (.. (str n)