Modify Clojure source code file in clojure

It is not a bad idea, it is one of the major properties of lisp, code is data. you can read the clj file as a list using read-string modify it and write it back.


(ns tmp
  (:require [clojure.zip :as zip])
  (:use clojure.contrib.pprint))

(def some-var true)

;;stolen from http://nakkaya.com/2011/06/29/ferret-an-experimental-clojure-compiler/
(defn morph-form [tree pred f]
  (loop [loc (zip/seq-zip tree)]
    (if (zip/end? loc)
      (zip/root loc)
      (recur
       (zip/next
        (if (pred (zip/node loc))
          (zip/replace loc (f (zip/node loc)))
          loc))))))

(let [morphed (morph-form (read-string (str \( (slurp "test.clj")\)))
                          #(or (= 'true %)
                               (= 'false %))
                          (fn [v] (if (= 'true v)
                                   'false
                                   'true)))]
  (spit "test.clj"
        (with-out-str
          (doseq [f morphed]
            (pprint f)))))

This reads itself and toggles boolean values and writes it back.