Showing posts with label leiningen. Show all posts
Showing posts with label leiningen. Show all posts

Sunday, April 22, 2012

Scripting Clojure with Leiningen 2

[2012-May-14] Update: Fixed shebang for more Unix variants

What would it take to write scripts in Clojure (and run them on a terminal) the way we write them in Python, Ruby or Groovy? To pipe scripts together to accomplish bigger tasks? What would it take to throw in argument handling and transitive dependency management capabilities to such scripts? This post attempts to answer some of these questions while illustrating how to use the Leiningen plugin lein-exec to write Clojure scripts.

In particular, I assume you have Leiningen 2 and lein-exec 0.2.0 installed. The shebang feature may require that you use a *nix environment.

Command-line eval

Let us begin with evaluating tiny Clojure S-expressions on the command line.

$ lein2 exec -e "(println \"40 and 50 make\" (+ 40 50))"
40 and 50 make 90


Since the plugin can also evaluate the content from STDIN, we can also do the same thing as above by piping the Clojure code to the plugin:

$ echo "(println \"40 and 50 make\" (+ 40 50))" | lein2 exec
40 and 50 make 90


While clojure.core vars are available, vars from other namespaces may need an explicit reference:

$ lein2 exec -e "(use 'clojure.pprint) (pprint (map inc (range 10)))"
(1 2 3 4 5 6 7 8 9 10)


You would need similar quoting when writing the Clojure scripts due to the fact that S-expressions and scripts are simply evaluated by lein-exec.

Scripting

So, let's start with the first script as a file called fib10.clj that simply prints out first 10 numbers in the Fibonacci series:

;; Taken from http://j.mp/IiT8UK
(def fib-seq
  ((fn rfib [a b]
    (lazy-seq (cons a (rfib b (+ a b)))))
    0 1))

(println (take 10 fib-seq))


We can run it using lein-exec:

$ lein2 exec fib10.clj
(0 1 1 2 3 5 8 13 21 34)


OK, that is fine and dandy but how do we run fib10.clj as an executable? Here's how – you edit the file and put a shebang on the first line:

#!/bin/bash lein-exec

;; Taken from http://j.mp/IiT8UK
(def fib-seq
  ((fn rfib [a b]
    (lazy-seq (cons a (rfib b (+ a b)))))
    0 1))

(println (take 10 fib-seq))


Now you can run the fib10.clj as an executable:

$ chmod a+x fib10.clj
$ ./fib10.clj
(0 1 1 2 3 5 8 13 21 34)


Handling arguments

Scripts often need to work with command-line arguments. While using lein-exec arguments are always passed as string via the clojure.core/*command-line-args* dynamic var – first argument is the name of the script followed by the arguments to the script. Below is an example that takes name and scores and prints out name and average:

#!/bin/bash lein-exec

(defn err-println "println for STDERR"
  [& args]
  (binding [*out* *err*]
    (apply println args)))

(defn parse-int "Parse string as an integer. Abort if invalid."
  [n]
  (try (Integer/parseInt n)
    (catch NumberFormatException e
      (err-println (str \' n \')
                   "is not a valid integer")
      (System/exit 1))))

(defn avg "Given a sequence of numbers return their average."
  [nseq]
  (double (/ (apply + nseq) (count nseq))))

(if (>= (count *command-line-args*) 3)
  (println (second *command-line-args*)
           (avg (map parse-int (drop 2 *command-line-args*))))
  (do (err-println "Usage:" (first *command-line-args*)
                   "name score [score2 ..]")
    (System/exit 1)))


Upon running the script we can inspect how it responds to different input arguments:

$ chmod a+x ./avg.clj
$ ./avg.clj
Usage: ./avg.clj name score [score2 ..]
$ ./avg.clj "Nick Foster"
Usage: ./avg.clj name score [score2 ..]
$ ./avg.clj "Nick Foster" 45 78 65
Nick Foster 62.66666666666667
$ ./avg.clj "Nick Foster" notnum 45 78 65
'notnum' is not a valid integer


Pipeline

Pipeline is a very powerful concept that enables us to chain simple tasks using their STDIN and STDOUT to build more sophisticated tasks. As we would see below, it is entirely possible to build pipe together scripts written in Clojure by simply reading input from STDIN and writing result to STDOUT:

#!/bin/bash lein-exec

(loop []
  (let [c (.read *in*)]
    (when (>= c 0)
      (if (and (>= c (int \A)) (<= c (int \Z)))
        (print (Character/toLowerCase (char c)))
        (print (char c)))
      (recur))))


This script lcase.clj converts the input fed via STDIN to lowercase. Let us see it in action:

$ chmod a+x ./lcase.clj
$ echo "5 Quick brown foxes Jumped over 7 lazy dogs" | ./lcase.clj 
5 quick brown foxes jumped over 7 lazy dogs
$ tree | ./lcase.clj
..result omitted..
$ ls -l ~ | ./lcase.clj
..result omitted..


Transitive dependencies

Scripting with Clojure is fun! It would only be nicer to have the power of transitive dependency management baked into it. Well, pomegranate that is part of Leiningen 2 already makes that possible. lein-exec wraps pomegranate API to provide its own simpler API. The example below shows how to create a demo web service using lein-exec's deps function and Ring:

#!/bin/bash lein-exec

(use '[leiningen.exec :only  (deps)])
(deps '[[ring "1.0.1"]])

(defn handler
  [request]
  {:status 200
   :headers {}
   :body "Hello from Ring!"})

(use 'ring.adapter.jetty)
(run-jetty handler {:port 3000})


The deps function above from leiningen.exec namespace, which is in the lein-exec plugin itself. Here we pull the dpendency ring 1.0.1 which depends on a number of components under it. All those dependencies are pulled in as you run this script. Upon running something this is what you see:

$ chmod a+x ring.clj
$ ./ring.clj
2012-04-22 17:55:35.814:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2012-04-22 17:55:35.815:INFO::jetty-6.1.25
2012-04-22 17:55:35.824:INFO::Started SocketConnector@0.0.0.0:3000


Depending on whether ring is already downloaded to your local Maven repo, you may see the script downloading them first if they don't already exist.

Working in project context

At times you may want to run a script in the context of a project, so that the code being evaluated has access to the project CLASSPATH and other project resources. All of the above usages of lein-exec support an additional switch -p that does the same thing in project scope.

$ lein2 exec -ep "(use 'foo.bar) (baz :qux)"
..result omitted..
$ cat foo.clj | lein2 exec -p
.. result omitted..
$ lein2 exec -p foo.clj
.. result omitted..


The examples above are applicable when you run them in a project. If you use -p outside of a project it will complain about missing project!

Caveats

While the ability to script in Clojure is fascinating with all the shebang operator, pipeline and dependency management, it's important to know its limitations:

  • As widely known, JVM startup time is a pain even though Leiningen works hard to reduce it.
  • Eval'd code runs in the same JVM that runs Leiningen. There's no easy way to customize that.
  • Currently, the deps function pulls in dependencies only from Maven Central and Clojars.
  • When you run lein-exec in project context, the project map is not accessible to the eval'd code.

Few of these limitations may be addressed in future versions.


I think many Clojure beginners may see scripting as a good way to learn the language and explore Clojure libraries. At the same time, some of the Clojure app/tool projects may find it easy to distribute the app via a script instead of a full blown JAR with instructions on how to run it. Whatever is your impression, feedback and ideas, please share it in comments. You may like to follow me on Twitter: @kumarshantanu

Happy scripting with Clojure!

Thursday, July 15, 2010

Setup Emacs for development with Clojure/Leiningen

Edit: [2011 Oct 16] This post works only for Emacs-Starter-Kit 1, and is hence out of date
Edit: [2011 April 8] Works on Mac OS X (Intel)
Edit: [2010 October 10] Updated for Windows 7

This post is to describe how to set up Emacs for Clojure development on Mac, Linux and Windows. I assume you have setup a project structure using Leiningen already. You can follow this to setup Leiningen on Windows.

Swank-Clojure

You need to get Swank-Clojure running first.

1. Mention
:dev-dependencies [[swank-clojure "1.2.1"]]
in project.clj as described here: http://github.com/technomancy/leiningen

2. Get the dependencies:
lein deps

3. Start Swank
lein swank


Run Emacs

1. Download and install Emacs (at least version 22, recommended version 23 or higher). Mac users can get Emacs from here: http://emacsformacosx.com/. Windows users can download Emacs binaries from here and set the PATH: http://ftp.gnu.org/gnu/windows/emacs/

2. Delete any previous .emacs.d directory from home directory.

Mac/Linux:
mv ~/.emacs.d ~/.emacs.d.bak

Windows XP:
C:\Documents and Settings\<username>\Application Data

Windows 7:
C:\Users\<username>\AppData\Roaming

3. Install Git.

Windows users can download Git (MSys Git) from here and set the PATH: http://code.google.com/p/msysgit/downloads/list (version 1.7.3.1 is fine as of October 2010)

4. Clone the Emacs Starter kit in a working directory (this command clones the starter kit as .emacs.d directory):
git clone http://github.com/technomancy/emacs-starter-kit/ .emacs.d

OR
git clone git://github.com/technomancy/emacs-starter-kit.git .emacs.d

5. Copy the cloned .emacs.d directory to your home directory (~ on Mac/Linux, or "C:\Documents and Settings\<username>\Application Data" on Windows XP, or "C:\Users\<username>\AppData\Roaming" on Windows 7).

6. Run Emacs, and follow the steps below ("M" means "Meta", which is the Alt key i.e. M-x means Alt+x. Press Enter after each Emacs command.):

(a) Install necessary Emacs packages.
M-x package-list-packages

You will be presented with a list of modes. Select clojure-mode and swank-clojure packages by navigating to those items in the list and pressing "i" against each. After selection, press "x" to install.

(b) Connect to the Swank server.
M-x slime-connect

It will ask for hostname and port. Press Enter key for both and it will take the defaults. If all goes well upto this point, you will be connected to the Swank-Clojure running via Lein. Emacs would be ready for use.


Just in case you are an Emacs newbie and don't know how to exit, use the following keys to quit Emacs ("C" means "Control", i.e. C-x means Ctrl+x):
C-x C-c

Please let me know your feedback and suggestions.

Monday, June 21, 2010

Setup Leiningen on Windows

Edit: Leiningen 1.3.1 got better Windows support and you don't need to follow these instructions anymore. Get the Windows distribution from here: http://github.com/technomancy/leiningen/downloads, unzip into a folder of choice and include in PATH.

Leiningen is a build tool for Clojure. Using Leiningen has been described here and here.

Leiningen installs and runs well on Linux and Mac. As of June 2010, Leiningen has experimental support for Windows and lacks the self-install feature. This post describes how to setup Leiningen on Windows XP. No prior Ant / Maven / Lancet experience is assumed.

1. Establish a directory where you want to install Leiningen (create if it doesn't exist). Example:


D:\lein


Also, add it to your system PATH environment variable.

2. Download the Leiningen script (right-click and choose "Save as"). Save it as "lein.bat" to the location discussed above.

3. Download the Leiningen JAR (for Leiningen 1.1.0) to the same location discussed above. The JAR filename can be figured out by looking at the comments (REM statements) in the lein.bat file.

4. Set environment variable LEIN_JAR to "D:\lein\leiningen-1.1.0-standalone.jar", or the appropriate path where the file is saved.


Leiningen is setup now. To test the install, try these:


D:\temp>lein new hello
D:\temp>cd hello
D:\temp\hello>lein deps
D:\temp\hello>lein test


Please let me know your comments and feedback.

Disqus for Char Sequence