This repository has been archived by the owner on Sep 16, 2021. It is now read-only.
forked from healthfinch/depstar
-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
uberjar.clj
701 lines (630 loc) · 28.9 KB
/
uberjar.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
(ns hf.depstar.uberjar
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.deps.alpha :as t]
[clojure.tools.deps.alpha.gen.pom :as pom]
[clojure.tools.logging :as logger]
[clojure.tools.namespace.find :as tnsf])
(:import (java.io File InputStream PushbackReader)
(java.nio.file CopyOption LinkOption OpenOption
StandardCopyOption StandardOpenOption
FileSystem FileSystems Files
FileVisitOption FileVisitResult FileVisitor
Path)
(java.nio.file.attribute FileAttribute FileTime)
(java.util.jar JarInputStream JarEntry)
(org.apache.logging.log4j.core.config.plugins.processor PluginCache))
(:gen-class))
(set! *warn-on-reflection* true)
(def ^:dynamic ^:private *debug* nil)
(def ^:dynamic ^:private *exclude* nil)
(def ^:dynamic ^:private *debug-clash* nil)
(def ^:dynamic ^:private *verbose* nil)
(defn- env-prop
"Given a setting name, get its Boolean value from the environment,
validate it, and return the value (or nil if no setting is present)."
[setting]
(let [env-setting (str "DEPSTAR_" (str/upper-case setting))
prop-setting (str "depstar." (str/lower-case setting))]
(when-let [level (or (System/getenv env-setting)
(System/getProperty prop-setting))]
(case level
"true" true
"false" false ;; because (if (Boolean. "false") :is-truthy :argh!)
(throw (ex-info (str "depstar " setting
" should be true or false")
{:level level
:env (System/getenv env-setting)
:property (System/getProperty prop-setting)}))))))
(defonce ^:private ^FileSystem FS (FileSystems/getDefault))
;; could add (StandardOpenOption/valueOf "SYNC") here as well but that
;; could slow things down (and hasn't yet proved to be necessary)
(def ^:private open-opts (into-array OpenOption [(StandardOpenOption/valueOf "CREATE")]))
(def ^:private copy-opts (into-array CopyOption [(StandardCopyOption/valueOf "REPLACE_EXISTING")]))
(def ^:private visit-opts (doto
(java.util.HashSet.)
(.add (FileVisitOption/valueOf "FOLLOW_LINKS"))))
(defonce ^:private errors (atom 0))
(defonce ^:private multi-release? (atom false))
(defn- path
^Path [s]
(.getPath FS s (make-array String 0)))
(def ^:private log4j2-plugins-file
"Log4j2 has a very problematic binary plugins cache file that needs to
be merged -- but it's going away in 3.0.0 apparently because it keeps
breaking build tools... We use log4j's plugin processor to merge it."
"META-INF/org/apache/logging/log4j/core/config/plugins/Log4j2Plugins.dat")
(defn- legal-file? [filename]
(re-find #"(?i)^(META-INF/)?(COPYRIGHT|NOTICE|LICENSE)(\.(txt|md))?$" filename))
(defn- clash-strategy
[filename]
(cond
(re-find #"^data_readers.clj[sc]?$" filename)
:merge-edn
(re-find #"^META-INF/services/" filename)
:concat-lines
(legal-file? filename)
:concat-no-dupe
(= log4j2-plugins-file filename)
:log4j2-surgery
:else
:noop))
(defmulti ^:private clash
(fn [filename _in _target]
(let [strategy (clash-strategy filename)]
(when *debug-clash*
(logger/info "Found" filename "in multiple dependencies,"
(case strategy
:merge-edn "merged as EDN."
:concat-lines "concatenated it."
:concat-no-dupe "concatenated (if not dupe)."
:log4j2-surgery "merged."
:noop "ignoring duplicate.")))
strategy)))
(defmethod clash
:merge-edn
[_ in target]
(let [;; read but do not close input stream
f1 (edn/read (PushbackReader. (io/reader in)))
;; read and then close target since we will rewrite it
f2 (with-open [r (PushbackReader. (Files/newBufferedReader target))]
(edn/read r))]
(when-let [conflict (some #(when-let [v (get f1 %)]
(when-not (= v (get f2 %))
{:tag % :new v :old (get f2 %)}))
(keys f2))]
(prn {:warning "conflicting data-reader mapping"
:conflict conflict
:in target}))
(with-open [w (Files/newBufferedWriter target open-opts)]
(binding [*out* w]
(prn (merge f1 f2))))))
(defmethod clash
:concat-lines
[_ in target]
(let [f1 (line-seq (io/reader in))
f2 (Files/readAllLines target)]
(with-open [w (Files/newBufferedWriter target open-opts)]
(binding [*out* w]
(run! println (-> (vec f1)
(conj "\n")
(into f2)))))))
(def ^:private no-dupe-files (atom {}))
(defmethod clash
:concat-no-dupe
[filename in target]
(let [f1 (line-seq (io/reader in))
f2 (Files/readAllLines target)
filename (str/lower-case filename) ; avoid case-sensitivity
prev-files (get @no-dupe-files filename)]
;; if we haven't already seen this exact same file before, concatenate it:
(when-not (some #(= % f1) prev-files)
(with-open [w (Files/newBufferedWriter target open-opts)]
(binding [*out* w]
(run! println (-> (vec f1)
(conj "\n")
(into f2)))))
(swap! no-dupe-files update filename (fnil conj []) f1))))
(defmethod clash
:log4j2-surgery
[_filename ^InputStream in ^Path target]
(let [cache (PluginCache.)
temp1 (Files/createTempFile "plugins" ".dat" (make-array FileAttribute 0))
temp2 (Files/createTempFile "plugins" ".dat" (make-array FileAttribute 0))
^java.util.Collection
urls (map #(.toURL (.toUri ^Path %)) [temp1 temp2])]
(Files/copy in temp1 ^"[Ljava.nio.file.CopyOption;" copy-opts)
(Files/copy target temp2 ^"[Ljava.nio.file.CopyOption;" copy-opts)
(.loadCacheFiles cache (.elements (java.util.Vector. urls)))
(with-open [os (Files/newOutputStream target open-opts)]
(.writeCache cache os))))
(defmethod clash
:default
[_ _in _target]
;; do nothing, first file wins
nil)
(def ^:private exclude-patterns
"Filename patterns to exclude. These are checked with re-matches and
should therefore be complete filename matches including any path."
[#"project.clj"
#"\.keep"
#".*\.pom$" #"module-info\.class$"
#"(?i)META-INF/.*\.(?:MF|SF|RSA|DSA)"
#"(?i)META-INF/(?:INDEX\.LIST|DEPENDENCIES)(?:\.txt)?"])
(defn- excluded?
[filename]
(or (some #(re-matches % filename) exclude-patterns)
(some #(re-matches % filename) *exclude*)))
(defn- copy!
;; filename drives strategy
[filename ^InputStream in ^Path target last-mod]
(if-not (excluded? filename)
(if (Files/exists target (make-array LinkOption 0))
(clash filename in target)
(do
;; remember legal files as we copy them:
(if (legal-file? filename)
(let [content (line-seq (io/reader in))]
(with-open [w (Files/newBufferedWriter target open-opts)]
(binding [*out* w]
(run! println content)))
(swap! no-dupe-files
update (str/lower-case filename) (fnil conj []) content))
(Files/copy in target ^"[Ljava.nio.file.CopyOption;" copy-opts))
(when last-mod
(Files/setLastModifiedTime target last-mod))))
(when *debug*
(prn {:excluded filename}))))
(defn- consume-jar
[^Path path f]
(with-open [is (-> path
(Files/newInputStream (make-array OpenOption 0))
java.io.BufferedInputStream.
JarInputStream.)]
(loop []
(when-let [entry (.getNextJarEntry is)]
(f is entry)
(recur)))))
(defn- classify
[entry]
(let [p (path entry)
symlink-opts (make-array LinkOption 0)]
(if (Files/exists p symlink-opts)
(cond
(Files/isDirectory p symlink-opts)
:directory
(and (Files/isRegularFile p symlink-opts)
(re-find #"\.jar$" (.toString p)))
:jar
:else :unknown)
:not-found)))
(defmulti ^:private copy-source*
(fn [src _dest _options]
(classify src)))
(defmethod copy-source*
:jar
[src dest options]
(when-not (= :thin (:jar-type options))
(when *verbose* (println src))
(consume-jar (path src)
(fn [inputstream ^JarEntry entry]
(let [^String name (.getName entry)
last-mod (.getLastModifiedTime entry)
target (.resolve ^Path dest name)]
(if (.isDirectory entry)
(Files/createDirectories target (make-array FileAttribute 0))
(do (Files/createDirectories (.getParent target) (make-array FileAttribute 0))
(try
(when (.startsWith name "META-INF/versions/")
(reset! multi-release? true))
(copy! name inputstream target last-mod)
(catch Throwable t
(prn {:error "unable to copy file"
:name name
:exception (class t)
:message (.getMessage t)})
(swap! errors inc))))))))))
(defn- copy-directory
[^Path src ^Path dest]
(let [copy-dir
(reify FileVisitor
(visitFile [_ p attrs]
(let [f (.relativize src p)
last-mod (Files/getLastModifiedTime p (make-array LinkOption 0))]
(when *verbose* (println (str (.toString src) "/" (.toString f))))
(with-open [is (Files/newInputStream p (make-array OpenOption 0))]
(copy! (.toString f) is (.resolve dest (.toString f)) last-mod)))
FileVisitResult/CONTINUE)
(preVisitDirectory [_ p attrs]
(Files/createDirectories (.resolve dest (.toString (.relativize src p)))
(make-array FileAttribute 0))
FileVisitResult/CONTINUE)
(postVisitDirectory [_ p ioexc]
(if ioexc (throw ioexc) FileVisitResult/CONTINUE))
(visitFileFailed [_ p ioexc] (throw (ex-info "Visit File Failed" {:p p} ioexc))))]
(Files/walkFileTree src visit-opts Integer/MAX_VALUE copy-dir)
:ok))
(defmethod copy-source*
:directory
[src dest _options]
(when *verbose* (println src))
(copy-directory (path src) dest))
(defmethod copy-source*
:not-found
[src _dest _options]
(prn {:warning "could not find classpath entry" :path src}))
(defmethod copy-source*
:unknown
[src _dest _options]
(if (excluded? src)
(when *debug* (prn {:excluded src}))
(prn {:warning "ignoring unknown file type" :path src})))
(defn- copy-source
[src dest options]
(copy-source* src dest options))
(defn- calc-project-basis
"Given the options map, use tools.deps.alpha to read and merge the
applicable `deps.edn` files, combine the specified aliases, calculate
the project basis (which will resolve/download dependencies), and
return the calculated project basis."
[{:keys [aliases repro]
:or {aliases [] repro true}}]
(let [{:keys [root-edn user-edn project-edn]} (t/find-edn-maps)
deps (t/merge-edns (if repro
[root-edn project-edn]
[root-edn user-edn project-edn]))
combined (t/combine-aliases deps aliases)]
;; this could be cleaner, by only selecting the "relevant"
;; keys from combined for each of these three uses (but
;; I'm waiting for the dust to settle on a possible higher-
;; level API appearing in tools.deps.alpha itself):
(t/calc-basis (t/tool deps combined)
{:resolve-args combined
:classpath-args combined})))
(comment
(calc-project-basis {})
(calc-project-basis {:aliases [:trial]})
,)
(defn- parse-classpath [^String cp]
(vec (.split cp (System/getProperty "path.separator"))))
(defn- first-by-tag
[pom-text tag]
(-> (re-seq (re-pattern (str "<" (name tag) ">([^<]+)</" (name tag) ">")) pom-text)
(first)
(second)))
(defn- sync-gav
"Given a pom file and options, return the group/artifact IDs and
the version. These are taken from the options, if present, otherwise
they are read in from the pom file.
Returns a hash map containing the group/artifact IDs, and the version.
If the values provided in the options differ from those in the pom file,
the pom file will be updated to reflect those in the options hash map.
Throw an exception if we cannot read them from the pom file."
[pom-file {:keys [artifact-id group-id version]}]
(let [pom-text (slurp pom-file)
artifact-id' (first-by-tag pom-text :artifactId)
group-id' (first-by-tag pom-text :groupId)
version' (first-by-tag pom-text :version)
result {:artifact-id (or artifact-id artifact-id')
:group-id (or group-id group-id')
:version (or version version')}]
(when-not (and (:group-id result) (:artifact-id result) (:version result))
(throw (ex-info "Unable to establish group/artifact and version!" result)))
;; do we need to override any of the pom.xml values?
(when (or (and artifact-id artifact-id' (not= artifact-id artifact-id'))
(and group-id group-id' (not= group-id group-id'))
(and version version' (not= version version')))
(logger/info "Updating pom.xml file to"
(str "{"
(:group-id result) "/"
(:artifact-id result) " "
"{:mvn/version \"" (:version result) "\"}"
"}"))
(spit pom-file
(cond-> pom-text
(and artifact-id artifact-id' (not= artifact-id artifact-id'))
(str/replace-first (str "<artifactId>" artifact-id' "</artifactId>")
(str "<artifactId>" artifact-id "</artifactId>"))
(and group-id group-id' (not= group-id group-id'))
(str/replace-first (str "<groupId>" group-id' "</groupId>")
(str "<groupId>" group-id "</groupId>"))
(and version version' (not= version version'))
(->
(str/replace-first (str "<version>" version' "</version>")
(str "<version>" version "</version>"))
;; also replace <tag> if it matched <version> with any prefix:
(str/replace-first (re-pattern (str "<tag>([^<]*)"
(java.util.regex.Pattern/quote version')
"</tag>"))
(str "<tag>$1" version "</tag>"))))))
result))
(defn- copy-pom
"Using the pom.xml file in the current directory, build a manifest
and pom.properties, and add both those and the pom.xml file to the JAR."
[^Path dest ^File pom-file {:keys [jar-type main-class] :as options}]
(let [{:keys [artifact-id group-id version]}
(sync-gav pom-file options)
jdk (str/replace (System/getProperty "java.version")
#"_.*" "")
build-now (java.util.Date.)
last-mod (FileTime/fromMillis (.getTime build-now))
manifest (str "Manifest-Version: 1.0\n"
"Built-By: depstar\n"
"Build-Jdk: " jdk "\n"
(when @multi-release?
"Multi-Release: true\n")
(when-not (= :thin jar-type)
(str "Main-Class: "
(if main-class
(str/replace main-class "-" "_")
"clojure.main")
"\n")))
properties (str "#Generated by depstar\n"
"#" build-now "\n"
"version=" version "\n"
"groupId=" group-id "\n"
"artifactId=" artifact-id "\n")
maven-dir (str "META-INF/maven/" group-id "/" artifact-id "/")]
(when *verbose* (println ""))
(logger/info "Processing pom.xml for"
(str "{" group-id "/" artifact-id
" {:mvn/version \"" version "\"}}"))
(with-open [is (io/input-stream (.getBytes manifest))]
(when *verbose*
(println "\nGenerating META-INF/MANIFEST.MF:\n")
(print manifest))
(let [target (.resolve dest "META-INF/MANIFEST.MF")]
(Files/createDirectories (.getParent target) (make-array FileAttribute 0))
(copy! "MANIFEST.MF" is target last-mod)))
(with-open [is (io/input-stream (.getBytes properties))]
(when *verbose*
(println (str "\nGenerating " maven-dir "pom.properties:\n"))
(print properties))
(let [target (.resolve dest (str maven-dir "pom.properties"))]
(Files/createDirectories (.getParent target) (make-array FileAttribute 0))
(copy! "pom.properties" is target last-mod)))
(with-open [is (io/input-stream pom-file)]
(when *verbose*
(println (str "\nCopying pom.xml to " maven-dir "pom.xml")))
;; we don't need the createDirectories call here
(copy! "pom.xml" is
(.resolve dest (str maven-dir "pom.xml"))
last-mod))))
(defn- print-help []
(println "library usage:")
(println " clojure -M:depstar -m hf.depstar.jar MyProject.jar")
(println "uberjar usage:")
(println " clojure -M:depstar -m hf.depstar.uberjar MyProject.jar")
(println " clojure -M:depstar -m hf.depstar.uberjar -C -m project.core MyProject.jar")
(println "options:")
(println " -C / --compile -- enable AOT compilation for uberjar")
(println " -P / --classpath <cp> -- override classpath")
(println " -D / --debug-clash -- print warnings about clashing jar items")
(println " (can be useful if you are not getting the files you expect in the JAR)")
(println " -h / --help -- show this help (and exit)")
(println " -J / --jar -- an alternative way to specify the JAR file")
(println " -m / --main -- specify the main namespace (or class)")
(println " -n / --no-pom -- ignore pom.xml")
(println " -v / --verbose -- explain what goes into the JAR file")
(println " -X / --exclude <regex> -- exclude files via regex")
(println "note: the -C and -m options require a pom.xml file"))
(defn build-jar
"Core functionality for depstar. Can be called from a REPL or as a library.
Returns a hash map containing:
* `:success` -- `true` or `false`
* `:reason` -- if `:success` is `false`, this explains what failed:
* `:help` -- help was requested
* `:no-jar` -- the `:jar` option was missing
* `:aot-failed` -- `:compile` was requested but it threw an exception
* `:copy-failure` -- one or more files could not be copied into the JAR
Additional detail about success and failure is also logged."
[{:keys [aot artifact-id classpath compile-ns debug-clash exclude
group-id help jar jar-type main-class no-pom pom-file
sync-pom verbose version]
:or {jar-type :uber}
:as options}]
(cond
help
{:success false :reason :help}
(not jar)
{:success false :reason :no-jar}
:else
(let [jar (some-> jar str) ; ensure we have a string
main-class (some-> main-class str) ; ensure we have a string
options (assoc options ; ensure defaulted/processed options present
:jar jar
:jar-type jar-type
:main-class main-class)
basis (calc-project-basis options)
^File
pom-file (io/file (or pom-file "pom.xml"))
new-pom (not (.exists pom-file))
_
(when sync-pom
(logger/info "Synchronizing" (.getName pom-file))
(pom/sync-pom
{:basis basis
:params (cond-> {:target-dir (or (.getParent pom-file) ".")
:src-pom (.getPath pom-file)}
(and new-pom group-id artifact-id)
(assoc :lib (symbol (name group-id) (name artifact-id)))
(and new-pom version)
(assoc :version version))}))
_ (.getParent (io/file "pom.xml"))
do-aot
(if main-class
(cond (= :thin jar-type)
(logger/warn "Ignoring :main-class because a 'thin' JAR was requested!")
no-pom
(logger/warn "Ignoring :main-class because :no-pom was specified!")
(not (.exists pom-file))
(logger/warn "Ignoring :main-class because no 'pom.xml' file is present!")
:else
aot)
(when aot
(logger/warn "Ignoring :aot because -m / --main was not specified!")))
cp (or (some-> classpath (parse-classpath))
(:classpath-roots basis))
;; expand :all using tools.namespace:
compile-ns (if (= :all compile-ns)
(into []
(comp
(filter #(= :directory (classify %)))
(map io/file)
(mapcat tnsf/find-namespaces-in-dir))
cp)
compile-ns)
;; force AOT if compile-ns explicitly requested:
do-aot (or do-aot (seq compile-ns))
;; compile main-class at least (if also do-aot):
compile-ns (or compile-ns [main-class])
tmp-c-dir (when do-aot
(Files/createTempDirectory "depstarc" (make-array FileAttribute 0)))
cp (into (cond-> [] do-aot (conj (str tmp-c-dir))) cp)
java (or (System/getenv "JAVA_CMD") "java")
windows? (-> (System/getProperty "os.name")
(str/lower-case)
(str/includes? "windows"))
cmd-args (fn [s]
(let [args [java
"-cp"
(str/join (System/getProperty "path.separator") cp)
"clojure.main"
"-e"
(str "(binding,[*compile-path*,"
(pr-str (str tmp-c-dir))
"],(compile,'"
(name s)
"))")]]
(if windows?
(mapv #(str/replace % "\"" "\\\"") args)
args)))
compile-fn (fn [s]
(logger/info "Compiling" s "...")
(let [p (.start (ProcessBuilder.
^"[Ljava.lang.String;"
(into-array
String
(cmd-args s))))]
(.waitFor p)
(let [stderr (slurp (.getErrorStream p))]
(when (seq stderr) (println stderr))
(if (zero? (.exitValue p))
false ; no AOT failure
(do
(logger/error (str "Compilation of " s " failed!"))
true)))))
aot-failure (when do-aot (some compile-fn compile-ns))]
(if aot-failure
{:success false :reason :aot-failed}
(let [tmp-z-dir (Files/createTempDirectory "depstarz" (make-array FileAttribute 0))
dest-name (str/replace jar #"^.*[/\\]" "")
jar-path (.resolve tmp-z-dir ^String dest-name)
jar-file (java.net.URI. (str "jar:" (.toUri jar-path)))
zip-opts (doto (java.util.HashMap.)
(.put "create" "true")
(.put "encoding" "UTF-8"))]
;; copy everything to a temporary ZIP (JAR) file:
(with-open [zfs (FileSystems/newFileSystem jar-file zip-opts)]
(let [tmp (.getPath zfs "/" (make-array String 0))]
(reset! errors 0)
(reset! multi-release? false)
(logger/info "Building" (name jar-type) "jar:" jar)
(binding [*debug* (env-prop "debug")
*exclude* (mapv re-pattern exclude)
*debug-clash* debug-clash
*verbose* verbose]
(run! #(copy-source % tmp options) cp)
(when (and (not no-pom) (.exists pom-file))
(copy-pom tmp pom-file options)))))
;; move the temporary file to its final location:
(let [dest-path (path jar)
parent (.getParent dest-path)]
(when parent (.. parent toFile mkdirs))
(Files/move jar-path dest-path copy-opts))
;; was it successful?
(if (pos? @errors)
{:success false :reason :copy-failure}
{:success true}))))))
(defn ^:no-doc run*
"Deprecated entry point for REPL or library usage.
Returns a hash map containing:
* `:success` -- `true` or `false`
* `:reason` -- if `:success` is `false`, this explains what failed:
* `:help` -- help was requested
* `:no-jar` -- the `:jar` option was missing
* `:aot-failed` -- `:compile` was requested but it threw an exception
* `:copy-failure` -- one or more files could not be copied into the JAR
More detail about success and failure is printed to stdout."
[options]
(logger/warn "DEPRECATED: hf.depstar.uberjar/run* -- use hf.depstar.uberjar/build-jar instead.")
(build-jar options))
(defn ^:no-doc build-jar-as-main
"Command-line entry point for `-X` (and legacy `-M`) that performs
checking on arguments, offers help, and calls `(System/exit 1)` if
the JAR-building process encounters errors."
[options]
(let [result (build-jar options)]
(if (:success result)
(shutdown-agents)
(do
(case (:reason result)
:help (print-help)
:no-jar (print-help)
:aot-failed (logger/error "AOT FAILED") ;nil ; details already printed
:copy-failure (logger/error "Completed with errors!"))
(System/exit 1)))))
(defn ^:no-doc run
"Deprecated entry point for uberjar invocations via `-X`."
[options]
(logger/warn "DEPRECATED: hf.depstar.uberjar/run -- use hf.depstar/uberjar instead.")
(build-jar-as-main options))
(defn ^:no-doc parse-args
"Returns a hash map with all the options set from command-line args.
Essentially deprecated since -M -m invocation is deprecated."
[args]
(let [merge-args (fn [opts new-arg]
(cond (contains? new-arg :exclude)
(update opts :exclude (fnil conj []) (:exclude new-arg))
(and (contains? new-arg :jar)
(contains? opts :jar))
(do
(logger/warn "Multiple JAR files specified:"
(:jar opts) "and" (:jar new-arg))
(logger/warn "Ignoring" (:jar opts)
"and using" (:jar new-arg) "\n")
(merge opts new-arg))
:else
(merge opts new-arg)))]
(loop [opts {} args args]
(if (seq args)
(let [[arg more]
(case (first args)
("-C" "--compile") [{:aot true} (next args)]
("-P" "--classpath") [{:classpath (fnext args)} (nnext args)]
("-D" "--debug-clash") [{:debug-clash true} (next args)]
("-h" "--help") [{:help true} (next args)]
("-J" "--jar") [{:jar (fnext args)} (nnext args)]
("-m" "--main") [{:main-class (fnext args)} (nnext args)]
("-n" "--no-pom") [{:no-pom true} (next args)]
("-S" "--suppress-clash") [{:debug-clash false} (next args)]
("-v" "--verbose") [{:verbose true} (next args)]
("-X" "--exclude") [{:exclude (fnext args)} (nnext args)]
(if (= \- (ffirst args))
(do
(logger/warn "Unknown option" (first args) "ignored!")
[{} (next args)])
[{:jar (first args)} (next args)]))]
(recur (merge-args opts arg) more))
opts))))
(defn ^:no-doc -main
"Deprecated entry point for uberjar invocation via -M."
[& args]
(logger/warn "DEPRECATED: -M -m hf.depstar.uberjar -- use -X hf.depstar/uberjar instead.")
(build-jar-as-main (assoc (parse-args args) :jar-type :uber)))
(comment
(parse-args ["foo.jar" "-v"])
(parse-args ["foo.jar" "-V"])
(parse-args ["-X" "a" "foo.jar" "-X" "b"])
nil)