Anton Harald
Anton Harald

Reputation: 5964

code as data: update a clojure file programmatically

Say you are using leiningen and you want to add a dependency to your project.clj file.

Instead of opening your editor and add this manually it must be possible to do so programmatically via the clojure language. Like so:

(update-in :dependencies conj ["enlive" "1.1.3"])

lein's update-in is not helping, since it does not make the change for good.

How would you guys do this?

Upvotes: 2

Views: 375

Answers (1)

nha
nha

Reputation: 18005

Since project.clj is a Clojure file, you could put this at the top of your project.clj file :

(def my-deps [["enlive" "1.1.3"]])

..and later on :

 :dependencies my-deps

Which means that you could even slurp an .edn file that you could edit however you want. I actually have this on the top of my build.boot (equivalent of project.clj but for boot) :

(defn slurp-deps []
  (read-string (slurp "resources/deps.edn")))

And I use it like so :

:dependencies (slurp-deps)

The rest would just be updating your map and writing it back to the same .edn file.

If you want to reload your dependencies after that have a look at this SO question.

Note : as an alternative, I know that this is the way to do things in a REPL with boot, and that it will fetch/load the dependencies :

boot.user=> (set-env! 
       #_=>   :resource-paths #{"src"}
       #_=>   :dependencies '[["enlive" "1.1.3"]])

Upvotes: 2

Related Questions