Writing Leiningen Plugins 101

I'm trying to switch, building my projects using Ant to leiningen. Almost all of them requires customs tasks such as building native executables, move files around etc. Which requires I have to come up with a lein plugin for each ant task, unfortunately not much documentation exists about writing lein plugins, this post collects bits and pieces of information I gathered over the web.

To begin with lein tasks are functions named "your-task" defined in the namespace "leiningen.your-task". They take a project argument containing information defined in defproject and command-line arguments. For simple tasks or quickly testing something, you can create a tasks directory in your project root and a .lein-classpath file containing tasks. Then you can put your tasks in there, like tasks/leiningen/foo.clj.

(ns leiningen.foo)
(defn foo [project & args] (println "Hello Foo!!"))

Now lein should have a new task named foo, running it should print "Hello Foo!!". Since tasks are just functions, making a task depend on another task is as easy as calling depencies on top of the function.

(ns leiningen.bar)

(defn bar [projects & args] 
  (apply leiningen.foo/foo projects args)
  (println "Hello Bar!!"))

Now running bar task should give you, "Hello Foo!!" and "Hello Bar!!". For sharing plugins across projects create a separate lein project for the plugin, after creating a Jar with "lein jar", push it to clojars then add your plugin as a user-level plugin for your project.