attaching clojure deps directly to the source file

I thought it would be a neat idea to implant a deps map directly inside of a clojure source file so it could be run without having an associated deps.edn on disk. This is of course possible via -Sdeps, but if you are using all the options, it can get a little long to enter it on the command line.

Here’s a file named foo.clj with implanted deps information:

#!/usr/bin/doclj
'{:deps {cheshire {:mvn/version "5.8.0"}}}
(ns foo (:require [cheshire.core :as json]))
(println (json/parse-string "{\"a\": 1}"))

chmod +x foo.clj && ./foo.clj => {a 1}

The script to do this is here (I named it doclj, but call it whatever you like).

#!/bin/sh

set -e

if [ $# -eq 0 ]; then
    echo "usage: doclj <file> [args ...]"
    exit 1;
fi

FILE=$1

shift

/bin/clj -Sdeps "$(clj --eval '(fnext (read-string (slurp "'"$FILE"'")))')" -i $FILE -- "$@"

The major drawback here is that there are two calls to clj, one to pull the first form out of the clojure file and read it, and the second to actually run the code.

UPDATE: We are not alone. Eric Normand and Gary Fredericks also have some clever versions of same. Check them out here.

 
6
Kudos
 
6
Kudos