tag:devinwalters.com,2014:/feedø¡–¬˚•Devin∆Walters•˚¬–¡ø2018-03-01T13:59:38-08:00Devin Waltershttp://devinwalters.comSvbtle.comtag:devinwalters.com,2014:Post/attaching-clojure-deps-directly-to-the-source-file2018-03-01T13:59:38-08:002018-03-01T13:59:38-08:00attaching clojure deps directly to the source file<p>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 <code class="prettyprint">deps.edn</code> on disk. This is of course possible via <code class="prettyprint">-Sdeps</code>, but if you are using all the options, it can get a little long to enter it on the command line.</p>
<p>Here’s a file named <code class="prettyprint">foo.clj</code> with implanted deps information:</p>
<pre><code class="prettyprint lang-clojure">#!/usr/bin/doclj
'{:deps {cheshire {:mvn/version "5.8.0"}}}
(ns foo (:require [cheshire.core :as json]))
(println (json/parse-string "{\"a\": 1}"))
</code></pre>
<p><code class="prettyprint">chmod +x foo.clj && ./foo.clj</code> => <code class="prettyprint">{a 1}</code></p>
<p>The script to do this is here (I named it <code class="prettyprint">doclj</code>, but call it whatever you like).</p>
<pre><code class="prettyprint lang-sh">#!/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 -- "$@"
</code></pre>
<p>The major drawback here is that there are <u>two</u> calls to <code class="prettyprint">clj</code>, one to pull the first form out of the clojure file and read it, and the second to actually run the code.</p>
<p><em>UPDATE</em>: We are not alone. Eric Normand and Gary Fredericks also have some clever versions of same. Check them out <a href="https://twitter.com/ericnormand/status/1101153515584536576">here</a>.</p>