Skip to content
Dominic Monroe edited this page Feb 3, 2016 · 15 revisions

Snippets

  1. Access a version string at runtime, from a jar
  2. Accessing test resources

Access a version string at runtime, from a jar

Often it is desirable to print the version of the source used to build the jar. This may be a version string or a git hash. One way to achieve this is to add the version number to a file in the classpath:

;; in build.boot

(def version "1.0")

;; or from the environment
;; (def version (or (System/getenv "CIRCLE_SHA1") "SNAPSHOT"))

(deftask add-version-txt []
  (with-pre-wrap fs
    (let [t (tmp-dir!)]
      (spit (clojure.java.io/file t "version.txt") version)
      (-> fs (add-resource t) commit!))))

(deftask dist []
  (comp (pom :project 'my-project
             :version version)
        (add-version-txt)
        (uber)
        (aot :namespace '#{my-project.core})
        (jar :main 'my-project.core)))
;; in your app code

(defn get-version []
   (some-> "version.txt" clojure.java.io/resource slurp clojure.string/trim))

Accessing test resources

In lein, you just create a dev-resources directory for your testing resources. Boot is almost as easy. Just as you need to add the source files you use for testing to the source-paths, you also need to add to the resource-paths:

(deftask testing
  "Profile setup for running tests."
  []
  (set-env! :source-paths #(conj % "test/clj"))
  (set-env! :resource-paths #(conj % "dev-resources"))
  identity)

Task environment conflicts

Sometimes boot tasks have conflicts with your project. You can filter the dependencies that will be used on the pod using this: Source: Micha Niskin on Slack

(defmacro with-env
  [env & body]
  (let [orig (into {} (map #(vector % (gensym)) (keys env)))]
    `(let [~@(mapcat (fn [[k v]] [v `(get-env ~k)]) orig)]
       ~@(for [[k v] env] `(set-env! ~k ~v))
       (with-let [ret# (do ~@body)]
         ~@(for [[k v] orig] `(set-env! ~k ~v))))))

(defn filter-deps
  [deps]
  (->> (get-env :dependencies)
       (filterv #(some (set deps) ((juxt first (comp symbol name first)) %)))))

(defmacro with-deps
  [deps & body]
  `(with-env {:dependencies (filter-deps '~deps)} ~@body))

Usage: Project has deps that conflict with boot-jetty, so we filter all of those out when we instantiate the task--it will not create pods with the troublesome deps.

(deftask foo
  []
  (comp (watch)
        (hoplon)
        (cljs)
        (with-deps [boot-jetty] (serve))))
Clone this wiki locally