Last active
November 25, 2019 21:41
-
-
Save bostonaholic/b7f1fbc974615fcea3097d17b9746c13 to your computer and use it in GitHub Desktop.
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
(defn- untrace [v] | |
(alter-var-root v (fn [new] | |
(if-let [untraced (:trace/untraced (meta new))] | |
untraced | |
(throw (Exception. "Wasn't traced.")))))) | |
(defn- maybe-disable [state n] | |
(if (< (:calls state) n) | |
(update-in state [:calls] inc) | |
(assoc state :done true))) | |
(defn- data-tracer [v state n old] | |
(when-not (fn? old) | |
(throw (Exception. "Don't trace non-functions."))) | |
(with-meta | |
(fn [& args] | |
(swap! state maybe-disable n) | |
(if (:done @state) | |
(do (untrace v) | |
(apply old args)) | |
(do (swap! state update-in [:args] conj args) | |
(let [ret (apply old args)] | |
(swap! state update-in [:rets] conj ret) | |
ret)))) | |
{:trace/untraced old})) | |
(defn data-trace | |
"Enable trace on any var containing a function for up to n calls | |
E.g. (data-trace #'myapp.foo/bar 10)" | |
[v n] | |
(let [state (atom {:args [] :rets [] :calls 0 :var v})] | |
(alter-var-root v (partial data-tracer v state n)) | |
state)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment