Without any libraries, what you'd like to do is
(with-open [reader (java.io.PushbackReader.
(clojure.java.io/reader "src/my/file/ns_path.clj"))]
(loop [forms []]
(try
(recur (conj forms (read reader)))
(catch Exception ex
(println (.getMessage ex))
forms))))
but Clojure doesn't allow recur
across try
, so instead you do
(with-open [reader (java.io.PushbackReader.
(clojure.java.io/reader "src/my/file/ns_path.clj"))]
(loop [[ forms done? ]
[ [] false ]]
(if done?
forms
(recur (try
[(conj forms (read reader)) false]
(catch Exception ex
(println (.getMessage ex))
[forms true]))))))
You need to propagate the done?
signal yourself once reading is complete upon the EOF (end-of-file) error. I tried to layout the loop
bindings so they match up clearly top to bottom.
That will return a vector of all the forms in the file. From there, you can perform whatever transformations you want on the forms as data, and spit/print/write them back to the file again.
REQUISITE LEGAL DISCLAIMER REGARDING read
Don't run clojure.core/read
on code/data you didn't write or check yourself first. See this ClojureDocs comment for examples of what can go wrong.