Finding vars from dynamically created namespaces in clojure - clojure

The following test fails:
(ns clojure_refactoring.rename-fn-test
(:use clojure.test))
(deftest test-fn-location
(in-ns 'refactoring-test-fn-rename)
(clojure.core/refer-clojure)
(defn a [b] (inc b))
(in-ns 'clojure_refactoring.rename-fn-test)
(is (not= (find-var 'refactoring-test-fn-rename/a)
nil))
(remove-ns 'refactoring-test-fn-rename))
That is, find-var (of a var I've just created, in a namespace I've just create) returns nil. This behaviour doesn't happen at the repl, where typing out the steps of the test works just fine.
Am I doing something wrong, or is this just something that doesn't work in clojure right now?

Updated to a version which really seems to do the intended thing, in contrast to my original answer...
This version seems to work:
(ns clojure-refactoring.rename-fn-test
(:use clojure.test
[clojure.contrib.with-ns :only [with-ns]]))
(deftest test-fn-location
(create-ns 'refactoring-test-fn-rename)
(with-ns 'refactoring-test-fn-rename
(clojure.core/refer-clojure)
(defn a [b] (inc b)))
(is (not= (find-var 'refactoring-test-fn-rename/a)
nil))
(remove-ns 'refactoring-test-fn-rename))
Also, you really need to change all occurrences of _ in namespace names to -, and the other way around for filenames.
With these changes in place, the test runs fine for me. (I haven't even tried to run it Apparently it still works without making the _ / - changes, but really, you need to do it! That's the accepted convention and things are not guaranteed to work if you don't follow it.)
For some reason, the code from the question seems to have been creating the Var a in the namespace the test was being defined in, thus (find-var 'clojure-refactoring.rename-fn-test/a) was returning a Var, whereas the test failed. With the above, (find-var 'clojure-refactoring.rename-fn-test/a) returns nil, as expected.

Related

How to set a dynamic var before aot compile

I want to have a *flag* variable in a given namespace that is set to true only when :aot compiling.
Is there a way to do that?
Your issue is kind of complicated because the definition of Clojure's own dynamic nature, so there's no rough equivalent of C's #ifdef or some other mechanism that happens at compile time, but here's a workaround:
I created a Leiningen project with lein new app flagdemo. This trick detects when AOT is performed, as #Biped Phill mentioned above, using the dynamic var *compile-files*, and saves a resource in the classpath of the compiled code:
The code looks like this:
(ns flagdemo.core
(:gen-class))
(def flag-path "target/uberjar/classes/flag.edn")
(defn write-flag [val]
(try (spit flag-path (str val)) (catch Exception _)))
(defn read-flag []
(some-> (clojure.java.io/resource "flag.edn") slurp clojure.edn/read-string))
(write-flag false)
(when clojure.core/*compile-files*
(write-flag true))
(defn -main
[& args]
(println "Flag is" (read-flag)))
So, when the file loads using, say, lein run or when you load it in the REPL, it will try to write an EDN file with the value false.
When you compile the package using lein uberjar, it loads the namespace and finds that *compile-files* is defined, thus it saves an EDN file that is packaged with the JAR as a resource.
The function read-flag just tries to load the EDN file from the classpath.
It works like this:
$ lein clean
$ lein run
Flag is nil
$ lein uberjar
Compiling flagdemo.core
Created /tmp/flagdemo/target/uberjar/flagdemo-0.1.0-SNAPSHOT.jar
Created /tmp/flagdemo/target/uberjar/flagdemo-0.1.0-SNAPSHOT-standalone.jar
$ java -jar target/uberjar/flagdemo-0.1.0-SNAPSHOT-standalone.jar
Flag is true
Credit to #Biped Phill and #Denis Fuenzalida for explaining it to me.
I think this works as well:
(def ^:dynamic *static* false)
(when (and *compile-files* boot/*static-flag*)
(alter-var-root #'*static* true))
then in profiles.clj:
:injections [(require 'boot)
(intern 'boot '*static-flag* true)]
First you need to indicate that a variable will change over time:
(def ^:dynamic *the-answer* nil)
*the-answer*
;=> nil
The ^:dynamic bit will allow that variable to be rebound later:
(binding [*the-answer* 42] *the-answer*)
;=> 42
ADDENDUM 1
Here's what would happen if you didn't use ^:dynamic:
(def *the-answer* nil)
(binding [*the-answer* 42] *the-answer*)
;=> [...] Can't dynamically bind non-dynamic var [...]
ADDENDUM 2
These kind of variables are commonly referred to as "earmuffs". The naming convention is unenforced but strongly encouraged.
Here's what happen in the REPL when you use this naming without declaring a dynamic variable:
(def *the-answer* nil)
; Warning: *the-answer* not declared dynamic and thus is not dynamically rebindable, but its name suggests otherwise. Please either indicate ^:dynamic *the-answer* or change the name. (/tmp/form-init7760459636905875407.clj:1)

Programmatically redef functions

I'm currently in the start of making a tool that should modify all the functions in another namespace, and the run the "main" function in that (other) namespace. Almost like mocking in unit-testing, but for another purpose. The first step to this is to redefine functions from another namespace. The first listing shows code that works, where I explicitly name the function to be replaced.
(ns one)
(defn a-fun []
(println "original"))
(defn caller []
(a-fun))
(ns two)
(with-redefs [one/a-fun #(println "replaced")]
(one/caller))
;; replaced
;; nil
The next step is getting the functions programmatically from the other namespace. This is where I have run into a wall. I've experimented much with ns-publics, but so far no luck. So I try to break the problem down. And the problem is that the replacement of the function is not working. The output should print "replaced" not "original".
(ns two)
(def target (ns-resolve 'one (symbol "a-fun")))
(def caller (ns-resolve 'one (symbol "caller")))
(with-redefs [target #(println "replaced")]
(caller))
;; original
;; nil
Now, the #'two/target shows #'one/a-fun when I evaluate it in the repl. I can call one/a-fun by entering ((ns-resolve 'one (symbol "a-fun"))) in the repl, so I don't understand what part is not working.
I've been through a lot of documentation today, and I'm not really getting any closer.
You could try using with-redefs-fn like so:
(defn p [] "old")
(with-redefs-fn
{(ns-resolve *ns* 'p) #(println "new")}
(fn []
(p)))
;; => new
This does mean that the body of with-redefs-fn must be a function that uses your redefined Vars.

Can reader tags be used with ClojureScript

In Clojure, adding custom reader tags is really simple
;; data_readers.clj (on classpath, eg. src/clj/)
{rd/qux datareaders.reader/my-reader}
;; Define a namespace containing the my-reader var:
(ns datareaders.reader)
(defn my-reader [x] 'y)
;; use special tag in other namespace. Readers have to be required first.
(require 'datareaders.reader)
(defn foo [x y]
(println #rd/qux x "prints y, not x due to reader tag."))
I am trying to achieve the same thing for ClojureScript but am getting an error that #rd/qux is not defined. I am using lein cljsbuild once to build the project. Is that a limitation of ClojureScript or is it that cljsbuild builds the project before the readers have been resolved? In that case, how can I force leiningen to load the readers namespace before cljsbuild is started?
EDIT: Note that this example intends to use reader tags within ClojureScript source code and not when reading auxilliary data via read-string.
This currently isn't possible, but will be as soon as #CLJS-1194 and #CLJS-1277 are fixed. Hopefully that will happen very soon.
If you wanted to do it, just rename data_readers.clj to data_readers.cljc and use conditional readers.
As an aside, what's your use case for this?
Both #CLJS-1194 and #CLJS-1277 are fixed, so this should work as expected.
The mechanism to add a custom reader tag in cljs is different. You have to call register-tag-parser! which takes a tag and a fn.
From the cljs reader tests:
(testing "Testing tag parsers"
(reader/register-tag-parser! 'foo identity)
(is (= [1 2] (reader/read-string "#foo [1 2]")))
Your example would be:
(cljs.reader/register-tag-parser! 'rd/qux (fn [x] 'y))
(defn foo [x y]
(println #rd/qux x "prints y, not x due to reader tag."))

including multiple files in a Clojure file

I am very new to Clojure. I know there is a way to include files in other files using a keyword like #include for C++. and i have done some digging and found a few things pointing to the keyword declare. Maybe I'm not using it correctly but it doesn't seem to work for me.
I am trying to write a function, for example, get_all_preds that uses another function predecessors, written in another file. the files are both under the directory src and each function is the only code in their respective files.
When i add (declare bar.clj) to the top of the foo.clj file i still get an error that bar cannot be found.
(defn get_all_preds
([tasks job]
(cond (empty? (predecessors tasks job)) (println "No predecessors")
:else (get_all_preds tasks (predecessors tasks job) (empty tasks))))
([tasks prereqs job]
(cond (empty? prereqs) job
:else (get_all_preds tasks (distinct (flatten (concat (predecessors tasks (first prereqs)) (rest prereqs))))
(distinct (cons (first prereqs) job))))))
(defn predecessors
[tasks-list job]
(cond (empty? tasks-list) 0
(= job (first (first tasks-list))) (rest (rest (first tasks-list)))
:else (predecessors (rest tasks-list) job)))
declare is for creating a var without binding it to a value.
The proper function for loading another Clojure namespace is require. To use require, you need to use namespaces, and create files with paths reflecting the semantic structure of the namespaces the files hold. The closest equivalent to #include is load, but this should be reserved for unstructured experiments where you might as well be copy / pasting into the repl, or unusual situations where namespaces are not appropriate.
A quick example:
in file src/foo/bar.clj:
(ns foo.bar)
(defn frob [] "hello")
in file src/foo/baz.clj:
(ns foo.baz
(:require [foo.bar :as bar]))
(defn frob [] (str (bar/frob) (bar/frob)))
(defn -main [& args]
(println (frob))
Running foo.baz/-main will print "hellohello" followed by a new line.
A Clojure namespace is a more structured concept than the compilation units of C, and is something that you can directly interact with in your code in a granular way. It will seem strange at first, but it allows fine grained control of what definitions are visible from various parts of your code (which in turn helps make code much easier to maintain and understand).

Setting Clojure "constants" at runtime

I have a Clojure program that I build as a JAR file using Maven. Embedded in the JAR Manifest is a build-version number, including the build timestamp.
I can easily read this at runtime from the JAR Manifest using the following code:
(defn set-version
"Set the version variable to the build number."
[]
(def version
(-> (str "jar:" (-> my.ns.name (.getProtectionDomain)
(.getCodeSource)
(.getLocation))
"!/META-INF/MANIFEST.MF")
(URL.)
(.openStream)
(Manifest.)
(.. getMainAttributes)
(.getValue "Build-number"))))
but I've been told that it is bad karma to use def inside defn.
What is the Clojure-idiomatic way to set a constant at runtime? I obviously do not have the build-version information to embed in my code as a def, but I would like it set once (and for all) from the main function when the program starts. It should then be available as a def to the rest of the running code.
UPDATE: BTW, Clojure has to be one of the coolest languages I have come across in quite a while. Kudos to Rich Hickey!
I still think the cleanest way is to use alter-var-root in the main method of your application.
(declare version)
(defn -main
[& args]
(alter-var-root #'version (constantly (-> ...)))
(do-stuff))
It declares the Var at compile time, sets its root value at runtime once, doesn't require deref and is not bound to the main thread. You didn't respond to this suggestion in your previous question. Did you try this approach?
You could use dynamic binding.
(declare *version*)
(defn start-my-program []
(binding [*version* (read-version-from-file)]
(main))
Now main and every function it calls will see the value of *version*.
While kotarak's solution works very well, here is an alternative approach: turn your code into a memoized function that returns the version. Like so:
(def get-version
(memoize
(fn []
(-> (str "jar:" (-> my.ns.name (.getProtectionDomain)
(.getCodeSource)
(.getLocation))
"!/META-INF/MANIFEST.MF")
(URL.)
(.openStream)
(Manifest.)
(.. getMainAttributes)
(.getValue "Build-number")))))
I hope i dont miss something this time.
If version is a constant, it's going to be defined one time and is not going to be changed you can simple remove the defn and keep the (def version ... ) alone. I suppose you dont want this for some reason.
If you want to change global variables in a fn i think the more idiomatic way is to use some of concurrency constructions to store the data and access and change it in a secure way
For example:
(def *version* (atom ""))
(defn set-version! [] (swap! *version* ...))