我想在clojure中的沙盒命名空间中运行加载文件
问题描述:
我是新来Clojure和乐趣/教育我正在写lein的通用迁移框架。该系统需要做的一件事是从磁盘读取clojure文件,然后运行up
函数或down
函数。我认为这个文件应该可以在一个临时名称空间中进行评估,但我无法正常工作。这是我到目前为止有:我想在clojure中的沙盒命名空间中运行加载文件
(def user-namespace (create-ns 'leiningen.generic-migrate.user-eval))
(defn load-migration-file [file]
(binding [*ns* user-namespace]
(load-file (.getAbsolutePath file))
(keys (ns-publics *ns*))))
这给我的错误:
Unable to resolve symbol: defn in this context
我的问题是,什么是使用负载文件,然后运行一个定义函数的最好的方法,没有风险有人在我的名字空间覆盖东西?
答
(defmacro with-ns
"Evaluates body in another namespace. ns is either a namespace
object or a symbol. This makes it possible to define functions in
namespaces other than the current one."
[ns & body]
`(binding [*ns* (the-ns ~ns)]
[email protected](map (fn [form] `(eval '~form)) body)))
(defmacro with-temp-ns
"Evaluates body in an anonymous namespace, which is then immediately
removed. The temporary namespace will 'refer' clojure.core."
[& body]
`(try
(create-ns 'sym#)
(let [result# (with-ns 'sym#
(clojure.core/refer-clojure)
[email protected])]
result#)
(finally (remove-ns 'sym#))))