PageRenderTime 17ms CodeModel.GetById 1ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 0ms

/src/cljs_devmode/core.clj

http://github.com/maxweber/cljs-devmode
Clojure | 74 lines | 60 code | 13 blank | 1 comment | 2 complexity | 87eb7eb9d85e112e972d3674a9bc6835 MD5 | raw file
 1(ns cljs-devmode.core
 2  (:use ring.util.response
 3        ring.middleware.file
 4        clojure.set
 5        ring.adapter.jetty)
 6  (:import java.io.File))
 7
 8(defn clojurescript-source-file?
 9  "Returns true if file is a normal file with a .cljs extension."
10  [^File file]
11  (and (.isFile file)
12       (.endsWith (.getName file) ".cljs")))
13
14(defn find-clojurescript-sources-in-dir
15  "Searches recursively under dir for ClojureScript source files (.cljs).
16  Returns a sequence of File objects, in breadth-first sort order."
17  [^File dir]
18  ;; Use sort by absolute path to get breadth-first search.
19  (sort-by #(.getAbsolutePath %)
20           (filter clojurescript-source-file? (file-seq dir))))
21
22(defn handler [request]
23  (response "ClojureScript devmode"))
24
25(def src-files (atom {}))
26
27(defn new-or-deleted-files? [files1 files2]
28  (let [s1 (into #{} files1)
29        s2 (into #{} files2)]
30    (not (= s1 s2))))
31
32(defn changes? [dir]
33  (let [files (into {} (map (fn [file]
34                         [(.getAbsolutePath file)
35                          (.lastModified file)])
36                       (find-clojurescript-sources-in-dir
37                        (File. dir))))]
38    (if (new-or-deleted-files? (keys files) (keys @src-files))
39      (boolean (reset! src-files files))
40      (if (some (fn [[path timestamp]]
41                  (not (= (get @src-files path) timestamp))) files)
42        (boolean (reset! src-files files))
43        false))))
44
45(defn wrap-compile [handler dir compile-fn]
46  (fn [request]
47    (when (changes? dir)
48      (println "Compiling ClojureScript files ...")
49      (compile-fn)
50      (println "Done."))
51    (handler request)))
52
53(defn app [dir compile-fn]
54     (-> handler
55         (wrap-file dir)
56         (wrap-compile dir compile-fn)))
57
58(def server nil)
59
60(defn devmode [dir compile-fn]
61     (run-jetty (app dir compile-fn) {:port 9090}))
62
63(defn start-devmode [dir compile-fn]
64  (alter-var-root (var server)
65                  (fn [v]
66                    (run-jetty (app dir compile-fn) {:port 9090 :join? false}))))
67
68(defn stop-devmode []
69  (when server
70    (.stop (.get server))))
71
72(comment
73  (cljsc/build "samples/hello/src" {:output-dir "samples/hello/out"
74                                    :output-to "samples/hello/hello.js"}))