This repository has been archived by the owner on May 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
util.cljc
302 lines (247 loc) · 8.2 KB
/
util.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
(ns trident.util
"Utility library. Docstrings are omitted for simple functions; read the source
to see what they do."
(:require [clojure.walk :refer [postwalk]]
[clojure.pprint]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[taoensso.encore :as enc]
#?@(:cljs [[goog.string :as gstring]
[goog.string.format]
[cljs.core.async :refer [<! put! chan close!]]]
:clj [[clojure.reflect :refer [reflect]]]))
#?(:cljs (:require-macros trident.util)))
(def pprint clojure.pprint/pprint)
(defn pred-> [x f g]
(if (f x) (g x) x))
(defn derive-config
"Replaces any `^:derived` values in `m`. See [[defconfig]]."
[m]
(postwalk #(if (:derived (meta %)) (% m) %) m))
(defn ^:no-doc text-rows [lines]
(str/join \newline (remove nil? (flatten lines))))
#?(:clj (do
(defmacro capture [& xs]
`(do ~@(for [x xs] `(def ~x ~x))))
(defmacro cljs-import-vars
"Like `potemkin/import-vars` but supports importing cljs-only functions.
Example:
```
(cljs-import-vars my.namespace.core
foo bar baz)
```"
[nspace & syms]
`(do ~@(for [s syms]
`(def ~s ~(symbol (str nspace) (str s))))))
(defmacro forv [& body]
`(vec (for ~@body)))
(defmacro condas->
"Combination of `cond->` and `as->`."
[expr name & clauses]
(assert (even? (count clauses)))
`(as-> ~expr ~name
~@(map (fn [[test step]] `(if ~test ~step ~name))
(partition 2 clauses))))
(defmacro js<!
"Like `<!` but for js promises. See [[to-chan]]."
[form]
`(cljs.core.async/<! (to-chan ~form)))
(defmacro for-every? [& forms]
`(every? boolean (for ~@forms)))
(defmacro for-some? [& forms]
`(some boolean (for ~@forms)))
(defmacro forcat [& forms]
`(apply concat (for ~@forms)))
(defn load-var
"Dynamically loads a var.
`sym`: a fully-qualified var symbol."
[sym]
(require (symbol (namespace sym)))
(let [f (if-let [f (resolve sym)]
f
(throw (ex-info sym " is not on the classpath.")))]
@f))
(defn loadf
"Returns a function that dynamically loads and calls the specified function.
`sym`: a fully-qualified function symbol."
[sym]
(fn [& args]
(apply (load-var sym) args)))
(defmacro load-fns
"Defines a bunch of \"dynamic functions\" (see [[loadf]]).
Example:
```
(load-fns
foo my.lib/foo
bar my.lib/bar
baz your.lib/baz)
(foo) ; same as (do (require 'my.lib) (my.lib/foo))
```"
[& forms]
(assert (even? (count forms)))
`(do ~@(for [[sym fn-sym] (partition 2 forms)]
`(def ~sym (#'loadf (quote ~fn-sym))))))
(s/def ::overrides (s/+ (s/cat :interface symbol? :fns (s/* list?))))
(defn- sigs [interface]
(if (class? interface)
(->> interface
reflect
:members
(filter #(contains? % :parameter-types))
(mapv (juxt :name (comp inc count :parameter-types))))
(for [{-name :name arglists :arglists} (vals (:sigs @interface))
arglist arglists]
[-name (count arglist)])))
(defmacro inherit
"Like `deftype` but with default function implementations.
The first field is the \"parent\": for any protocol functions you don't define,
the function will be called again with the parent as the first argument instead
of the current object.
Example:
```
(defprotocol P
(foo [this])
(bar [this]))
(deftype Parent []
P
(foo [_] \"parent foo\")
(bar [_] \"parent bar\"))
(inherit Child [parent]
P
(foo [_] \"child foo\"))
(def parent (Parent.))
(def child (Child. parent))
(foo child)
=> \"child foo\"
(bar child)
=> \"parent bar\"
```"
[child-name [parent-instance :as fields] & overrides]
(s/assert ::overrides overrides)
`(deftype ~child-name ~fields
~@(forcat [{:keys [interface fns]} (s/conform ::overrides overrides)]
(let [interface' (resolve interface)
override-fns (->> fns
(map (fn [form] [[(first form)
(count (second form))] form]))
(into {}))]
`[~interface
~@(for [[-name argcount :as sig] (sigs interface')]
(or (override-fns sig)
(let [arglist (vec (conj (repeatedly (dec argcount) gensym) '_))
parent-method (if (class? interface')
(symbol (str "." (name -name)))
(symbol (namespace interface) (name -name)))]
`(~-name
~arglist
(~parent-method
~parent-instance
~@(rest arglist))))))]))))
(defmacro defconfig
"Defines `config` and `init-config!` vars.
Example:
```
(defconfig
{:first-name \"John\"
:last-name \"Doe\"
:full-name ^:derived #(str (:first-name %) \" \" (:last-name %))})
config
=> {:first-name \"John\" :last-name \"Doe\" :full-name \"John Doe\"}
(init-config! {:first-name \"Jane\"})
config
=> {:first-name \"Jane\" :last-name \"Doe\" :full-name \"Jane Doe\"}
```
`default` is a map. Any values with a truthy `:derived` metadata value must
be single-argument functions. These functions will be replaced with their return
values, with the config map as the argument.
`init-config!` takes any number of maps and merges them onto the provided config
map using `taoensso.encore/nested-merge`, deriving values afterward."
[default]
`(do
(def ~'config (derive-config ~default))
(defn ~'init-config! [& ms#]
(let [c# (apply enc/nested-merge ~default ms#)
c# (derive-config c#)]
(def ~'config c#)))))
(defmacro text
"Generates a string from pairs of conditions and lines of text.
The right-hand side values will be flattened, so you can give strings,
collections of strings, or nested collections of strings. `nil`s are
removed.
Example:
```
(println (text
true [\"foo\" nil \"bar\"]
false \"baz\"
true \"quux\"))
foo
bar
quux
```"
[& forms]
`(text-rows [~@(for [[condition lines] (partition 2 forms)]
`(when ~condition ~lines))]))
(def ^:no-doc instant-type java.util.Date)
(def ord int)
(defn parse-int [s]
(Long/parseLong s))
) :cljs (do
(defn to-chan
"Converts a js promise to a channel.
If the promise throws an error, logs to the console and closes the channel."
[p]
(let [c (chan)]
(.. p (then #(put! c %))
(catch #(do
(.error js/console %)
(close! c))))
c))
(def ^{:doc "alias for `goog.string.format`"}
format gstring/format)
(def ^:no-doc instant-type (type #inst "0001-01-01"))
(def char->int (into {} (map #(vector (char %) %) (range 256))))
(def ord char->int)
(defn parse-int [s]
(js/parseInt s))
))
(defn instant? [x]
(= (type x) instant-type))
(defn rand-str [len]
(apply str (take len (repeatedly #(char (+ (rand 26) 65))))))
(defn map-kv [f xs]
(into {} (map #(apply f %) xs)))
(defn doclines
"Returns the docstring of a var as a collection of lines, removing indentation."
[_var]
(when-some [_doc (:doc (meta _var))]
(let [lines (str/split _doc #"\n")
indent (->> (rest lines)
(map #(count (re-find #"^ *" %)))
(apply min ##Inf))]
(map-indexed #(cond-> %2 (not (zero? %1)) (subs indent))
lines))))
(defn pad [n _val coll]
(take n (concat coll (repeat _val))))
(defn format-columns
"Formats rows of text into columns.
Example:
```
(doseq [row (format-columns [[\"hellooooooooo \" \"there\"]
[\"foo \" \"bar\"]
[\"one column\"]])]
(println row))
hellooooooooo there
foo bar
one column
```"
[rows]
(let [
n-cols (apply max (map count rows))
rows (map (partial pad n-cols " ") rows)
lens (apply map (fn [& column-parts]
(apply max (map count column-parts)))
rows)
fmt (str/join (map #(str "%" (when (not (zero? %)) (str "-" %)) "s") lens))]
(->> rows
(map #(apply (partial format fmt) %))
(map str/trimr))))