/
classpath.clj
1453 lines (1236 loc) · 50.5 KB
/
classpath.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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns shadow.build.classpath
(:require
[clojure.tools.reader.reader-types :as readers]
[clojure.tools.reader :as reader]
[clojure.edn :as edn]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.set :as set]
[cljs.tagged-literals :as tags]
[shadow.debug :as dbg :refer (?> ?-> ?->>)]
[shadow.jvm-log :as log]
[shadow.spec :as ss]
[shadow.build.resource :as rc]
[shadow.cljs.util :as util]
[shadow.build.cache :as cache]
[shadow.build.ns-form :as ns-form]
[shadow.build.config :as config]
[shadow.build.cljs-bridge :as cljs-bridge]
[shadow.build.npm :as npm]
[shadow.build.data :as data])
(:import (java.io File)
(java.util.jar JarFile JarEntry Attributes$Name)
(java.net URL URLDecoder)
(java.util.zip ZipException)
(shadow.build.closure JsInspector)
[java.nio.file Paths Path]
[com.google.javascript.jscomp CompilerOptions$LanguageMode CompilerOptions SourceFile]
[com.google.javascript.jscomp.deps ModuleNames]
[javax.xml.parsers DocumentBuilderFactory]
[org.w3c.dom Element]))
(set! *warn-on-reflection* true)
(def CACHE-TIMESTAMP (util/resource-last-modified "shadow/build/classpath.clj"))
(defn get-classpath []
;; in case of a dynamically modified classpath
;; we can't use java.class.path so its used last
;; shadow-cljs-launcher sets shadow.class.path
;; boot-clj sets boot.class-path
(let [classpath-entries
(-> (or (System/getProperty "shadow.class.path")
(System/getProperty "boot.class.path")
(System/getProperty "java.class.path"))
(.split File/pathSeparator)
(->> (into [] (map io/file))))]
;; java -cp helper.jar foo.main
;; java supports a single jar with a manifest Class-Path entry to further
;; expand the classpath. sometimes used when the classpath is too long
;; on Windows to be invoked as a command. the original jar will likely be empty
(if (not= 1 (count classpath-entries))
classpath-entries
(let [^File entry (nth classpath-entries 0)]
;; don't think it is even possible to get here
;; with one classpath entry that isn't a jar but who knows
(if-not (.endsWith (-> entry (.getName) (.toLowerCase)) ".jar")
classpath-entries
(let [jar-file (JarFile. entry)
manifest (.getManifest jar-file)
cp-from-jar
(-> (.getMainAttributes manifest)
(.getValue Attributes$Name/CLASS_PATH))]
;; no Class-Path:, might be uberjar?
(if-not cp-from-jar
classpath-entries
(->> (str/split cp-from-jar #"\s")
;; spec says they must he urls, so assuming file:/...
;; spec also allows remote urls but unlikely we have that?
;; FIXME: should likely check just in case
(map (fn [s] (-> (URL. s) (.getPath) (io/file))))
(vec)))))))))
(defn service? [x]
(and (map? x) (::service x)))
(defn inspect-js [{:keys [compiler] :as state} {:keys [resource-name url] :as rc}]
;; avoid parsing cljsjs files since they are standalone bundles
;; and can never require/import anything, we don't want to ever include them anyways
(when-not (str/starts-with? resource-name "cljsjs/")
(let [source
(slurp url)
;; all requires are collected into
;; :js-requires ["foo" "bar/thing" "./baz]
;; all imports are collected into
;; :js-imports ["react"]
{:keys [js-requires
js-imports
js-errors
js-warnings
js-invalid-requires
js-language
js-str-offsets
goog-module
goog-module-legacy-namespace
goog-requires
goog-provides]
:as info}
(JsInspector/getFileInfoMap
compiler
;; SourceFile/fromFile seems to leak file descriptors
(SourceFile/fromCode resource-name source))
rc (assoc rc :inspect-info info)]
(cond
;; goog.provide('thing')
;; goog.require('foo')
;; goog.module('some.thing')
(or (seq goog-module)
(seq goog-provides)
(seq goog-requires)
(= resource-name "goog/base.js"))
;; FIXME: support require/import in ClosureJS
(let [deps
(-> []
(cond->
(not= resource-name "goog/base.js")
(conj 'goog))
(into (map util/munge-goog-ns) goog-requires))]
(-> rc
(assoc :type :goog
:requires (into #{} deps)
:goog-src (or (= resource-name "goog/base.js")
(and (seq goog-provides) (every? #(str/starts-with? % "goog.") goog-provides)))
:source source
:provides
(-> #{}
;; for goog files make both namespaces available
;; to match cljs behaviour where _ is always converted to -
;; goog.i18n.DateTimeSymbols_en
(into (map symbol) goog-provides)
;; goog.i18n.DateTimeSymbols-en
(into (map util/munge-goog-ns) goog-provides))
:deps deps)
(cond->
(seq goog-module)
(-> (assoc :ns (util/munge-goog-ns goog-module)
:goog-module goog-module
:goog-module-legacy-namespace goog-module-legacy-namespace
:goog-src (str/starts-with? goog-module "goog."))
(update :provides conj (util/munge-goog-ns goog-module) (symbol goog-module)))
(= resource-name "goog/base.js")
(update :provides conj 'goog)
)))
;; require("foo")
;; import ... from "foo"
;; might be no require/import/exports
;; externs files will hit this
:else
(let [js-deps
(->> (concat js-requires js-imports)
(distinct)
(map npm/maybe-convert-goog)
(into []))
js-deps
(cond-> js-deps
(:uses-global-buffer info)
(conj "buffer")
(:uses-global-process info)
(conj "process"))
ns
(-> (ModuleNames/fileToModuleName resource-name)
(symbol))]
(-> info
(merge rc)
(assoc :source source
:type :js
:classpath true
:ns ns
:provides #{ns}
:requires #{}
:deps js-deps)))
))))
(defn inspect-cljs
"looks at the first form in a .cljs file, analyzes it if (ns ...) and returns the updated resource
with ns-related infos"
[{:keys [url resource-name macros-ns] :as rc}]
(try
(let [{:keys [name deps requires] :as ast}
(cljs-bridge/get-resource-info
resource-name
(or (:source rc) ;; nREPL load-file supplies source
(slurp url))
;; since the classpath instance is shared we use the default
;; on resolve the resource should be inspected again
#{:cljs})
provide-name
(if-not macros-ns
name
(symbol (str name "$macros")))]
(-> rc
(assoc
:ns-info (dissoc ast :env)
:ns provide-name
:provides #{provide-name}
:requires (into #{} (vals requires))
:macro-requires
(-> #{}
(into (-> ast :require-macros vals))
(into (-> ast :use-macros vals)))
:deps deps)
(cond->
macros-ns
(assoc :macros-ns true :source-ns name))))
(catch Exception e
;; when the ns form fails to parse or any other related error occurs
;; we guess the ns from the filename and proceed to the real error
;; occurs again when actually trying to compile
;; otherwise the error ends up unrelated in the log
;; with the build error just being a generic "not available"
(log/debug-ex e ::inspect-failure {:macro-ns macros-ns :url url})
(let [guessed-ns (util/filename->ns resource-name)]
(assoc rc
:ns guessed-ns
:inspect-error true
:inspect-error-data (ex-data e)
:provides #{guessed-ns}
:requires '#{goog cljs.core}
:macro-requires #{}
:deps '[goog cljs.core])
))))
(defn inspect-resource
[state {:keys [resource-name url] :as rc}]
(cond
(util/is-js-file? resource-name)
(inspect-js state rc)
(util/is-cljs-file? resource-name)
(->> (assoc rc :type :cljs)
(inspect-cljs))
:else
(throw (ex-info "cannot identify as cljs resource" {:resource-name resource-name :url (str url)}))))
(defn should-ignore-resource?
[{:keys [ignore-patterns] :as state} resource-name]
(loop [patterns ignore-patterns]
(if-let [pattern (first patterns)]
(if (re-find pattern resource-name)
true
(recur (rest patterns)))
false
)))
(defn process-deps-cljs [cp ^File source-path resources]
{:pre [(sequential? resources)
(util/file? source-path)]}
(let [index
(->> resources
(map (juxt :resource-name identity))
(into {}))
data-readers
(get index "data_readers.cljc")
index
(dissoc index "data_readers.cljc")
deps-cljs
(get index "deps.cljs")]
(if (nil? deps-cljs)
{:foreign-libs []
:externs []
:resources (vec (vals index))
:data-readers data-readers}
(let [{:keys [externs foreign-libs] :as deps-cljs}
(-> (slurp (:url deps-cljs))
(edn/read-string))
_ (when-not (s/valid? ::config/deps-cljs deps-cljs)
(throw (ex-info "invalid deps.cljs"
(assoc (s/explain-data ::config/deps-cljs deps-cljs)
:tag ::deps-cljs
:deps deps-cljs
:source-path source-path))))
get-index-rc
(fn [index resource-name]
(or (get index resource-name)
(throw (ex-info (format "%s deps.cljs refers to file not in jar: %s" source-path resource-name)
{:tag ::deps-cljs :source-path source-path :name resource-name}))))
foreign-rcs
(->> foreign-libs
(map-indexed
(fn [idx {:keys [externs provides requires file file-min global-exports] :as foreign-lib}]
(when-not (seq provides)
(throw (ex-info "deps.cljs foreign-lib without provides"
{:tag ::deps-cljs :source-path source-path})))
(let [file-rc
(when file
(get-index-rc index file))
file-min-rc
(when file-min
(get-index-rc index file-min))
extern-rcs
(into [] (map #(get-index-rc index %)) externs)
;; requires and provides are strings :(
deps
(into [] (map symbol) requires)
provides
(set (map symbol provides))
extern-rcs
(->> externs
(map #(get-index-rc index %))
(into []))
resource-name
(or file file-min)
]
(-> {:resource-id [::foreign (.getAbsolutePath source-path) idx]
:resource-name resource-name
:type :foreign
:output-name (util/flat-js-name resource-name)
;; :file, :file-min and :externs can all invalidate the foreign lib
:cache-key (-> [(:cache-key file-rc)
(:cache-key file-min-rc)]
(into (map :cache-key extern-rcs)))
;; FIXME: this is bad, it must choose one but loses the other in the process
:last-modified (or (:last-modified file-rc)
(:last-modified file-min-rc))
:requires (set deps)
:provides provides
:deps deps
:externs extern-rcs}
(cond->
global-exports
(assoc :global-exports global-exports)
file-rc
(assoc :url (:url file-rc))
file-min-rc
(assoc :url-min (:url file-min-rc))))
)))
(into []))
index
(dissoc index "deps.cljs")
things-to-drop
(reduce
(fn [x {::keys [externs file file-min]}]
(-> (into x externs)
(cond->
file
(conj file)
file-min
(conj file-min))))
(into #{"deps.cljs"} externs)
foreign-libs)
extern-rcs
(into [] (map #(get-index-rc index %)) externs)
index
(reduce dissoc index things-to-drop)]
{:resources (vec (vals index))
:foreign-libs foreign-rcs
:data-readers data-readers
:externs extern-rcs}
))))
(defn pom-info-for-jar [^File file]
(when (.isFile file)
(let [pom-file (io/file
(.getParentFile file)
(str/replace (.getName file) ".jar" ".pom"))]
(when (.exists pom-file)
(try
(let [doc
(-> (DocumentBuilderFactory/newInstance)
(.newDocumentBuilder)
(.parse pom-file))
el
(.getDocumentElement doc)
child-nodes
(.getChildNodes el)
{:keys [artifact-id group-id version] :as pom-info}
(loop [x 0
info {}]
(if (>= x (.getLength child-nodes))
info
(let [^Element node (.item child-nodes x)]
(recur
(inc x)
(case (.getNodeName node)
"artifactId"
(assoc info :artifact-id (symbol (.getTextContent node)))
"groupId"
(assoc info :group-id (symbol (.getTextContent node)))
;; POM inheritance ... no idea how that works
;; but core.cache and others don't have their own groupId
;; guessing they inherit from the parent
"parent"
(let [pgid
(-> node
(.getElementsByTagName "groupId")
(.item 0)
(.getTextContent)
(symbol))]
(-> info
(assoc :parent-group-id pgid)
(cond->
(not (contains? info :group-id))
(assoc :group-id pgid))))
"version"
(assoc info :version (.getTextContent node))
"name"
(assoc info :name (.getTextContent node))
"url"
(assoc info :url (.getTextContent node))
"description"
(assoc info :description (str/trim (.getTextContent node)))
info
)))))
id
(if (= artifact-id group-id)
artifact-id
(symbol (str group-id) (str artifact-id)))]
(assoc pom-info
:id id
:coordinate [id version]))
(catch Exception e
(log/debug-ex e ::pom-error {:pom pom-file})
nil))))))
(comment
(doseq [x (get-classpath)]
(prn (pom-info-for-jar x))))
(defn get-jar-info* [jar-path]
(let [file (io/file jar-path)]
(when-not (and (.exists file) (.isFile file))
(throw (ex-info "expected to find jar file but didn't" {:jar-path jar-path})))
(let [pom-info (pom-info-for-jar file)
checksum (data/sha1-file file)]
{:checksum checksum
:pom-info pom-info
:last-modified (.lastModified file)})))
(def get-jar-info (memoize get-jar-info*))
;; jar:file:/C:/Users/thheller/.m2/repository/org/clojure/clojurescript/1.10.773/clojurescript-1.10.773.jar!/cljs/core.cljs
(defn get-jar-info-for-url [^URL rc-url]
(let [path (.getFile rc-url)]
(when-not (str/starts-with? path "file:")
(throw (ex-info "expected to file: in jar url but didn't" {:rc-url rc-url})))
(let [idx (str/index-of path "!/")]
(when-not idx
(throw (ex-info "expected to find !/ in jar url but didn't" {:rc-url rc-url})))
(let [jar-path (URLDecoder/decode (subs path 5 idx) "utf-8")]
(get-jar-info jar-path)))))
(defn make-jar-resource [^URL rc-url name]
(let [{:keys [checksum last-modified pom-info]}
(get-jar-info-for-url rc-url)]
(-> {:resource-id [::resource name]
:resource-name name
:cache-key [checksum]
:last-modified last-modified
:url rc-url
:from-jar true}
(cond->
pom-info
(assoc :pom-info pom-info)))))
(defn find-jar-resources* [cp ^File file checksum]
(try
(let [jar-path
(.getCanonicalPath file)
jar-file
(JarFile. file)
last-modified
(.lastModified file)
pom-info
(pom-info-for-jar file)
entries
(.entries jar-file)]
(loop [result (transient [])]
(if (not (.hasMoreElements entries))
(persistent! result)
;; next entry
(let [^JarEntry jar-entry (.nextElement entries)
name (.getName jar-entry)]
(if (or (not (util/is-js-file? name))
(should-ignore-resource? cp name))
(recur result)
(let [url (URL. (str "jar:file:" jar-path "!/" name))]
(-> result
(conj! (-> {:resource-id [::resource name]
:resource-name (rc/normalize-name name)
:cache-key [checksum]
:last-modified last-modified
:url url
:from-jar true}
(cond->
pom-info
(assoc :pom-info pom-info))))
(recur)
)))))))
(catch ZipException e
(log/debug-ex e ::bad-jar {:file file})
[])
(catch Exception e
(throw (ex-info (str "failed to generate jar manifest for file: " file) {:file file} e)))
))
(defn set-output-name
"sets the :output-name for each given resource
demo/foo.cljs becomes demo.foo.js
JS inputs are named to match their name generated by closure to avoid conclicts
demo/foo.js becomes module$demo$foo.js"
;; FIXME: makes .js files annoying to use directly in npm-module
[{:keys [type ns resource-name] :as rc}]
(assoc rc
:output-name
(case type
:goog
(util/flat-filename resource-name)
:cljs
(util/flat-js-name resource-name)
:js
(str ns ".js")
)))
(defmethod log/log-msg ::resource-inspect [_ {:keys [loc]}]
(format "failed to inspect resource \"%s\", it will not be available." loc))
(defn inspect-resources [cp {:keys [resources] :as contents}]
(assoc contents :resources
(->> resources
(map (fn [src]
(try
(inspect-resource cp src)
(catch Exception e
;; don't warn with stacktrace
(log/warn ::resource-inspect
{:loc (or (:file src)
(:url src)
(:resource-name src))})
;; debug log should contain stacktrace
(log/debug-ex e
::inspect-ex
{:log (or (:file src)
(:url src)
(:resource-name src))})
nil))))
(remove nil?)
(map set-output-name)
(into [])
)))
(defn process-root-contents [cp source-path root-contents]
{:pre [(sequential? root-contents)
(util/file? source-path)]}
(->> (process-deps-cljs cp source-path root-contents)
(inspect-resources cp)))
;; if a jar contains a cljs.core file (compiled or source) filter out all other files
;; from that directory as it is compiled output that shouldn't be in the jar in the first place
;; cljs-bean contains an actual legit
;; cljs-bean.from.cljs.core
;; ns that needs to be accounted for and not quarantined
;; will be filtered at a later stage if the ns does not match the filename
(defn quarantine-bad-jar-contents [^File jar-file banned-name resources]
(let [bad
(->> resources
(filter (fn [{:keys [resource-name] :as rc}]
(str/ends-with? resource-name banned-name))))]
(if-not (seq bad)
resources
;; .jar file contains a compiled version of cljs.core
;; filter out all sources in that directory, likely contains many other compiled
;; and uncompiled sources
(reduce
(fn [resources {:keys [resource-name] :as bad-rc}]
(let [bad-prefix
(subs resource-name 0 (str/index-of resource-name banned-name))
filtered
(->> resources
(remove (fn [{:keys [resource-name] :as rc}]
(str/starts-with? resource-name bad-prefix)))
(vec))]
(log/warn ::bad-jar-contents
{:jar-file (.getAbsolutePath jar-file)
:bad-prefix bad-prefix
:bad-count (- (count resources) (count filtered))})
filtered))
resources
bad))))
(defn find-jar-resources
[{:keys [manifest-cache-dir] :as cp} ^File jar-file]
(let [checksum
(data/sha1-file jar-file)
manifest-name
(str (.getName jar-file) "." checksum ".manifest")
mfile
(io/file manifest-cache-dir manifest-name)]
(or (when (and (.exists mfile)
(>= (.lastModified mfile) (.lastModified jar-file))
(>= (.lastModified mfile) CACHE-TIMESTAMP))
(try
(let [cache (cache/read-cache mfile)]
;; user downloads version 2.0.0 runs it
;; upgrades to latest version release a day ago
;; last-modified of cache is higher that release data
;; so the initial check succeeds because >= is true
;; comparing them to be equal ensures that new version
;; will invalidate the cache
(when (= CACHE-TIMESTAMP (::CACHE-TIMESTAMP cache))
cache))
(catch Throwable e
(log/info-ex e ::jar-cache-read-ex {:file mfile})
nil)))
(let [jar-contents
(->> (find-jar-resources* cp jar-file checksum)
(quarantine-bad-jar-contents jar-file "/cljs/core.js")
(quarantine-bad-jar-contents jar-file "/goog/base.js")
(process-root-contents cp jar-file))]
(io/make-parents mfile)
(try
(cache/write-file mfile (assoc jar-contents ::CACHE-TIMESTAMP CACHE-TIMESTAMP))
(catch Throwable e
(log/info-ex e ::jar-cache-write-ex {:file mfile})))
jar-contents))))
(comment
(tap>
(let [svc (start (io/file "tmp" "jar-manifests"))]
(find-jar-resources
svc
(io/file
(System/getProperty "user.home")
".m2"
"repository"
"viz-cljc"
"viz-cljc"
"0.1.3"
"viz-cljc-0.1.3.jar"
)))))
(defn is-gitlib-file? [^File file]
(loop [file (.getAbsoluteFile file)]
(cond
(nil? file)
false
(and (.exists file) (.isDirectory file) (= ".gitlibs" (.getName file)))
true
:else
(recur (.getParentFile file)))))
(def ^Path project-root-path
(-> (io/file ".")
(.getCanonicalFile)
(.toPath)))
;; can fail to relativize when on different disks, see https://github.com/thheller/shadow-cljs/issues/966
;; the only purpose for this path currently is the build report in a relative manner so it doesn't show
;; machine specific details
;; eg. ../shadow-experiments/src/main
;; instead of C:/Users/thheller/code/shadow-experiments/src/main
;; if that fails we show the entire path regardless with a special case for gitlibs
(defn project-rel-path [^File dir]
(if-not (is-gitlib-file? dir)
(try
(-> (.relativize project-root-path
(-> dir (.getAbsoluteFile) (.toPath)))
(str)
(rc/normalize-name))
(catch Exception e
(.getAbsolutePath dir)))
;; gitlib files
(let [^File gitlib-root
(loop [curr dir]
(if (= ".gitlibs" (.getName curr))
(io/file curr "libs")
(recur (.getParentFile curr))))
dir-abs
(.getAbsolutePath dir)
root-abs
(.getAbsolutePath gitlib-root)]
;; C:\Users\thheller\.gitlibs\libs\re-frame\re-frame\8cf68c30722a4c6f8f948a134c900d7a656ecad4\src
;; gitlibs://re-frame/re-frame/8cf68c30722a4c6f8f948a134c900d7a656ecad4/src
(str "gitlibs:/" (rc/normalize-name (subs dir-abs (count root-abs)))))))
(defn make-fs-resource
([^File file name]
(let [fs-root
(loop [root file
i (count (str/split name #"/"))]
(if (zero? i)
(project-rel-path root)
(recur (.getParentFile root) (dec i))))]
(make-fs-resource file name fs-root)))
([^File file name fs-root]
(let [last-mod
(if (.exists file)
(.lastModified file)
(System/currentTimeMillis))
checksum
(data/sha1-file file)]
(-> {:resource-id [::resource name]
:resource-name name
:cache-key [checksum]
:last-modified last-mod
:file file
:fs-root fs-root
:url (.toURL file)}
(cond->
(is-gitlib-file? file)
(assoc :from-jar true))))))
(comment
(make-fs-resource
(io/file "src" "main" "shadow" "build.clj")
"shadow/build.cljs"))
(comment
(is-gitlib-file? (io/file "src" "main" "shadow" "build.clj"))
(is-gitlib-file? (io/file (System/getProperty "user.home") ".gitlibs" "libs")))
(defn find-fs-resources*
[cp ^File root]
(let [root-path (.getCanonicalPath root)
rel-path (project-rel-path root)
root-len (inc (count root-path))
is-gitlib-root? (is-gitlib-file? root)]
(into []
(for [^File file (file-seq root)
:when (and (.isFile file)
(not (.isHidden file))
(util/is-js-file? (.getName file)))
:let [file (.getAbsoluteFile file)
abs-path (.getAbsolutePath file)
_ (assert (str/starts-with? abs-path root-path))
name (-> abs-path
(.substring root-len)
(rc/normalize-name))]
:when (not (should-ignore-resource? cp name))]
(-> (make-fs-resource file name rel-path)
;; treat gitlibs as if they were from a .jar
;; affects hot-reload and warnings logic
(cond->
is-gitlib-root?
(assoc :from-jar true)))
))))
(defn find-fs-resources [cp ^File root]
(->> (find-fs-resources* cp root)
(process-root-contents cp root)))
(defn find-resources [cp ^File file]
(cond
(not (.exists file))
{}
(.isDirectory file)
(find-fs-resources cp file)
(and (.isFile file) (util/is-jar? (.getName file)))
(find-jar-resources cp file)
;; silently ignore all other cases since we can't do anything with them anyways
;; don't throw since java doesn't throw either
:else
{}))
(defn should-exclude-classpath [exclude ^File file]
(let [abs-path (.getAbsolutePath file)]
(boolean (some #(re-find % abs-path) exclude))))
(defn get-classpath-entries [{:keys [index-ref] :as cp}]
(let [{:keys [classpath-excludes]} @index-ref]
(->> (get-classpath)
;; apparently linux distros put jars on the classpath that don't exist?
;; https://github.com/shadow-cljs/shadow-cljs.github.io/pull/19
(filter #(.exists ^File %))
(remove #(should-exclude-classpath classpath-excludes %))
(map #(.getCanonicalFile ^File %))
(distinct)
(into []))))
(defn index-rc-remove [index resource-name]
{:pre [(string? resource-name)]}
(let [{:keys [provides file] :as current} (get-in index [:sources resource-name])]
(if-not current
index
(-> index
(util/reduce->
(fn [state provide]
(update-in state [:provide->source] dissoc provide))
provides)
(update :sources dissoc resource-name)
(cond->
file
(update :file->name dissoc file))))))
(defn is-same-resource? [a b]
(and (= (:resource-id a) (:resource-id b))
(= (:resource-name a) (:resource-name b))
(= (:url a) (:url b))))
(defn index-rc-add [state {:keys [resource-name file provides] :as rc}]
(-> state
(assoc-in [:sources resource-name] rc)
(util/reduce->
(fn [state provide]
(assoc-in state [:provide->source provide] resource-name))
provides)
(cond->
file
(assoc-in [:file->name file] resource-name))))
(defmethod log/log-msg ::duplicate-resource [_ {:keys [resource-name url-a url-b]}]
(format "duplicate resource %s on classpath, using %s over %s" resource-name url-a url-b))
(defmethod log/log-msg ::filename-violation [_ {:keys [ns expected actual]}]
(format "filename violation for ns %s, got: %s expected: %s (or .cljc)" ns actual expected))
(defmethod log/log-msg ::provide-conflict [_ {:keys [provides resource-name conflicts]}]
(format "provide conflict for %s provided by %s and %s" provides resource-name conflicts))
(defn index-rc-merge-js
[index {:keys [type ns resource-name provides url file] :as rc}]
(cond
;; do not merge files that are already present from a different source path
;; same rules as other sources
(when-let [existing (get-in index [:sources resource-name])]
(not (is-same-resource? rc existing)))
(let [conflict (get-in index [:sources resource-name])]
(when-not (and (:from-jar rc)
(not (:from-jar conflict)))
;; only warn when jar conflicts with jar, fs is allowed to override files in jars
(log/info ::duplicate-resource {:resource-name resource-name
:url-a (:url conflict)
:url-b (:url rc)}))
index)
:no-conflict
(index-rc-add index rc)))
(defn index-rc-merge
[index {:keys [type ns resource-name provides url] :as rc}]
(cond
;; sanity check for development
(not (rc/valid-resource? rc))
(throw (ex-info "invalid resource" {}))
(= :js type)
(index-rc-merge-js index rc)
;; ignore process/env.cljs shim, we have our own
(and (= :cljs type)
(= 'process.env ns)
(= "process/env.cljs" resource-name))
index
;; some cljs libs contain a :none compiled version of cljs.core in a jar
;; only cljs/core.cljs is allowed to provide cljs.core
(and (contains? (:provides rc) 'cljs.core)
(not= resource-name "cljs/core.cljs"))
index
;; do not merge files that don't have the expected path for their ns
;; ONLY enforce this for files in jars, since they sometimes contain
;; invalid files which should never be used.
;; for actual files the resource should be available but display a proper warning
;; so it can be fixed. not including the file displays confusing errors otherwise.
(and (= :cljs (:type rc))
(:from-jar rc)
(symbol? (:ns rc))
(let [expected-cljs (util/ns->cljs-filename (:ns rc))
expected-cljc (str/replace expected-cljs #".cljs$" ".cljc")]
(not (or (= resource-name expected-cljs)
(= resource-name expected-cljc)
))))
(do (log/info ::filename-violation {:ns (:ns rc)
:actual resource-name
:expected (util/ns->cljs-filename (:ns rc))})
;; still want to remember the resource so it doesn't get detected as new all the time
;; remove all provides, otherwise it might end up being used despite the invalid name
;; enforce this behavior since the warning might get overlooked easily
(let [invalid-src (assoc rc
:provides #{}
:requires #{}
:deps [])]
(index-rc-add index invalid-src)))
;; do not merge files that are already present from a different source path
(when-let [existing (get-in index [:sources resource-name])]
(not (is-same-resource? rc existing)))
(let [conflict (get-in index [:sources resource-name])]
(when-not (and (:from-jar rc)
(not (:from-jar conflict)))
;; only warn when jar conflicts with jar, fs is allowed to override files in jars
(log/info ::duplicate-resource {:resource-name resource-name
:url-a (:url conflict)
:url-b (:url rc)}))
index)
;; now we need to handle conflicts for cljc/cljs files
;; only use cljs if both exist
:valid-resource
(let [cljc?
(util/is-cljc? resource-name)
cljc-name
(when (util/is-cljs? resource-name)
(str/replace resource-name #"cljs$" "cljc"))
cljs-name
(when cljc?
(str/replace resource-name #"cljc$" "cljs"))
lookup-xf
(comp (map #(get-in index [:provide->source %]))
(remove nil?))
existing-provides
(into #{} lookup-xf provides)
expected-name
(util/ns->cljs-filename (:ns rc))
expected-filename?
(and (= :cljs (:type rc))
(symbol? (:ns rc))