-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcore.clj
427 lines (376 loc) · 16.9 KB
/
core.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
(ns clj-reload.core
(:require
[clj-reload.keep :as keep]
[clj-reload.parse :as parse]
[clj-reload.util :as util]
[clojure.java.io :as io])
(:import
[java.util.concurrent.locks ReentrantLock]))
; Config :: {:dirs [<string> ...] - where to look for files
; :files #"<regex>" - which files to scan, defaults to #".*\.cljc?"
; :no-unload #{<symbol> ...} - list of nses to skip unload
; :no-reload #{<symbol> ...} - list of nses to skip reload
; :reload-hook <symbol> - if function with this name exists,
; it will be called after reloading.
; default: after-ns-reload
; :unload-hook <symbol> - if function with this name exists,
; it will be called before unloading.
; default: before-ns-unload
; :output <keyword>} - verbosity of log output. Options:
; :verbose - print Unloading/Reloading for each namespace
; :quieter - only print 'Reloaded N namespaces'
; :quiet - no output at all
; default: :verbose
(def ^:private ^:dynamic *config*)
; State :: {:since <long> - last time list of files was scanned
; :files {<file> -> File} - all found files
; :namespaces {<symbol> -> NS} - all found namespaces
; :to-unload #{<symbol> ...} - list of nses pending unload
; :to-load #{<symbol> ...}} - list of nses pending load
;
; File :: {:namespaces #{<symbol> ...} - nses defined in this file
; :modified <modified>} - lastModified
;
; NS :: {:ns-files #{<file> ...} - files containing (ns ...) declaration
; :in-ns-files #{<file> ...} - files containing (in-ns ...) declaration
; :requires #{<symbol> ...} - other nses this depends on
; :meta {} - metadata from ns symbol
; :keep {<symbol> -> Keep}}} - vars to keep between reloads
;
; Keep :: {:tag <symbol> - type of value ('def, 'defonce etc)
; :form <any> - full source form, just in case
;
; // stashed vars - one or more of these will contain
; values remembered between reloads
; :var Var?
; :ctor Var?
; :map-ctor Var?
; :proto Var?
; :methods {<symbol> Var}?}
(def ^:private *state
(atom {}))
(def ^ReentrantLock lock
(ReentrantLock.))
(defmacro with-lock [& body]
`(try
(.lock lock)
~@body
(finally
(.unlock lock))))
(defn- files->namespaces [files already-read]
(let [*res (volatile! {})]
(doseq [file files
[name namespace] (or
(already-read file)
(parse/read-file file))
:when (not (util/throwable? namespace))]
(vswap! *res update name #(merge-with into % namespace)))
@*res))
(defn- scan-impl [{files-before :files
nses-before :namespaces} since]
(let [files-now (->> (:dirs *config*)
(mapcat #(file-seq (io/file %)))
(filter util/file?)
(filter #(re-matches (:files *config*) (util/file-name %))))
[files-modified
files-broken] (reduce
(fn [[modified broken] file]
(if (<= (util/last-modified file) since)
[modified broken]
(let [res (parse/read-file file)]
(if (util/throwable? res)
[modified (assoc broken file res)]
[(assoc modified file res) broken]))))
[{} {}] files-now)
files-deleted (reduce disj (set (keys files-before)) files-now)
nses-broken (util/for-map [[file ex] files-broken
ns (get-in files-before [file :namespaces])]
[ns ex])
nses-unload (reduce
#(into %1 (get-in files-before [%2 :namespaces]))
#{}
(concat (keys files-modified) files-deleted))
nses-load (util/for-set [[file namespaces] files-modified
ns (keys namespaces)]
ns)
files' (as-> files-before %
(reduce dissoc % files-deleted)
(merge %
(util/for-map [[file namespaces] files-modified]
[file {:namespaces (set (keys namespaces))
:modified (util/last-modified file)}])))
already-read (merge
(util/for-map [[file {:keys [namespaces]}] files-before]
[file (select-keys nses-before namespaces)])
files-modified
(util/for-map [[file _] files-broken]
[file {}]))
nses' (files->namespaces (keys files') already-read)]
{:broken nses-broken
:files' files'
:namespaces' nses'
:to-unload' nses-unload
:to-load' nses-load}))
(defn find-namespaces
"Returns namespaces matching regex, or all of them"
([]
(find-namespaces #".*"))
([regex]
(binding [util/*log-fn* nil]
(let [{:keys [namespaces']} (scan-impl @*state 0)]
(into #{} (filter #(re-matches regex (name %)) (keys namespaces')))))))
(def ^{:doc "Returns dirs that are currently on classpath"
:arglists '([])}
classpath-dirs
util/classpath-dirs)
(defn init
"Options:
:dirs :: [<string> ...] - where to look for files
:files :: #\"<regex>\" - which files to scan, defaults to #\".*\\\\.cljc?\"
:no-reload :: #{<symbol> ...} - list of namespaces to skip reload entirely
:no-unload :: #{<symbol> ...} - list of namespaces to skip unload only.
These will be loaded “on top” of previous state
:unload-hook :: <symbol> - if function with this name exists in a namespace,
it will be called before unloading. Default: 'before-ns-unload
:reload-hook :: <symbol> - if function with this name exists in a namespace,
it will be called after reloading. Default: 'after-ns-reload
:output :: <keyword> - verbosity of log output. Options:
:verbose - print Unloading/Reloading for each namespace
:quieter - only print 'Reloaded N namespaces'
:quiet - no output at all
Default: :verbose"
[opts]
(with-lock
(binding [util/*log-fn* nil]
(let [dirs (vec (or (:dirs opts) (classpath-dirs)))
files (or (:files opts) #".*\.cljc?")
now (util/now)]
(alter-var-root #'*config*
(constantly
{:dirs dirs
:files files
:no-unload (set (:no-unload opts))
:no-reload (set (:no-reload opts))
:reload-hook (:reload-hook opts 'after-ns-reload)
:unload-hook (:unload-hook opts 'before-ns-unload)
:output (:output opts :verbose)}))
(let [{:keys [files' namespaces']} (scan-impl nil 0)]
(reset! *state {:since now
:files files'
:namespaces namespaces'}))))))
(defn- topo-sort-fn
"Accepts dependees map {ns -> #{downsteram-ns ...}},
returns a fn that topologically sorts dependencies"
[deps]
(let [sorted (parse/topo-sort deps)]
(fn [coll]
(filter (set coll) sorted))))
(defn- add-unloaded [scan re loaded]
(let [new (->> (keys (:namespaces' scan))
(remove loaded)
(filter #(re-matches re (str %))))]
(update scan :to-load' into new)))
(defn carry-keeps [from to]
(util/for-map [[ns-sym ns] to]
[ns-sym (assoc ns :keep
(merge-with merge
(get-in from [ns-sym :keep])
(:keep ns)))]))
(defn- scan [state opts]
(let [{:keys [no-unload no-reload]} *config*
{:keys [since to-load to-unload files namespaces]} state
{:keys [only] :or {only :changed}} opts
now (util/now)
loaded @@#'clojure.core/*loaded-libs*
{:keys [broken
files'
namespaces'
to-unload'
to-load']} (case only
:changed (scan-impl state since)
:loaded (scan-impl state 0)
:all (scan-impl state 0)
#_regex (-> (scan-impl state since)
(add-unloaded only loaded)))
_ (doseq [[ns {:keys [exception]}] broken
:when (loaded ns)
:when (not (no-reload ns))]
(throw exception))
since' (transduce (map :modified) max (max since now) (vals files'))
unload? #(and
(loaded %)
(not (:clj-reload/no-unload (:meta (namespaces %))))
(not (:clj-reload/no-reload (:meta (namespaces %))))
(not (no-unload %))
(not (no-reload %)))
deps (parse/dependees namespaces)
topo-sort (topo-sort-fn deps)
to-unload'' (->> to-unload'
(filter unload?)
(parse/transitive-closure deps)
(filter unload?)
(concat to-unload)
(topo-sort)
(reverse))
load? #(and
(case only
:changed (loaded %)
:loaded (loaded %)
:all true
#_regex (or (loaded %) (re-matches only (str %))))
(not (:clj-reload/no-reload (:meta (namespaces %))))
(not (no-reload %))
(namespaces' %))
deps' (parse/dependees namespaces')
topo-sort' (topo-sort-fn deps')
to-load'' (->> to-load'
(filter load?)
(parse/transitive-closure deps')
(filter load?)
(concat to-load)
(topo-sort'))]
(assoc state
:since since'
:files files'
:namespaces (carry-keeps namespaces namespaces')
:to-unload to-unload''
:to-load to-load'')))
(defn- ns-unload [ns]
(when (= (:output *config*) :verbose)
(util/log "Unloading" ns))
(try
(when-some [unload-hook (:unload-hook *config*)]
(when-some [ns-obj (find-ns ns)]
(when-some [unload-fn (ns-resolve ns-obj unload-hook)]
(unload-fn))))
(catch Throwable t
;; eat up unload error
;; if we can’t unload there’s no way to fix that
;; because any changes would require reload first
(util/log " exception during unload hook" t)))
(remove-ns ns)
(dosync
(alter @#'clojure.core/*loaded-libs* disj ns)))
(defn- ns-load [ns file keeps]
(when (= (:output *config*) :verbose)
(util/log "Loading" ns #_"from" #_(util/file-path file)))
(try
(if (empty? keeps)
(util/ns-load-file (slurp file) ns file)
(keep/ns-load-patched ns file keeps))
(when-some [reload-hook (:reload-hook *config*)]
(when-some [reload-fn (ns-resolve (find-ns ns) reload-hook)]
(reload-fn)))
nil
(catch Throwable t
(util/log " failed to load" ns t)
t)))
(defn unload
"Same as `reload`, but does not loads namespaces back"
([]
(unload nil))
([opts]
(binding [util/*log-fn* (:log-fn opts util/*log-fn*)]
(swap! *state scan opts)
(loop [unloaded []]
(let [state @*state]
(if (not-empty (:to-unload state))
(let [[ns & to-unload'] (:to-unload state)
keeps (keep/resolve-keeps ns (-> state :namespaces ns :keep))]
(ns-unload ns)
(swap! *state
#(-> %
(assoc :to-unload to-unload')
(update :namespaces update ns update :keep util/deep-merge keeps)))
(recur (conj unloaded ns)))
(do
(when (and
(= (:output *config*) :verbose)
(empty? unloaded))
(util/log "Nothing to unload"))
{:unloaded unloaded})))))))
(defn reload
"Options:
:throw :: true | false - throw or return exception, default true
:log-fn :: (fn [& args]) - fn to display unload/reload status
:only :: :changed - default. Only reloads changed already loaded files
| :loaded - Reload all loaded files
| <Pattern> - Reload all nses matching this pattern
| :all - Reload everything it can find in dirs
Returns map of what was reloaded
{:unloaded [<symbol> ...]
:loaded [<symbol> ...]}
If anything fails, throws. If :throw false, return value will also have keys
{:failed <symbol>
:exception <Throwable>}
Can be called multiple times. If reload fails, fix the error and call `reload` again"
([]
(reload nil))
([opts]
(with-lock
(binding [util/*log-fn* (:log-fn opts util/*log-fn*)]
(let [{:keys [unloaded]} (unload opts)]
(loop [loaded []]
(let [state @*state]
(if (not-empty (:to-load state))
(let [[ns & to-load'] (:to-load state)
files (-> state :namespaces ns :ns-files)]
(if-some [ex (some #(ns-load ns % (-> state :namespaces ns :keep)) files)]
(do
(swap! *state update :to-unload #(cons ns %))
(if (:throw opts true)
(throw
(ex-info
(str "Failed to load namespace: " ns)
{:unloaded unloaded
:loaded loaded
:failed ns}
ex))
{:unloaded unloaded
:loaded loaded
:failed ns
:exception ex}))
(do
(swap! *state #(-> %
(assoc :to-load to-load')
(update-in [:namespaces ns] dissoc :keep)))
(recur (conj loaded ns)))))
(do
(when (and
(= (:output *config*) :verbose)
(empty? loaded))
(util/log "Nothing to reload"))
(when (= (:output *config*) :quieter)
(util/log (format "Reloaded %s namespaces" (count loaded))))
{:unloaded unloaded
:loaded loaded})))))))))
(defmulti keep-methods
(fn [tag]
tag))
(defmethod keep-methods :default [tag]
(throw
(ex-info
(str "Keeping " tag " forms is not implemented")
{:tag tag})))
(defmethod keep-methods 'def [_]
keep/keep-methods-defs)
(defmethod keep-methods 'defn [_]
keep/keep-methods-defs)
(defmethod keep-methods 'defn- [_]
keep/keep-methods-defs)
(defmethod keep-methods 'defonce [_]
keep/keep-methods-defs)
(defmethod keep-methods 'deftype [_]
keep/keep-methods-deftype)
(defmethod keep-methods 'defrecord [_]
keep/keep-methods-defrecord)
(defmethod keep-methods 'defprotocol [_]
keep/keep-methods-defprotocol)
;; Initialize with classpath-dirs to support “init-less” workflow
;; See https://github.com/tonsky/clj-reload/pull/4
;; and https://github.com/clojure-emacs/cider-nrepl/issues/849
(when (and
(not= "false" (System/getenv "CLJ_RELOAD_AUTO_INIT"))
(not= "false" (System/getProperty "clj-reload.auto-init")))
(init
{:dirs (classpath-dirs)}))