Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In clojure, how do I get the file name of the current namespace?

Tags:

clojure

I am writing some code which needs to store data about the current namespace. My code is generating an ontology, and I need to assign URIs that need to persist between clojure invocations. These URIs are automatically generated, so it's not just a case of the code authors writing them.

I thought to use a similar mechanism to the way Emacs stores data; by generating some lisp forms and saving them in a file. These can then be evaluated when clojure starts and everyone is happy. The problem when using tools like leningen, these files will end up in the root directory.

I can build against standard directory conventions, but I'd prefer to get the data straight from clojure; I know the compiler adds source location data to clojure; is there a way that I can access this myself?

like image 971
Phil Lord Avatar asked Dec 19 '12 15:12

Phil Lord


1 Answers

If you're looking for the namespace in which code is currently executing at runtime, then you can simply look at the value of clojure.core/*ns*:

user> (defn which-ns? [] (str *ns*))
user> (which-ns?)
"user"
user> (ns user2)
user2> (which-ns?)
"user2"

If you're looking for the file in which a var or namespace was defined, then the source code location you're referring to is stored by the compiler as metadata on the var when it evaluates a def form:

user> (defn foo [x] (inc x))
user> (meta #'foo)
{:arglists ([x]), :ns #<Namespace user>, :name foo, :line 1, :file "NO_SOURCE_FILE"}

The "NO_SOURCE_FILE" is because you're evaluating a form entered in the REPL. If you evaluate code from a source file, then :file will point to the pathname of the source file.

like image 99
Alex Avatar answered Sep 25 '22 05:09

Alex