How to start writing Lein Plugins?
Leiningen is powerful and build tool for Clojure. I have been using lein mainly for my clojure apps, and it had all been only for lein test
, lein run
, lein clean
, lein uberjar
.
Recently, I was trying to CICD my clojure application for Lambda function and I was unable to upload uberjar with my lein deploy
to the repository. So, I started looking into code to get it deploy with uberjar. But I ended up writing my own custom plugin to create uberjar and deploy uberjar to my repository. So, here I am sharing how easy it is to start writing lein plugins.
Before starting to write one, let’s see how lein invokes custom plugins. When you write lein plugin
, lein will basically call your plugin method. So let’s say we write lein say-phrase
, lein will call say-phrase
function from say-phrase.clj and passes project.clj converted to {} and optional args that we might provide. Ok, let’s get our hands dirty, we will create a plugin, that will take a optional argument.
$ lein say-phrase
Hello World!
$ lein say-phrase morning
Good Morning!
So, this is how structure of our project directory should look. I am naming the project directory as “say-phrase-plugin”.
say-phrase-plugin
|__project.clj
|__src
|__leiningen
|__say_phrase.clj
Yup, that easy-peazy. You need to put your plugin name file in src/leiningen folder. That’s how leiningen will locate your plugin file. You might also want to look at how are built-in leiningen plugins are located.
Also, there is another way to create. Yes, you guessed it right, just use
lein new plugin say-phrase --to-dir say-phrase-template
Ok, let’s take a look at project.clj. You will need :eval-in-leiningen true
to be set in your project.clj.
Now, let’s take a look at src/leiningen/say_phrase.clj
(ns leiningen.say-phrase)(defn say-phrase
"I don't do a lot."
[project & args]
(println "Hi!"))
We will be writing our code in say-phrase
function. We use condp
to check phrase and use leiningen.core.main/info
to print out to console. Avoid using println
, use leiningen.core.main/warn
, leiningen.core.main/info
, and leiningen.core.main/debug
.
And, that’s it. To test it locally, you can change the version to 0.1.0
instead of 0.1.0-SNAPSHOT
, and run below command.
$ lein install
Created /<path-to-dir>/say-phrase-template/target/say-phrase-0.1.0.jar
Wrote /<path-to-dir>/say-phrase-template/pom.xml
Installed jar and pom into local repo.
To use say-phrase plugin in your existing app, add [say-phrase "0.1.0"]
to :plugins
section. And you are all set.
$ cd <to-existing-app>
$ lein say-phrase
Hello World!
$ lein say-phrase morning
Good Morning!
Now, if you are all happy with your plugin and you want to push it to Clojar, use lein deploy clojar
, it will prompt you for your username and password.
$ cd <to-say-phrase-template>
$ lein deploy clojars
And your plugin is deployed to Clojar.
Hope this helps and you get start with writing many more plugins and publish!