Scripts

Nicolas Ha edited this page Jun 6, 2016 · 18 revisions
Clone this wiki locally

It's possible to create self-contained, executable Clojure scripts that can bring in Maven dependencies, using a shebang. Here is an example that runs a game like Lunar Lander:

Put this into a file called lunarlander:

#!/usr/bin/env boot

(set-env! :dependencies '[[alandipert/hyperturbo "1.0.0"]])
(require '[alandipert.hyperturbo.lunar-lander :refer [run]])

(defn -main [& args]
  (run))

NOTE: Github wiki's syntax formatting is messed up and eats single quotes sometimes. The vector passed to set-env! above should be quoted.

Make the file executable:

chmod +x lunarlander

Run the script:

./lunarlander

Command-line args

If you define a -main function, it will be called and passed any command-line arguments.

(defn -main [& args]
  ...)

You can use Boot's built-in arg specification macro to get parsing of named args and automatic --help generation as well:

(require '[boot.cli :refer [defclifn]])

(defclifn -main
  [a awesome bool "Whether you want this app to be awesome or not. (Default true)"]
  ...)

In addition to the raw task *opts*, defclifn exports trailing-arguments bound to *args*:

(require '[boot.cli :refer [defclifn]])

(defclifn -main
  [a awesome bool "Whether you want this app to be awesome or not. (Default true)"]
  (println "Named parameters " *opts*)
  (println "List of arguments " *args*))

Calling boot tasks from the script

 (boot (some-task))