Compiling Clojure Code with Leiningen
First of all, I would like to push a little for Programming Clojure by Stuart Halloway. It’s fantastic if you have prior experience with the Java ecosystem or a LISP, it might be a bit over your head if you don’t have either. Luckily I’m coming from PicoLisp so I’m OK, I just need to get up to speed with the Java.
The reason for Clojure for me is that PicoLisp is lacking the libraries, and since Clojure is on the JVM it doesn’t.
Currently I’m trying to figure out if I should go for more general storage solutions like Hadoop, Cassandra and Riak, or PicoLisp’s OODB but that will have to come later, first I need to learn the basics.
A theme that is running through Programming Clojure is some kind of wrapper around Ant called Lancet. As far as I could understand it will let you get away from the XML. However I quickly learned that Leiningen is a step further and seems to be the preferred build tool in the Clojure community.
So the first basic task here is to build a jar that when executed will simply print Hello Fred if you pass Fred to it, just like in the Clojure compile example, but using Leiningen instead of Clojure’s compile.
To be able to work properly with Leiningen I’ve put the lein shell script in /opt/clojure which is also where my test project is in the form of /opt/clojure/testapp. Installing Leiningen is dead easy, no need for explanations there but we need to put the script on our path by first doing nano ~/.bashrc and putting this in it:
PATH=$PATH:/opt/clojure
export PATH
Don’t forget to restart your shell after that. Now you should be able to simply call lein no matter where you are.
So every project needs a project.clj, I suppose this is Leiningen’s version of build.xml. Mine looks like this:
(defproject testapp "0.1"
:source-path "src/clj"
:java-fork "true"
:javac-debug "true"
:dependencies [[org.clojure/clojure "1.1.0"]
[org.clojure/clojure-contrib "1.1.0"]]
:namespaces [theapp.hello])
In the testapp folder we have the project.clj and then a src/clj/theapp/hello.clj file which looks like this:
(ns theapp.hello
(:gen-class))
(defn -main
[greetee]
(println (str "Hello " greetee "!")))
Running lein jar in the testapp folder will pull down the dependencies clojure core and clojure contrib which seems to be two things you basically need in every Clojure project, they end up in the lib folder which will be created if it wasn’t there already. The build result is testapp.jar.
Now we can run our application like this:
java -cp classes:lib/clojure-1.1.0.jar:lib/clojure-contrib-1.1.0.jar:testapp.jar theapp.hello Fred
Note that we need to put both core and contrib on the class path, simply doing java testapp.jar Fred won’t work.
All in all, Leiningen is a great thing that seems to be making Clojure development go on rails.