-
-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathmain.cljc
2581 lines (2336 loc) · 116 KB
/
main.cljc
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 figwheel.main
#?(:clj
(:require
[cljs.analyzer :as ana]
[cljs.analyzer.api :as ana-api]
[cljs.build.api :as bapi]
[cljs.compiler]
[cljs.closure]
[cljs.cli :as cli]
[cljs.env]
[cljs.main :as cm]
[cljs.repl]
[cljs.repl.figwheel]
[cljs.util]
[clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.pprint :refer [pprint]]
[clojure.string :as string]
[clojure.edn :as edn]
[clojure.java.shell :as sh]
[clojure.tools.reader.edn :as redn]
[clojure.tools.reader.reader-types :as rtypes]
[clojure.walk :as walk]
[figwheel.core :as fw-core]
[figwheel.main.ansi-party :as ansip]
[figwheel.main.logging :as log]
[figwheel.main.util :as fw-util]
[figwheel.main.watching :as fww]
[figwheel.main.helper :as helper]
[figwheel.main.npm :as npm]
[figwheel.main.async-result :as async-result]
[figwheel.main.react-native :as react-native]
[figwheel.main.testing :as testing]
[figwheel.repl :as fw-repl]
[figwheel.main.compat.ana-api :as ana-compat]
[figwheel.tools.exceptions :as fig-ex]
[certifiable.main :as certifiable]
[certifiable.log]))
#?(:clj
(:import
[java.io StringReader]
java.net.InetAddress
java.net.URI
java.net.URLEncoder
java.nio.file.Paths))
#?(:cljs
(:require-macros [figwheel.main])))
#?(:clj
(do
(def ^:dynamic *base-config*)
(def ^:dynamic *config*)
(def default-target-dir "target")
(defonce process-unique (subs (str (java.util.UUID/randomUUID)) 0 6))
(defn- time-elapsed [started-at]
(let [elapsed-us (- (System/currentTimeMillis) started-at)]
(with-precision 2
(str (/ (double elapsed-us) 1000) " seconds"))))
(defn- extract-bundle-cmd-cli [opts]
(get-in opts [:bundle-cmd (or (#{:none} (:optimizations opts :none)) :default)]))
(defn bundle-once? [config]
(if (not (contains? config :bundle-freq))
(get config :bundle-once true)
(= :once (get config :bundle-freq :once))))
(defn bundle-always? [config]
(if (not (contains? config :bundle-freq))
(not (get config :bundle-once true))
(= :always (get config :bundle-freq :once))))
(defn bundle-smart? [config]
(= :smart (get config :bundle-freq :once)))
(defn bundle-once-opts [config opts]
(if (bundle-once? config)
(dissoc opts :bundle-cmd)
opts))
(def NPM-DEPS-FILE "npm_deps.js")
(defn bundle-smart-opts [opts & [scope]]
(if (and (bundle-smart? (::config *config*))
(let [{:keys [output-to output-dir]} opts
output-to? (fw-util/file-has-changed? output-to scope)
npm-deps? (fw-util/file-has-changed? (io/file output-dir NPM-DEPS-FILE) scope)]
(and (not output-to?) (not npm-deps?))))
(dissoc opts :bundle-cmd)
opts))
;; filling in a bundle-cmd template at the last moment
(let [npx-cmd (fw-util/npx-executable)]
(defn- fill-in-bundle-cmd-template [opts final-output-to]
(let [final-output-to-file (io/file final-output-to)
file-path (try (.getParent final-output-to-file) (catch Throwable t nil))
file-name (try (.getName final-output-to-file) (catch Throwable t nil))
fill-in (cond-> {:output-to (str (fw-util/dot-slash (:output-to opts)))
:final-output-to (str (fw-util/dot-slash final-output-to))
:none :none
:default :default
:npx-cmd npx-cmd}
file-path (assoc :final-output-dir (str (fw-util/dot-slash file-path)))
file-name (assoc :final-output-filename file-name))]
(if (:bundle-cmd opts)
(update opts :bundle-cmd
#(walk/postwalk
(fn [x]
(if (keyword? x)
(if-let [replace (fill-in x)]
replace
(throw (ex-info (format "No %s available to fill :bundle-cmd template" x)
{})))
x))
%))
opts))))
;; taken and modified from cljs.closure/run-bundle-cmd
(defn run-bundle-cmd* [opts]
(when-let [cmd (extract-bundle-cmd-cli opts)]
(let [{:keys [exit out err]}
(try
(log/info (str "Bundling: " (string/join " " cmd)))
(apply sh/sh cmd)
(catch Throwable t
(throw
(ex-info (str "Bundling command failed: " (.getMessage t))
{::error true :cmd cmd} t))))]
(when-not (== 0 exit)
(throw
(ex-info (cond-> (str "Bundling command failed")
(not (string/blank? out)) (str "\n" out)
(not (string/blank? err)) (str "\n" err))
{::error true :cmd cmd :exit-code exit :stdout out :stderr err}))))))
(defn run-bundle-cmd
([opts] (run-bundle-cmd opts (:final-output-to (::config *config*))))
([opts final-output-to]
(let [opts (fill-in-bundle-cmd-template opts final-output-to)]
(run-bundle-cmd* opts))))
(defn- wrap-with-bundling [build-fn]
(fn [id build-inputs opts & args]
(let [bundling? (and (= :bundle (:target opts))
(:bundle-cmd opts))]
(when bundling?
(fw-util/file-has-changed? (:output-to opts) id)
(fw-util/file-has-changed? (io/file (:output-dir opts) NPM-DEPS-FILE) id))
(apply build-fn id build-inputs (dissoc opts :bundle-cmd) args)
(when bundling?
(run-bundle-cmd (bundle-smart-opts opts id))))))
(defn- wrap-with-build-logging [build-fn]
(fn [id? build-inputs opts & args]
(let [started-at (System/currentTimeMillis)
{:keys [output-to output-dir]} opts]
;; print start message
(log/info (str "Compiling build"
(when id? (str " " id?))
" to \""
(or output-to output-dir)
"\""))
(try
(let [warnings (volatile! [])
out *out*
warning-fn (fn [warning-type env extra]
(when (get cljs.analyzer/*cljs-warnings* warning-type)
(let [warn {:warning-type warning-type
:env env
:extra extra
:path ana/*cljs-file*}]
(binding [*out* out]
(if (<= (count @warnings) 2)
(log/cljs-syntax-warning warn)
(binding [log/*syntax-error-style* :concise]
(log/cljs-syntax-warning warn))))
(vswap! warnings conj warn))))]
(binding [cljs.analyzer/*cljs-warning-handlers*
(conj (remove #{cljs.analyzer/default-warning-handler}
cljs.analyzer/*cljs-warning-handlers*)
warning-fn)]
(apply build-fn build-inputs opts args)))
(log/succeed (str "Successfully compiled build"
(when id? (str " " id?))
" to \""
(or output-to output-dir)
"\" in " (time-elapsed started-at) "."))
(catch Throwable e
(log/failure (str
"Failed to compile build" (when id? (str " " id?))
" in " (time-elapsed started-at) "."))
(log/syntax-exception e)
(throw e))))))
(declare resolve-fn-var)
(defn run-hooks [hooks & args]
(when (not-empty hooks)
(doseq [h hooks]
(apply h args))))
(defn- wrap-with-build-hooks [build-fn]
(fn [& args]
(run-hooks (::pre-build-hooks *config*) *config*)
(apply build-fn args)
(run-hooks (::post-build-hooks *config*) *config*)))
(defn wrap-with-compiler-passes [build-fn]
(fn [& args]
(if (::passes *config*)
(binding [ana/*passes* (into ana-compat/default-passes (::passes *config*))
fw-util/*compile-collector* (atom {})]
(apply build-fn args))
(apply build-fn args))))
(def build-cljs
(-> bapi/build
wrap-with-build-logging
wrap-with-bundling
wrap-with-build-hooks
wrap-with-compiler-passes))
(def fig-core-build
(-> figwheel.core/build
wrap-with-build-logging
wrap-with-bundling
wrap-with-build-hooks
wrap-with-compiler-passes))
;; TODO the word config is soo abused in this namespace that it's hard to
;; know what and argument is supposed to be
(defn config->reload-config [config]
(select-keys config [:reload-clj-files :wait-time-ms :hawk-options :bundle-once :bundle-freq]))
(defn watch-build [id paths inputs opts cenv & [reload-config]]
(when-let [inputs (not-empty (if (coll? inputs) inputs [inputs]))]
(let [build-inputs (if (coll? inputs) (apply bapi/inputs inputs) inputs)
;; watch is always called after in initial build
opts (bundle-once-opts reload-config opts)
;; the build-fn needs to be passed in before here?
build-fn (if (some #{'figwheel.core} (:preloads opts))
#(fig-core-build id build-inputs opts cenv %)
(fn [files] (build-cljs id build-inputs opts cenv)))]
(log/info "Watching paths:" (pr-str paths) "to compile build -" id)
(log/debug "Build Inputs:" (pr-str inputs))
(binding [fww/*hawk-options* (:hawk-options reload-config nil)]
(fww/add-watch!
[::autobuild id]
(merge
{::watch-info (merge
(:extra-info reload-config)
{:id id
:paths paths
:inputs inputs
:options opts
:compiler-env cenv
:reload-config reload-config})}
{:paths paths
:filter (fww/suffix-filter #{"cljc" "cljs" "js" "clj"})
:handler (fww/throttle
(:wait-time-ms reload-config 50)
(bound-fn [evts]
(binding [cljs.env/*compiler* cenv]
(let [files (mapv (comp #(.getCanonicalPath %) :file) evts)]
(try
(when-let [clj-files
(->> evts
(filter
(partial
(fww/suffix-filter
(set
(cond
(coll? (:reload-clj-files reload-config))
(mapv name (:reload-clj-files reload-config))
(false? (:reload-clj-files reload-config)) []
:else ["clj" "cljc"]))) nil))
(mapv (comp #(.getCanonicalPath %) :file))
not-empty)]
(log/debug "Reloading clj files: " (pr-str (map str clj-files)))
(try
(figwheel.core/reload-clj-files clj-files)
(catch Throwable t
(if (-> t ex-data :figwheel.core/internal)
(do
(log/error (.getMessage t) t)
(log/debug (with-out-str (clojure.pprint/pprint (Throwable->map t)))))
(do
(log/syntax-exception t)
(figwheel.core/notify-on-exception cenv t {})))
;; skip cljs reloading in this case
(throw t))))
(log/debug "Detected changed cljs files: " (pr-str (map str files)))
(build-fn files)
(catch Throwable t
(log/error t)
(log/debug (with-out-str (clojure.pprint/pprint (Throwable->map t))))
false))))))}))))))
(declare read-edn-file)
(defn get-edn-file-key
([edn-file key] (get-edn-file-key edn-file key nil))
([edn-file key default]
(try (get (read-string (slurp edn-file)) key default)
(catch Throwable t default))))
(def validate-config!*
(when (try
(require 'clojure.spec.alpha)
(require 'expound.alpha)
(require 'expound.ansi)
(require 'figwheel.main.schema.config)
(require 'figwheel.main.schema.cljs-options)
(require 'figwheel.main.schema.cli)
true
(catch Throwable t false))
(resolve 'figwheel.main.schema.core/validate-config!)))
(defn validate-config! [spec edn fail-msg & [succ-msg]]
(when (and validate-config!*
(not
(false?
(:validate-config
edn
(get-edn-file-key "figwheel-main.edn" :validate-config)))))
(binding [expound.ansi/*enable-color* (:ansi-color-output edn true)]
(validate-config!* spec edn fail-msg))
(when succ-msg
(log/succeed succ-msg))))
(def validate-cli!*
(when validate-config!*
(resolve 'figwheel.main.schema.cli/validate-cli!)))
(defn validate-cli! [cli-args & [succ-msg]]
(when (and validate-cli!*
(get-edn-file-key "figwheel-main.edn" :validate-cli true))
(binding [expound.ansi/*enable-color*
(get-edn-file-key "figwheel-main.edn" :ansi-color-output true)]
(validate-cli!* cli-args "Error in command line args"))
(when succ-msg
(log/succeed succ-msg))))
;; ----------------------------------------------------------------------------
;; Additional cli options
;; ----------------------------------------------------------------------------
;; Help
(def help-template
"Usage: clojure -m figwheel.main [init-opt*] [main-opt] [arg*]
Common usage:
clj -m figwheel.main -b dev -r
Which is equivalient to:
clj -m figwheel.main -co dev.cljs.edn -c example.core -r
In the above example, dev.cljs.edn is a file in the current directory
that holds a build configuration which is a Map of ClojureScript
compile options. In the above command example.core is ClojureScript
namespace on your classpath that you want to compile.
A minimal dev.cljs.edn will look similar to:
{:main example.core}
The above command will start a watch process that will compile your
source files when one of them changes, it will also facilitate
communication between this watch process and your JavaScript
environment (normally a browser window) so that it can hot reload
changed code into the environment. After the initial compile, it
will then launch a browser to host your compiled ClojureScript code,
and finally a CLJS REPL will launch.
Configuration:
In the above example, besides looking for a dev.cljs.edn file,
figwheel.main will also look for a figwheel-main.edn file in the
current directory as well.
A list of all the config options can be found here:
https://github.com/bhauman/figwheel-main/blob/master/doc/figwheel-main-options.md
A list of ClojureScript compile options can be found here:
https://clojurescript.org/reference/compiler-options
You can add build specific figwheel.main configuration in the
*.cljs.edn file by adding metadata to the build config file like
so:
^{:watch-dirs [\"dev\" \"cljs-src\"]}
{:main example.core}
Command Line Options:
With no options or args, figwheel.main runs a ClojureScript REPL
%s
For --main and --repl:
- Enters the cljs.user namespace
- Binds *command-line-args* to a seq of strings containing command line
args that appear after any main option
- Runs all init options in order
- Calls a -main function or runs a repl or script if requested
The init options may be repeated and mixed freely, but must appear before
any main option.
In the case of --compile and --build you may supply --repl or --serve
options afterwards.
Paths may be absolute or relative in the filesystem or relative to
classpath. Classpath-relative paths have prefix of @ or @/")
(defn adjust-option-docs [commands]
(-> commands
(update-in [:groups :cljs.cli/main&compile :pseudos]
dissoc ["-re" "--repl-env"])
(assoc-in [:init ["-d" "--output-dir"] :doc]
"Set the output directory to use")
(update-in [:init ["-w" "--watch"] :doc] str
". This option can be supplied multiple times.")))
(defn help-str [repl-env]
(format
help-template
(#'cljs.cli/options-str
(adjust-option-docs
(#'cljs.cli/merged-commands repl-env)))))
(defn help-opt
[repl-env _ _]
(println (help-str repl-env)))
;; safer option reading from files which prints out syntax errors
(defn read-edn-file [f]
(try (redn/read
(rtypes/source-logging-push-back-reader (io/reader f) 1 f))
(catch Throwable t
(log/syntax-exception t)
(throw
(ex-info (str "Couldn't read the file:" f)
{::error true} t)))))
(defn read-edn-string [s & [fail-msg]]
(try
(redn/read
(rtypes/source-logging-push-back-reader (io/reader (.getBytes s)) 1))
(catch Throwable t
(let [except-data (fig-ex/add-excerpt (fig-ex/parse-exception t) s)]
(log/info (ansip/format-str (log/format-ex except-data)))
(throw (ex-info (str (or fail-msg "Failed to read EDN string: ")
(.getMessage t))
{::error true}
t))))))
(defn read-edn-opts [str]
(letfn [(read-rsrc [rsrc-str orig-str]
(if-let [rsrc (io/resource rsrc-str)]
(read-edn-string (slurp rsrc))
(cljs.cli/missing-resource orig-str)))]
(cond
(string/starts-with? str "@/") (read-rsrc (subs str 2) str)
(string/starts-with? str "@") (read-rsrc (subs str 1) str)
:else
(let [f (io/file str)]
(if (.isFile f)
(read-edn-file f)
(cljs.cli/missing-file str))))))
(defn merge-meta [m m1] (with-meta (merge m m1) (merge (meta m) (meta m1))))
(defn load-edn-opts [str]
(reduce merge-meta {} (map read-edn-opts (cljs.util/split-paths str))))
(defn fallback-id [edn]
(let [m (meta edn)]
(cond
(and (:id m) (not (string/blank? (str (:id m)))))
(:id m)
;;(:main edn) (munge (str (:main edn)))
:else
(str "build-"
(.getValue (doto (java.util.zip.CRC32.)
(.update (.getBytes (pr-str (into (sorted-map) edn))))))))))
(defn compile-opts-opt
[cfg copts]
(let [copts (string/trim copts)
edn (if (or (string/starts-with? copts "{")
(string/starts-with? copts "^"))
(read-edn-string copts "Error reading EDN from command line flag: -co ")
(load-edn-opts copts))
config (meta edn)
id
(and edn
(if (or (string/starts-with? copts "{")
(string/starts-with? copts "^"))
(and (map? edn) (fallback-id edn))
(->>
(cljs.util/split-paths copts)
(filter (complement string/blank?))
(filter #(not (.startsWith % "@")))
(map io/file)
(map (comp first #(string/split % #"\.") #(.getName %)))
(string/join ""))))]
(log/debug "Validating options passed to --compile-opts")
(validate-config!
:figwheel.main.schema.cljs-options/cljs-options
edn
(str "Configuration error in options passed to --compile-opts"))
(cond-> cfg
edn (update :options merge edn)
id (update-in [::build :id] #(if-not % id %))
config (update-in [::build :config] merge config))))
(defn repl-env-opts-opt
[cfg ropts]
(let [ropts (string/trim ropts)
edn (if (string/starts-with? ropts "{")
(read-edn-string ropts "Error reading EDN from command line flag: --repl-opts ")
(load-edn-opts ropts))]
(update cfg :repl-env-options merge edn)))
(defn figwheel-opts-opt
[cfg ropts]
(let [ropts (string/trim ropts)
edn (if (string/starts-with? ropts "{")
(read-edn-string ropts "Error reading EDN from command line flag: -fw-opts ")
(load-edn-opts ropts))]
(validate-config!
:figwheel.main.schema.config/edn
edn "Error validating figwheel options EDN provided to -fwo CLI flag")
(update cfg ::config merge edn)))
(defn print-config-opt [cfg opt]
(assoc-in cfg [::config :pprint-config] (not= "false" opt)))
(defn clean-outputs-opt [cfg opt]
(assoc-in cfg [::config :clean-outputs] (not= "false" opt)))
(defn- watch-opt
[cfg path]
(when-not (.exists (io/file path))
(if (or (string/starts-with? path "-")
(string/blank? path))
(throw
(ex-info
(str "Missing watch path")
{:cljs.main/error :invalid-arg}))
(throw
(ex-info
(str "Watch path \"" path "\" does not exist")
{:cljs.main/error :invalid-arg}))))
(update-in cfg [::extra-config :watch-dirs] (fnil conj []) path))
(defn figwheel-opt [cfg bl]
(assoc-in cfg [::config :figwheel-core] (not= bl "false")))
(defn get-build [bn]
(let [fname (if (.contains bn (System/getProperty "path.separator"))
bn
(str bn ".cljs.edn"))
build (->> (cljs.util/split-paths bn)
(map #(str % ".cljs.edn"))
(string/join (System/getProperty "path.separator"))
load-edn-opts)]
(when build
(when-not (false? (:validate-config (meta build)))
(when (meta build)
(log/debug "Validating metadata in build: " fname)
(validate-config!
:figwheel.main.schema.config/edn
(meta build)
(str "Configuration error in build options meta data: " fname)))
(log/debug "Validating CLJS compile options for build:" fname)
(validate-config!
:figwheel.main.schema.cljs-options/cljs-options
build
(str "Configuration error in CLJS compile options: " fname))))
build))
(defn watch-dir-from-ns [main-ns]
(let [source (fw-util/ns->location main-ns)]
(when-let [f (:uri source)]
(when (= "file" (.getScheme (.toURI f)))
(let [res (fw-util/relativized-path-parts (.getPath f))
end-parts (fw-util/path-parts (:relative-path source))]
(when (= end-parts (take-last (count end-parts) res))
(str (apply io/file (drop-last (count end-parts) res)))))))))
(def default-main-repl-index-body
(str
"<p>Welcome to the Figwheel REPL page.</p>"
"<p>This page is served when you launch <code>figwheel.main</code> without any command line arguments.</p>"
"<p>This page is currently hosting your REPL and application evaluation environment. "
"Validate the connection by typing <code>(js/alert \"Hello Figwheel!\")</code> in the REPL.</p>"))
(defn get-build-with-error [bn]
(when-not (.exists (io/file (str bn ".cljs.edn")))
(if (or (string/starts-with? bn "-")
(string/blank? bn))
(throw
(ex-info
(str "Missing build name")
{:cljs.main/error :invalid-arg}))
(throw
(ex-info
(str "Build " (str bn ".cljs.edn") " does not exist")
{:cljs.main/error :invalid-arg}))))
(get-build bn))
(defn build-opt [cfg bn]
(let [bns (string/split bn #":")
id (string/join "" bns)
options (->> bns
(map get-build-with-error)
(reduce merge-meta))]
(-> cfg
(update :options merge options)
(assoc ::build (cond-> {:id id}
(meta options)
(assoc :config (meta options)))))))
(defn build-once-opt [cfg bn]
(let [cfg (build-opt cfg bn)]
(assoc-in cfg [::config ::build-once] true)))
(defn background-build-opt [cfg bn]
(let [{:keys [options ::build]} (build-opt {} bn)]
(update cfg ::background-builds
(fnil conj [])
(assoc build :options options))))
;; TODO move these down to main action section
(declare default-compile)
(defn build-main-opt [repl-env-fn [_ build-name & args] cfg]
;; serve if no other args
(let [args (if-not (#{"-s" "-r" "--repl" "--serve"} (first args))
(cons "-s" args)
args)]
(default-compile repl-env-fn
(merge (build-opt cfg build-name)
{:args args
::build-main-opt true}))))
(defn build-once-main-opt [repl-env-fn [_ build-name & args] cfg]
(default-compile repl-env-fn
(merge (build-once-opt cfg build-name)
{:args args})))
(declare default-output-dir default-output-to)
(defn make-temp-dir []
(let [tempf (java.io.File/createTempFile "figwheel" "repl")]
(.delete tempf)
(.mkdirs tempf)
(.deleteOnExit (io/file tempf))
(fw-util/add-classpath! (.toURL tempf))
tempf))
(defn add-temp-dir [cfg]
(let [temp-dir (make-temp-dir)
config-with-target (assoc-in cfg [::config :target-dir] temp-dir)
output-dir (default-output-dir config-with-target)
output-to (default-output-to config-with-target)]
(-> cfg
(assoc-in [:options :output-dir] output-dir)
(assoc-in [:options :output-to] output-to)
(assoc-in [:options :asset-path]
(str "/cljs-out"
(when-let [id (-> cfg ::build :id)]
(str "/" id)))))))
(defn pwd-likely-project-root-dir? []
(or (some #(.isFile (clojure.java.io/file %))
["project.clj" "deps.edn" "figwheel-main.edn"])
(->> (seq (.listFiles (clojure.java.io/file ".")))
(map #(.getName %))
(some #(.endsWith % ".cljs.edn")))))
(defn should-add-temp-dir? [cfg]
(not (pwd-likely-project-root-dir?)))
(defn helper-ring-app [handler html-body output-to & [force-index?]]
(figwheel.server.ring/default-index-html
handler
(figwheel.server.ring/index-html (cond-> {}
html-body (assoc :body html-body)
output-to (assoc :output-to output-to)))
force-index?))
(defn repl-main-opt [repl-env-fn args cfg]
(let [cfg (if (should-add-temp-dir? cfg)
(add-temp-dir cfg)
cfg)
cfg (if (get-in cfg [::build :id])
cfg
(assoc-in cfg [::build :id] "figwheel-default-repl-build"))
output-to (get-in cfg [:options :output-to]
(default-output-to cfg))]
(default-compile
repl-env-fn
(-> cfg
(assoc :args args)
(update :options (fn [opt] (merge {:main 'figwheel.repl.preload} opt)))
(assoc-in [:options :aot-cache] true)
(assoc-in [::config
:ring-stack-options
:figwheel.server.ring/dev
:figwheel.server.ring/system-app-handler]
#(helper/middleware
%
{:header "REPL Host page"
:body (slurp (io/resource "public/com/bhauman/figwheel/helper/content/repl_welcome.html"))
:output-to output-to}))
(assoc-in [::config :mode] :repl)))))
(declare serve update-config)
(defn print-conf [cfg]
(println "---------------------- Figwheel options ----------------------")
(pprint (::config cfg))
(println "---------------------- Compiler options ----------------------")
(pprint (:options cfg)))
(defn serve-main-opt [repl-env-fn args b-cfg]
(let [{:keys [repl-env-options repl-options options] :as cfg}
(-> b-cfg
(assoc :args args)
update-config)
repl-env-options
(update-in
repl-env-options
[:ring-stack-options
:figwheel.server.ring/dev
:figwheel.server.ring/system-app-handler]
(fn [sah]
(if sah
sah
#(helper/serve-only-middleware % {}))))
{:keys [pprint-config]} (::config cfg)
repl-env (apply repl-env-fn (mapcat identity repl-env-options))]
(log/trace "Verbose config:" (with-out-str (pprint cfg)))
(if pprint-config
(do
(log/info ":pprint-config true - printing config:")
(print-conf cfg))
(serve {:repl-env repl-env
:repl-options repl-options
:join? true}))))
(def figwheel-commands
{:init {["-w" "--watch"]
{:group :cljs.cli/compile :fn watch-opt
:arg "path"
:doc "Continuously build, only effective with the --compile and --build main options"}
["-fwo" "--fw-opts"]
{:group :cljs.cli/compile :fn figwheel-opts-opt
:arg "edn"
:doc (str "Options to configure figwheel.main, can be an EDN string or "
"system-dependent path-separated list of EDN files / classpath resources. Options "
"will be merged left to right.")}
["-ro" "--repl-opts"]
{:group ::main&compile :fn repl-env-opts-opt
:arg "edn"
:doc (str "Options to configure the repl-env, can be an EDN string or "
"system-dependent path-separated list of EDN files / classpath resources. Options "
"will be merged left to right.")}
["-co" "--compile-opts"]
{:group :cljs.cli/main&compile :fn compile-opts-opt
:arg "edn"
:doc (str "Options to configure the build, can be an EDN string or "
"system-dependent path-separated list of EDN files / classpath resources. Options "
"will be merged left to right. Any meta data will be merged with the figwheel-options.")}
;; TODO uncertain about this
["-fw" "--figwheel"]
{:group :cljs.cli/compile :fn figwheel-opt
:arg "bool"
:doc (str "Use Figwheel to auto reload and report compile info. "
"Only takes effect when watching is happening and the "
"optimizations level is :none or nil."
"Defaults to true.")}
["-bb" "--background-build"]
{:group :cljs.cli/compile :fn background-build-opt
:arg "str"
:doc "The name of a build config to watch and build in the background."}
["-pc" "--print-config"]
{:group :cljs.cli/main&compile :fn print-config-opt
:doc "Instead of running the command print out the configuration built up by the command. Useful for debugging."}
["--clean"]
{:group :cljs.cli/main&compile :fn clean-outputs-opt
:doc (str "Delete the compile artifacts for this build before compiling. "
"Deletes :output-dir, :output-to, :final-output-to and any extra-main files."
"This option can be supplied by itself to clean all builds."
"Or you can supply a single build name to clean only that build.")}}
:main {["-b" "--build"]
{:fn build-main-opt
:arg "string"
:doc (str "Run a compile process. The supplied build name or a list of build names "
"(seperated by \":\") refer to "
"EDN files of compile options "
"IE. If you use \"dev\" as a build name it will indicate "
"that a \"dev.cljs.edn\" will be read for "
"compile options. "
"Multiple build names will merged left to right along with their metadata. "
"The --build option will make an "
"extra attempt to "
"initialize a figwheel live reloading workflow. "
"May be followed buy either --repl or --serve. "
"If --repl follows, "
"will launch a REPL (along with a server) after the compile completes. "
"If --serve follows, will only start a web server according to "
"current configuration after the compile "
"completes.")}
["-bo" "--build-once"]
{:fn build-once-main-opt
:arg "string"
:doc (str "Compile for the build name one time. "
"Looks for build EDN files just like the --build command. "
"This will not inject Figwheel or REPL functionality into your build. "
"It will still inject devtools if you are using :optimizations :none. "
"If --serve follows, will start a web server according to "
"current configuration after the compile "
"completes.")}
["-r" "--repl"]
{:fn repl-main-opt
:doc "Run a REPL"}
["-s" "--serve"]
{:fn serve-main-opt
:arg "host:port"
:doc "Run a server based on the figwheel-main configuration options."}
["-h" "--help" "-?"]
{:fn help-opt
:doc "Print this help message and exit"}}})
;; ----------------------------------------------------------------------------
;; Config
;; ----------------------------------------------------------------------------
(defn browser-target? [target]
(or (nil? target)
(= :bundle target)))
(defn default-output-dir* [target & [scope]]
(->> (cond-> [(or target default-target-dir) "public" "cljs-out"]
scope (conj scope))
(apply io/file)
(.getPath)))
(defn config-auto-bundle [{:keys [options ::config] :as cfg}]
;; we only support webpack right now
(if (:auto-bundle config)
(cond-> cfg
true (assoc-in [:options :target] :bundle)
(= :webpack (:auto-bundle config))
(update-in [:options :bundle-cmd]
#(merge
{:none [:npx-cmd "webpack" "--mode=development" "--entry" :output-to
"--output-path" :final-output-dir
"--output-filename" :final-output-filename]
:default [:npx-cmd "webpack" "--mode=production" "--entry" :output-to
"--output-path" :final-output-dir
"--output-filename" :final-output-filename]}
%))
(= :parcel (:auto-bundle config))
(update-in [:options :bundle-cmd]
#(merge
{:none [:npx-cmd "parcel" "build" :output-to
"--out-dir" :final-output-dir
"--out-file" :final-output-filename
"--no-minify"]
:default [:npx-cmd "parcel" "build" :output-to
"--out-dir" :final-output-dir
"--out-file" :final-output-filename]}
%))
(#{:advanced :simple :whitespace} (:optimizations options))
(assoc-in [:options :closure-defines 'cljs.core/*global*] "window"))
cfg))
(defmulti default-output-dir (fn [{:keys [options]}]
(get options :target :browser)))
(defmethod default-output-dir :default [{:keys [::config ::build]}]
(default-output-dir* (:target-dir config) (:id build)))
(defmethod default-output-dir :nodejs [{:keys [::config ::build]}]
(let [target (:target-dir config default-target-dir)
scope (:id build)]
(->> (cond-> [target "node"]
scope (conj scope))
(apply io/file)
(.getPath))))
(defn default-output-to* [target & [scope]]
(.getPath (io/file (or target default-target-dir) "public" "cljs-out"
(cond->> "main.js"
scope (str scope "-")))))
(defn default-bundle-output-to* [target & [scope]]
(->> (cond-> [(or target default-target-dir) "public" "cljs-out"]
scope (conj scope)
true (conj "main.js"))
(apply io/file)
(.getPath)))
(defmulti default-output-to (fn [{:keys [options]}]
(get options :target :browser)))
(defmethod default-output-to :default [{:keys [options ::config ::build]}]
(if-let [out-dir (:output-dir options)]
(.getPath (io/file out-dir "main.js"))
(default-output-to* (:target-dir config) (:id build))))
(defmethod default-output-to :bundle [{:keys [options ::config ::build]}]
(if-let [out-dir (:output-dir options)]
(.getPath (io/file out-dir "main.js"))
(default-bundle-output-to* (:target-dir config) (:id build))))
(defmethod default-output-to :nodejs [{:keys [::build] :as cfg}]
(let [scope (:id build)]
(.getPath (io/file (default-output-dir cfg)
(cond->> "main.js"
scope (str scope "-"))))))
(defn extra-config-merge [a' b']
(merge-with (fn [a b]
(cond
(and (map? a) (map? b)) (merge a b)
(and (sequential? a)
(sequential? b))
(distinct (concat a b))
(nil? b) a
:else b))
a' b'))
(defn resolve-fn-var [prefix handler]
(if (or (nil? handler) (var? handler))
handler
(let [prefix (when prefix (str prefix ": "))]
(when (and handler (nil? (namespace (symbol handler))))
(throw
(ex-info
(format "%sThe var '%s has the wrong form it must be a namespaced symbol" prefix
(pr-str handler))
{::error true :handler handler})))
(let [handler-res (fw-util/require-resolve-handler-or-error handler)]
(when (and handler (not handler-res))
(throw (ex-info
(format "%sWas able to load namespace '%s but unable to resolve the specific var: '%s"
prefix
(namespace (symbol handler))
(str handler))
{::error true
:handler handler})))
(when (map? handler-res)
(letfn [(error [s]
(throw (ex-info s {::error true :handler handler})))]
(condp = (:stage handler-res)
:bad-namespaced-symbol
(do (log/syntax-exception (:exception handler-res))
(error (format "%sThere was an error while trying to resolve '%s"
prefix
(pr-str handler))))
:unable-to-resolve-handler-fn
(error (format "%sWas able to load namespace '%s but unable to resolve the specific var: '%s"
prefix
(namespace (symbol handler))
(str handler)))
:unable-to-load-handler-namespace
(do
(log/syntax-exception (:exception handler-res))
(error (format "%sThere was an exception while requiring the namespace '%s while trying to load the var '%s"
prefix
(namespace (symbol handler))
(str handler)))))))
handler-res))))
(defn resolve-ring-handler [ring-handler]
(resolve-fn-var "ring-handler" ring-handler))
(defn process-main-config [{:keys [ring-handler] :as main-config}]
(let [handler (resolve-ring-handler ring-handler)]
(cond-> main-config
handler (assoc :ring-handler handler))))
(defn process-figwheel-main-edn [main-edn]
(when main-edn
(when-not (false? (:validate-config main-edn))
(log/info "Validating figwheel-main.edn")
(validate-config!
:figwheel.main.schema.config/edn