Is there a way to read all forms in a clojure file?
Insert a [ and ] at the beginning and end of the line to make the entire file into one vector shape:
user> (clojure.pprint/pprint (read-string (str "[" (slurp "/home/arthur/hello/project.clj") "]"))) [(defproject hello "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "http://example.com/FIXME" :license {:name "Eclipse Public License", :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.5.1"] [clj-time "0.6.0"]] :source-paths ["dev"])] nil `` ``
This function opens the stream for Clojure to read and eagerly reads all forms from this stream until reading throws an exception (this happens if there is a parsing 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)))))