.clj" (slurp) (read-string)) This will only read the first form in th...">

Is there a way to read all forms in a clojure file?

If i use

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

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

I would prefer not to use external libraries.

+6
source share
2 answers

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 

`` ``

+5
source

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))))) 
+10
source

Source: https://habr.com/ru/post/972736/


All Articles