Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure - slurping files relative to project

Tags:

clojure

slurp

I have a project created using leningen in which I've saved clj files in the src/some_project_name directory (alongside the autogenerated core.clj file).

Also saved with these clj files are text files which I want to slurp from the clj files they live beside. My understanding is that reading files is relative to the working directory, and that the working directory will be wherever you've started the REPL from. I started the REPL from inside src/some_project_name where all the files are located, rather than root. (System/getProperty "user.dir") confirms this is the active directory.

However I've also read that slurp will look for files relative to your root directory, which is apparently what is happening despite starting the REPL from within src/some_project_name. I have to list the text file paths relative to the root directory in order for them to be found, e.g. "src/some_project_name/foo.txt" rather than just "foo.txt".

Before setting up a project, files were accessible relative to wherever the REPL was running (as I would expect). Now after setting up a project, they seem to only be accessible relative to root, regardless of where the REPL is started.

I have no problem with this, but I don't understand it. Is there some setup done by leningen that intercepts REPL evaluation and tells it to search from root rather than where the active directory is?

like image 466
Solaxun Avatar asked Jun 14 '17 00:06

Solaxun


1 Answers

I believe Leiningen REPLs use the project root as their working directory. (If not trampolined, they use a subprocess with the expected working directory – try jps -l after a lein repl, you should see two clojure.main processes.)

On a separate note, you may want to use clojure.java.io/resource to load files using classpath-relative paths. Such files would typically be placed in a resources folder – with Leiningen, this will typically be a sibling to src.

For example, if you place foo.txt in resources/some_project_name, you should be able to do the following:

(require '[clojure.java.io :as io])

(slurp (io/resource "some_project_name/foo.txt"))
like image 51
Michał Marczyk Avatar answered Nov 07 '22 14:11

Michał Marczyk