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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With