Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to read all the forms in a clojure file?

Tags:

clojure

If I use

(-> "<file>.clj" 
    (slurp) 
    (read-string))

That will only read the first form in the file (typically the ns declaration). Is there a way to retrieve a list of forms from the file?

I'd prefer if no external libraries are used.

like image 915
zcaudate Avatar asked Jul 23 '14 23:07

zcaudate


1 Answers

This function opens a stream for Clojure to read from, and eagerly reads all forms from that stream until read throws an exception (this happens if there is a parse error, or there are no more forms to read).

(import '[java.io PushbackReader])
(require '[clojure.java.io :as io])

(defn read-all
  [file]
  (let [rdr (-> file io/file io/reader PushbackReader.)]
    (loop [forms []]
      (let [form (try (read rdr) (catch Exception e nil))]
        (if form
          (recur (conj forms form))
          forms)))))
like image 191
noisesmith Avatar answered Nov 24 '22 15:11

noisesmith