How to call a Clojure function from another project on my PC [duplicate] - clojure

This question already has answers here:
How can I set up leiningen to work with multiple projects?
(2 answers)
Closed 20 days ago.
I have two separate Leiningen projects on my PC (the result of running lein new alpha and lein new beta on the same directory). In addition to the usual core.clj file, the alpha project contains also a file called src/alpha/utils.clj with a function called plus.
Calling plus from it sibling file core.clj is no problem:
; src/alpha/core.clj
(ns alpha.core
(:require [alpha.utils :as u]))
(u/plus 2 3)
;; 5
The question is: How do I call that plus function from the beta project; esp.from src/beta/core.clj?
I found a similar-sounding question here on StackOverflow but that is about calling a function stored in a separate file in the same project (the cooperating namespaces (foo.bar and foo.quux.baz) have the same prefix).

As indicated by #possum, the solution is to create a symbolic link in a top-level subdirectory called checkouts in the beta project ("the client"). Here are the commands for MS Windows:
mkdir \path\to\beta\checkouts
cd \path\to\beta\checkouts
mklink /D alpha \path\to\alpha
Now it is possible to start the REPL on beta and run (require '[alpha.utils :as u])

Related

Load clj files through a leinigen-based repl

I'm trying to run snake.clj from the Programming Clojure (3rd ed) book examples. Said file starts with this declaration:
(ns examples.snake
(:import (java.awt Color Dimension)
(javax.swing JPanel JFrame Timer JOptionPane)
(java.awt.event ActionListener KeyListener))
(:require [examples.import-static :refer :all]))
(import-static java.awt.event.KeyEvent VK_LEFT VK_RIGHT VK_UP VK_DOWN)
; actual program omitted, see above link
Because I'm trying to run this on Windows, and the Clojure CLI Getting Started (recommended by the book) isn't yet available on Windows, I'm using leinigen instead. I've used these instructions to run:
lein repl from the examples folder containing my snake.clj file
=> (load-file "snake.clj")
But this gives me an error:
CompilerException java.io.FileNotFoundException: Could not locate examples/import_static__init.class or examples/import_static.clj on class path...
Somehow my setup with a repl through leinigen fails to let me use import-static like that.
As a workaround, I've used WSL Ubuntu to install the Clojure CLI and run it in the root of the book's source code folder, loading the snake file directly using the suggested code in the book ((require '[examples.snake :refer :all])). That loads just fine, I can even run (game) from the loaded file, but of course that crashes because WSL Ubuntu has no GUI options (it crashes on an "No X11 DISPLAY..." error).
I would assume that the leinigen-based setup I used failed because I had to do (load-file "import_static.clj") first. In fact, doing so is a fine workaround because then it all works (after also doing (use examples.snake)), but this doesn't scale very well for multiple/recursive imports.
What is the proper way to use leinigen (on Windows) to run such scripts? Should I've created a leinigen project file? Or is there a repl-trick to do this?
This isn't a direct answer to your question, but it'll help you get up and running.
The problem is that the files aren't on the class path because the author seems have decided to neglect using projects altogether, so leiningen can't help you. The/A solution is to create a new project, and stick everything in there.
How to get it working:
Go to a directory, start up a command prompt there, and run lein new snake. This will create a "snake" folder containing the barebones structure of a project, complete with a "project.clj".
From the files you downloaded, copy the entire "src" folder (that contains the examples folder), and paste it into the new "snake" folder so it overwrites the generated "src". You should now have a path "snake/src/examples/".
Now that "snake/src" is on the class path, it can be referenced as expected. Go to the root "snake" folder, start up a command prompt, and run
lein repl
(require '[examples.snake :as s])
(s/game)
The game window should pop up as expected.

access library functions in leiningen REPL

For the development of a library I started from a lein project, invoked like so:
lein new mylib
if I call lein install now, I can access my library in other projects. But trying to immidiately test the functions I wrote failed:
lein repl
...
(dir mylib.core)
Exception No namespace: mylib.core found clojure.core/the-ns (core.clj:4008)
Do I have to add something to the project.clj file maybe?
In order to use a library you must cause the code to be loaded - that it be on the classpath is not sufficient.
You can do this easily in an ns declaration in a file of course, but in the repl it can be easier to use (require '[my-lib.whatever :as w]) after which one can call (w/foo) (w/bar) etc. as expected. You can also use (in-ns 'my-lib.whatever) in order to switch to the namespace, but this will not give you a good result unless you have previously used require or use or load-file etc. to get the definitions first.
Let's say you created a new library named clj-foo.
% lein new clj-foo
Start your repl.
% cd clj-foo
% lein repl
In the repl, load the main entry point to your library and switch to its namespace.
(load-file "src/clj_foo/core.clj")
(ns clj-foo.core)
Now you're in the clj-foo.core namespace, make sure to add back in the repl ns to get things like doc available.
(use 'clojure.repl)
That's it. You're all set to start calling functions in your library. Note that other library files will be available from the clj-foo.core namespace if they were loaded by namespace declaration at the top of clj_foo/core.clj. If not, then you'll need to invoke load-file with their path as well.
If you make changes in core.clj. You can invoke load-file again to pick up the new code. As you progress, you can use cider to facilitate loading of individual functions and files. But that's for another question. :)
You need to add a dependency to use your library from another project. To do this add a vector (a tuple-2) to the vector that is the value of the :dependencies key in the project.clj file. Here's an example:
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.170"]
[org.clojure/core.async "0.2.371"]
[default-db-format "0.1.0-SNAPSHOT"]
[com.andrewmcveigh/cljs-time "0.3.14"]]
My own local library is called default-db-format. Its really no different to adding a dependency for com.andrewmcveigh/cljs-time.
As you say you can already do this, but are having trouble getting a REPL connection to the project of the library itself. When you go (in-ns 'some-path), you need the single quote in front of some-path. Note that some-path is a different thing to the name of your library.
Rather than use lein repl you can use the figwheel repl - if your project is setup with figwheel. My library has only one entry point and that is lein figwheel devcards. After that I had no problem going to a namespace and trying out a function:
cljs.user=> (in-ns 'default-db-format.core)
nil
default-db-format.core=> (check 1 2)
As noisesmith mentioned having a REPL in your IDE is the best setup. No fiddly typing just bring up pre-configured REPLs (per namespace) with the click of a button (or keystroke). Figwheel/Cursive setup instructions here.
I was also facing the same issue with the following configuration:
Leiningen 2.9.0 on Java 1.8.0_201 Java HotSpot(TM) 64-Bit Server VM
My file looks like this, and from the repl I desired to invoke the foo function
(ns cljtest.test
(:gen-class))
(defn foo [input]
(assoc {} "a" 123))
Both these approaches worked fine for me on the repl.
1)Switch to the appropriate name space:
cljtest.core=> (in-ns 'cljtest.test)
#object[clojure.lang.Namespace 0x90175dd "cljtest.test"]
cljtest.test=> (foo nil)
{"a" 123}
cljtest.test=>
2)Require the appropriate name space:
cljtest.core=> (require '[cljtest.test :as test])
nil
cljtest.core=> (test/foo nil)
{"a" 123}
cljtest.core=>

Can org-mode babel tangle produce leiningen directories?

We want to automate the production of a Leiningen project tree
entirely from an org-mode babel file. We want to do this so that we
can also create beautiful, typeset documentation via
org-latex-export-to-pdf. We want no less than full literate
programming in Clojure from org-mode.
The following command:
$ lein new ex1
produces a tree that looks like this:
ex1
ex1/.gitignore
ex1/doc
ex1/doc/intro.md
ex1/project.clj
ex1/README.md
ex1/resources
ex1/src
ex1/src/ex1
ex1/src/ex1/core.clj
ex1/test
ex1/test/ex1
ex1/test/ex1/core_test.clj
We want to do the identical thing just by running
org-babel-tangle, and no more, in our org-mode buffer in
emacs.
A difficulty arises: whereas tangle is happy to produce
files in existing subdirectories like src and test, it seems reluctant to produce the subdirectories if they don't exist. That means we must
create the directory structure by some other means -- unless we can
get tangle to do it for us, and that's the subject of this
StackOverflow question.
There are six files in the directory structure created by Leiningen. I can remove them all and re-create them from my org-file with BEGIN_SRC blocks such as the following
#+BEGIN_SRC clojure :tangle ./ex1/src/ex1/core.clj
(ns ex1.core)
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
#+END_SRC
Notice particularly the name of the subdirectory path
#+BEGIN_SRC clojure :tangle ./ex1/src/ex1/core.clj
All is well if our directory structure already exists. org-mode's tangle will
create or update all six files described above and create new files in any existing directory. We don't know how to
get tangle to produce the directories; it complains that there is no such
directory.
A copy of the desired .org file can be found here if you would like more details.
It is possible use the following header in the begin_src section,
:mkdirp yes
FYI There's now a lein project template for using org based projects:
https://github.com/thi-ng/thing-babel

How to use my own versions of Clojure libraries?

Say I made a change to a Clojure library (eg. added a parameter to the request-token in clj-oauth) and want to use that changed library in my project. What's the best way to do this, short of compiling the new library as a JAR and copying that to my project lib?
I want to be able to tweak the library and my project at the same time (preferably in the REPL). If I were doing this in Ruby, I would download and 'require' the gem, then reopen that class in my own project source and add or override the methods as needed.
You can hack directly at the REPL. Suppose you've got incanter on your classpath.
Start a REPL. The first thing we need to do is bring the incanter classes into it.
user> (require 'incanter.core)
nil
Now we can see the function incanter.core/matrix?
user> (incanter.core/matrix? 2)
false
We can look at the original source code:
user> (require 'clojure.repl)
nil
user> (clojure.repl/source incanter.core/matrix?)
(defn matrix?
" Test if obj is 'derived' incanter.Matrix."
([obj] (is-matrix obj)))
nil
Let's go and screw it up:
First change to the incanter.core namespace:
user> (in-ns 'incanter.core)
#<Namespace incanter.core>
Then we can redefine it, using the old source code as a crib:
incanter.core> (defn matrix? [obj] "hello")
#'incanter.core/matrix?
Unit test:
incanter.core> (matrix? 2)
"hello"
Switch back to the user namespace:
incanter.core> (in-ns 'user)
#<Namespace user>
Try it out:
user> (matrix? 2)
; Evaluation aborted.
There is no definition of user/matrix. We redefined it in the incanter.core namespace.
user> (incanter.core/matrix? 2)
"hello"
For experimenting at the repl, it's ok just to change source files and re-compile the single file (C-C C-k in emacs), or if you're in the right namespace, just re-evaluate the definition.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Now, if we want to make our valuable change permanent and available to other projects, it depends on how everything is set up.
I use maven for dependency management, so it would be a question of modifying the source file, and then re-running the build process for the library to compile the new version and install it into the local maven repository.
With a maven project, that should be as simple as
$ mvn install
A note about version numbers:
If you do make permanent modifications and use dependency management to coordinate the differences, then you should change the version number of your library, from maybe 1.2.0 to 1.2.0-johnshack-SNAPSHOT, or something that is unlikely to collide with the real thing when you want to use an unperverted version in another project. You wouldn't want a modified version finding its way into projects where it isn't welcome.
Then you modify your own project files to make sure that you use the hacked version where you want to, and the next time you start your repl, it should pull in the last hack that you installed.
You will need to reinstall again every time you want your changes to make their way into the repository, but that's actually probably a good thing.
Unfortunately, (and it was at this point that I started to wish that I had chosen a different example) Incanter turns out to be a leiningen project which is split into sub-modules in an ad-hoc scripty sort of way, so we need to figure out how it expects to be installed. The figuring out turned out to be quite hard, although the answer is easy. Leiningen sets my hair on fire.
You can get incanter's source here:
$ git clone http://github.com/liebke/incanter.git
and the relevant source file is:
~/incanter/modules/incanter-core/src/incanter/core.clj
Modify it to break the matrix? function, and then it turns out that what you have to do is:
Change the version numbers in both the top level project.clj, and also in the submodule project.clj.
Then you run lein install in the incanter-core directory, and then again in the top-level directory, and you have to do it in that order. I don't quite understand why.
At the moment all this seems needlessly complicated. I'm (fairly) sure that it will settle down as the tools mature.
If you're using (or wouldn't mind using) cake, check out the subproject dependencies section of the README. I think it might be exactly what you're looking for.
You upload it to clojars under a different name depend on that.

Clojure load files

I'm trying to set up a simple clojure project, and I'm not sure how to load files between the project. I'm sure that the answer is in the documentation, but I can't find a simple answer any where and I'm not sure where to look.
Essentially, my directory looks like this:
Clojure/
clojure/
clojure.jar
other clojure files
clojure-contrib/
clojure-contrib.jar
other contrib files
project/
main.clj
utils.clj
And I want main.clj to be something like this:
(ns project.main
(:require project.utils))
(greet)
and utils.clj to be something like this:
(ns project.utils)
(defn greet [] (println "Hello, World!"))
But that fails with:
Exception in thread "main" java.io.FileNotFoundException: Could not locate project/utils__init.class or project/utils.clj on classpath: (main.clj:1)
When I attempt to run it. My classpath includes the top Clojure/ directory and both jars. I also tried putting the project/ directory in the classpath as well, with no luck.
How do you set up a simple clojure project?
You don't mention what your environment is (i.e. Emacs/SLIME/Swank, vim/Vimclojure), so I'm going to assume you are trying to invoke it from the command line.
You need to have your Clojure/ project directory in the classpath:
java -cp path/to/clojure.jar:path/to/clojure-contrib.jar:path/to/Clojure ...
Make sure to check that paths are correct relative to current working directory. It needs to point to the root of your namespace (i.e. if running in Clojure/, the path is .).
In fact, your project layout Works On My Machine(tm), with the exception that I have use instead of require (but you should've got a different error anyway if you got to the point when Clojure could find all your files).
This answer I posted to another question should hopefully give you an idea of how your filenames should relate to namespace names for things to work. However, since your question is "how to set up a simple Clojure project", the following is a better start:
Go to GitHub and grab Leiningen.
Follow the instructions in the README. You'll end up doing something like
$ lein new my-project
$ cd my-project
# ... edit project.clj ...
$ lein deps
Hack away! You'll need to put your files in the correct places. That will mean putting your source files in the directory tree rooted at my-project/src, with your core namespace most likely residing at my-project/src/my_project/core.clj. But really, I've explained all the details in the answer linked to above, so please read it (and do leave a comment if I missed something). :-)
Leiningen will take care of the basic project layout and setting up the classpath for a REPL / swank / nailgun for you (if you haven't yet come across the latter two, you will soon -- but that's a separate topic, the swank part of which I have covered to a certain degree e.g. in this SO answer), so hopefully you'll never need to deal with the java -cp ... nonsense by hand. (The swank-related answer I linked to in the last parenthetical remark has details on how to set up swank with the correct classpath from within Emacs.)