forked from technomancy/leiningen
/
eval.clj
266 lines (231 loc) · 9.93 KB
/
eval.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
(ns leiningen.core.eval
"Evaluate code inside the context of a project."
(:require [classlojure.core :as cl]
[clojure.java.io :as io]
[clojure.string :as string]
[cemerick.pomegranate :as pomegranate]
[leiningen.core.user :as user]
[leiningen.core.project :as project]
[leiningen.core.main :as main]
[leiningen.core.classpath :as classpath]))
;; # OS detection
(defn- get-by-pattern
"Gets a value from map m, but uses the keys as regex patterns, trying
to match against k instead of doing an exact match."
[m k]
(m (first (drop-while #(nil? (re-find (re-pattern %) k))
(keys m)))))
(def ^:private native-names
{"Mac OS X" :macosx "Windows" :windows "Linux" :linux
"FreeBSD" :freebsd "OpenBSD" :openbsd
"amd64" :x86_64 "x86_64" :x86_64 "x86" :x86 "i386" :x86
"arm" :arm "SunOS" :solaris "sparc" :sparc "Darwin" :macosx})
(def ^:private arch-options
{:x86 ["-d32"] :x86_64 ["-d64"]})
(defn get-os
"Returns a keyword naming the host OS."
[]
(get-by-pattern native-names (System/getProperty "os.name")))
(defn get-arch
"Returns a keyword naming the host architecture"
[]
(get-by-pattern native-names (System/getProperty "os.arch")))
(defn platform-nullsink []
(io/file (if (= :windows (get-os))
"NUL"
"/dev/null")))
;; # Preparing for eval-in-project
(defn run-prep-tasks
"Execute all the prep-tasks. A task can either be a string, or a
vector if it takes arguments. see :prep-tasks in sample.project.clj
for examples"
[{:keys [prep-tasks] :as project}]
(doseq [task prep-tasks]
(let [[task-name & task-args] (if (vector? task) task [task])
task-name (main/lookup-alias task-name project)]
(main/apply-task task-name (dissoc project :prep-tasks) task-args))))
;; Some tasks
(defonce ^{:doc "Block on this to wait till the project is fully prepped."}
prep-blocker (atom (promise)))
(defn prep
"Before we can run eval-in-project we need to prep the project by running
javac, compile, and any other tasks the project specifies."
[project]
;; This must exist before the project is launched.
(.mkdirs (io/file (:compile-path project "/tmp")))
(classpath/resolve-dependencies :dependencies project)
(run-prep-tasks project)
(.mkdirs (io/file (:compile-path project "/tmp")))
(deliver @prep-blocker true)
(reset! prep-blocker (promise)))
;; # Subprocess stuff
(defn native-arch-path
"Path to the os/arch-specific directory containing native libs."
[project]
(let [os (:os project (get-os))
arch (:arch project (get-arch))]
(if (and os arch)
(io/file (:native-path project) (name os) (name arch)))))
(defn- as-str [x]
(if (instance? clojure.lang.Named x)
(name x)
(str x)))
(defn- d-property [[k v]]
(format "-D%s=%s" (as-str k) v))
;; TODO: this would still screw up with something like this:
;; export JAVA_OPTS="-Dmain.greeting=\"hello -main\" -Xmx512m"
(defn- join-broken-arg [args x]
(if (= \- (first x))
(conj args x)
(conj (vec (butlast args))
(str (last args) " " x))))
(defn ^:internal get-jvm-opts-from-env [env-opts]
(and (seq env-opts)
(reduce join-broken-arg []
(.split (string/trim env-opts) " "))))
(defn- get-jvm-args
"Calculate command-line arguments for launching java subprocess."
[project]
(let [native-arch-path (native-arch-path project)]
`(~@(get-jvm-opts-from-env (System/getenv "JVM_OPTS"))
~@(:jvm-opts project)
~@(get arch-options (:arch project))
~@(map d-property {:clojure.compile.path (:compile-path project)
(str (:name project) ".version") (:version project)
:file.encoding (or (System/getProperty "file.encoding") "UTF-8")
:clojure.debug (boolean (or (System/getenv "DEBUG")
(:debug project)))})
~@(if (and native-arch-path (.exists native-arch-path))
[(d-property [:java.library.path native-arch-path])])
~@(if-let [{:keys [host port non-proxy-hosts]} (classpath/get-proxy-settings)]
[(d-property [:http.proxyHost host])
(d-property [:http.proxyPort port])
(d-property [:http.nonProxyHosts non-proxy-hosts])]))))
(defn- pump [reader out]
(let [buffer (make-array Character/TYPE 1000)]
(loop [len (.read reader buffer)]
(when-not (neg? len)
(.write out buffer 0 len)
(.flush out)
(Thread/sleep 100)
(recur (.read reader buffer))))))
(def ^:dynamic *dir*
"Directory in which to start subprocesses with eval-in-project or sh."
(System/getProperty "user.dir"))
(def ^:dynamic *env*
"Environment map with which to start subprocesses with eval-in-project or sh.
Merged into the current environment unless ^:replace metadata is attached."
nil)
(def ^:dynamic *pump-in*
"Rebind this to false to disable forwarding *in* to subprocesses."
true)
(defn- overridden-env
"Returns an overridden version of the current environment as an Array of
Strings of the form name=val, suitable for passing to Runtime#exec."
[env]
(->> (if (:replace (meta env))
env
(merge {} (System/getenv) env))
(filter val)
(map #(str (name (key %)) "=" (val %)))
(into-array String)))
(defn sh
"A version of clojure.java.shell/sh that streams in/out/err."
[& cmd]
(let [env (overridden-env *env*)
proc (.exec (Runtime/getRuntime) (into-array cmd) env (io/file *dir*))]
(.addShutdownHook (Runtime/getRuntime)
(Thread. (fn [] (.destroy proc))))
(with-open [out (io/reader (.getInputStream proc))
err (io/reader (.getErrorStream proc))
in (io/writer (.getOutputStream proc))]
(let [pump-out (doto (Thread. (bound-fn [] (pump out *out*))) .start)
pump-err (doto (Thread. (bound-fn [] (pump err *err*))) .start)
pump-in (Thread. (bound-fn [] (pump *in* in)))]
(when *pump-in* (.start pump-in))
(.join pump-out)
(.join pump-err))
(.waitFor proc))))
;; work around java's command line handling on windows
;; http://bit.ly/9c6biv This isn't perfect, but works for what's
;; currently being passed; see http://www.perlmonks.org/?node_id=300286
;; for some of the landmines involved in doing it properly
(defn- form-string [form eval-in]
(if (and (= (get-os) :windows) (not= :trampoline eval-in))
(let [s (pr-str (pr-str form))] (subs s 1 (dec (.length s))))
(pr-str form)))
(defn- classpath-arg [project]
(if (:bootclasspath project)
[(apply str "-Xbootclasspath/a:"
(interpose java.io.File/pathSeparatorChar
(classpath/get-classpath project)))]
["-classpath" (string/join java.io.File/pathSeparatorChar
(classpath/get-classpath project))]))
(defn shell-command
"Calculate vector of strings needed to evaluate form in a project subprocess."
[project form]
`(~(or (:java-cmd project) (System/getenv "JAVA_CMD") "java")
~@(classpath-arg project)
~@(get-jvm-args project)
"clojure.main" "-e" ~(form-string form (:eval-in project))))
;; # eval-in multimethod
(defmulti eval-in
"Evaluate the given form in various contexts."
;; Force it to be a keyword so that we can accept symbols too. That
;; way ^:replace and ^:displace metadata can be applied.
(fn [project _] (keyword (name (:eval-in project :subprocess)))))
(defmethod eval-in :subprocess [project form]
(binding [*dir* (:root project)]
(let [exit-code (apply sh (shell-command project form))]
(when (pos? exit-code)
(throw (ex-info "Subprocess failed" {:exit-code exit-code}))))))
(defonce trampoline-forms (atom []))
(defonce trampoline-profiles (atom []))
(defmethod eval-in :trampoline [project form]
(swap! trampoline-forms conj form)
(swap! trampoline-profiles conj (select-keys project
[:dependencies :source-paths
:resource-paths :test-paths])))
(defmethod eval-in :classloader [project form]
(when-let [classpath (map io/file (classpath/ext-classpath project))]
(cl/wrap-ext-classloader classpath))
(let [classpath (map io/file (classpath/get-classpath project))
classloader (cl/classlojure classpath)]
(doseq [opt (get-jvm-args project)
:when (.startsWith opt "-D")
:let [[_ k v] (re-find #"^-D(.*?)=(.*)$" opt)]]
(if (= k "java.library.path")
(cl/alter-java-library-path!
(constantly (string/split v (re-pattern java.io.File/pathSeparator))))
(System/setProperty k v)))
(try (cl/eval-in classloader form)
(catch Exception e
(println (str "Error evaluating in classloader: "
(class e) ":" (.getMessage e)))
(.printStackTrace e)
(throw (ex-info "Classloader eval failed" {:exit-code 1}))))))
(defmethod eval-in :leiningen [project form]
(when (:debug project)
(System/setProperty "clojure.debug" "true"))
;; :dependencies are loaded the same way as plugins in eval-in-leiningen
(project/load-plugins project :dependencies)
(doseq [path (classpath/get-classpath project)]
(pomegranate/add-classpath path))
(doseq [opt (get-jvm-args project)
:when (.startsWith opt "-D")
:let [[_ k v] (re-find #"^-D(.*?)=(.*)$" opt)]]
(System/setProperty k v))
(eval form))
(defn eval-in-project
"Executes form in isolation with the classpath and compile path set correctly
for the project. If the form depends on any requires, put them in the init arg
to avoid the Gilardi Scenario: http://technomancy.us/143"
([project form init]
(prep project)
(eval-in project
`(do ~init
~@(:injections project)
(set! ~'*warn-on-reflection*
~(:warn-on-reflection project))
~form)))
([project form] (eval-in-project project form nil)))