Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: how to get the path of a running JAR/root source directory?

Tags:

path

jar

clojure

In Java there's a simple way to get path of a running jar file:

MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()

But in Clojure we do not have class name, only namespace and functions. Same thing applies to the uncompiled scripts/REPL.

So my questions are:

  1. How can we find a path to the running jar file?
  2. How can we find a path to uncompiled source files?
like image 672
ffriend Avatar asked Mar 14 '12 01:03

ffriend


1 Answers

By default the name of your class is the name of your AOT-compiled namespace (that's what gen-class is for), so you can simply use the namespace's class.

(ns foo.core
  (:gen-class))

(defn this-jar
  "utility function to get the name of jar in which this function is invoked"
  [& [ns]]
  ;; The .toURI step is vital to avoid problems with special characters,
  ;; including spaces and pluses.
  ;; Source: https://stackoverflow.com/q/320542/7012#comment18478290_320595
  (-> (or ns (class *ns*))
      .getProtectionDomain .getCodeSource .getLocation .toURI .getPath))

(defn -main [& _]
  (println (this-jar foo.core)))

Result of running:

$ java -cp foo-0.1.0-SNAPSHOT-standalone.jar foo.core
/home/rlevy/prj/foo/target/foo-0.1.0-SNAPSHOT-standalone.jar
like image 148
rplevy Avatar answered Jan 05 '23 01:01

rplevy