/
core.clj
1273 lines (1093 loc) · 41 KB
/
core.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
;; ## "The Kitchen Sink"
;;
;; Pretty much everything in here should _probably_ be organized into
;; proper namespaces, or perhaps even separate libraries
;; altogether. But who has time for that?
(ns puppetlabs.kitchensink.core
(:refer-clojure :exclude [boolean? uuid?])
(:require [clj-time.coerce :as time-coerce]
[clj-time.core :as time]
[clj-time.format :as time-format]
[clojure.java.io :as io]
[clojure.pprint :as pprint]
[clojure.set :as set]
[clojure.string :as string]
[clojure.tools.cli :as cli]
[clojure.tools.logging :as log]
[digest]
[me.raynes.fs :as fs]
[slingshot.slingshot :refer [throw+]])
(:import (java.io File Reader StringWriter)
(java.time ZoneId ZoneOffset ZonedDateTime)
(java.time.format DateTimeFormatter)
javax.naming.ldap.LdapName
(javax.naming.ldap Rdn)
(org.ini4j BasicProfileSection Config Ini)))
(defn error-map
[kind message]
{:kind kind
:msg message})
;; ## Type checking
(defn array?
"Returns true if `x` is an array"
[x]
(some-> x
(class)
(.isArray)))
(defn datetime?
"Predicate returning whether or not the supplied object is
convertible to a Joda DateTime"
[x]
(and
(satisfies? time-coerce/ICoerce x)
(time-coerce/to-date-time x)))
(defn boolean?
"Returns true if the value is a boolean"
[value]
(instance? Boolean value))
(defn regexp?
"Returns true if the type is a regexp pattern"
[regexp]
{:post [(boolean? %)]}
(instance? java.util.regex.Pattern regexp))
(defn zipper?
"Checks to see if the object has zip/make-node metadata on it (confirming it
to be a zipper."
[obj]
(contains? (meta obj) :zip/make-node))
;; ## String utilities
(defn strict-parse-bool
"Parse a string and return its boolean value; throws an exception if the String
does not match `\"true\"` or `\"false\"` (case-insensitive)."
[^String s]
{:pre [(string? s)]
:post [(boolean? %)]}
(condp = (.toLowerCase s)
"true" true
"false" false
(throw+ (error-map ::parse-error
(format "Unable to parse '%s' to a boolean" s)))))
(defn parse-bool
"Parse a string and return its boolean value."
[s]
{:pre [(or (nil? s) (string? s))]
:post [(boolean? %)]}
(Boolean/parseBoolean s))
(defn to-bool
"Converts the argument to a boolean. The behavior is as follows:
* If the argument is a Boolean, it is simply returned.
* If the argument is a String, returns the Boolean `true` if the String
matches `\"true\"` (case insensitive), or `false` if the String matches
`\"false\"` (case insensitive). Throws an exception otherwise.
* If the argument is `nil`, returns false."
[val]
{:pre [((some-fn boolean? string? nil?) val)]
:post [(boolean? %)]}
(cond
(boolean? val) val
(string? val) (strict-parse-bool val)
(nil? val) false))
(defn string-contains?
"Returns true if `s` has the `substring` in it"
[^String substring ^String s]
{:pre [(string? s)
(string? substring)]}
(>= (.indexOf s substring) 0))
(defn true-str?
"Return true if the string contains true"
[^String s]
(.equalsIgnoreCase "true" s))
(defn pprint-to-string [x]
(let [w (StringWriter.)]
(pprint/pprint x w)
(.toString w)))
(defn to-sentence
"Join the given strings as they would be listed in a sentence (using an Oxford
comma if there are three or more strings).
Examples:
[\"apple\"] => \"apple\"
[\"apple\" \"orange\"] => \"apple and orange\"
[\"apple\" \"orange\" \"banana\"] => \"apple, orange, and banana\""
[strings]
(let [num-strings (count strings)]
(cond
(empty? strings)
""
(= num-strings 1)
(first strings)
(= num-strings 2)
(str (first strings) " and " (second strings))
(= num-strings 3)
(let [[s0 s1 s2] strings]
(str s0 ", " s1 ", and " s2))
(> num-strings 3)
(str (first strings) ", " (to-sentence (rest strings))))))
(defn key->str
"Convert a keyword to a string, stripping the leading : character. This is
distinct from the `name` function as it will preserve the 'namespace' portion
before a slash. If the key is already a string, it is returned unmodified."
[kw]
(if (keyword? kw)
(subs (str kw) 1)
kw))
;; ## I/O
(defn lines
"Returns a sequence of lines from the given filename"
[filename]
(with-open [file-reader (io/reader (fs/file filename))]
;; line seq is lazy and file-reader gets closed
(doall (line-seq file-reader))))
(defn mkdirs!
"Given a path (may be a File or a string), creates a directory (including any
missing parent directories). Throws a slingshot exception with a meaningful
error message if the directory cannot be created.
(The reason for the existence of this function is that the Java File.mkdirs
method only returns a boolean indicating whether the directory was created;
if you get back a `false`, you have no idea whether it failed due to permission
errors, or the path being invalid in some way, or the directory already exists.)
The slingshot exception will look like this:
`{:kind :puppetlabs.kitchensink.core/io-error
:msg \"Parent directory '/foo/bar' is not writable\"}`"
[path]
{:pre [((some-fn #(instance? File %) string?) path)]
:post [(fs/directory? path)]}
(let [path-as-file (fs/file path)]
(if (fs/file? path-as-file)
(throw+ (error-map ::io-error
(format "Path '%s' is a file" path)))
(doseq [^File dir (reverse (cons path-as-file (fs/parents path-as-file)))]
(when-not (fs/exists? dir)
(let [parent (.getParentFile dir)]
(when (fs/file? parent)
(throw+ (error-map ::io-error
(format "Parent directory '%s' is a file"
parent))))
(when-not (.canWrite parent)
(throw+ (error-map ::io-error
(format "Parent directory '%s' is not writable"
parent))))
(let [success (.mkdir dir)]
(when-not success
(throw+ (error-map ::io-error
(format "Unable to create directory '%s'"
parent)))))))))))
;; ## Math
(defn quotient
"Performs division on the supplied arguments, substituting `default`
when the divisor is 0"
([dividend divisor]
(quotient dividend divisor 0))
([dividend divisor default]
(if (zero? divisor)
default
(/ dividend divisor))))
;; ## Numerics
(defn parse-int
"Parse a string `s` as an integer, returning nil if the string doesn't
contain an integer."
[s]
{:pre [(string? s)]
:post [(or (integer? %) (nil? %))]}
(try (Integer/parseInt s)
(catch NumberFormatException _e
nil)))
(defn parse-float
"Parse a string `s` as a float, returning nil if the string doesn't
contain a float"
[s]
{:pre [(string? s)]
:post [(or (float? %) (nil? %))]}
(try (Float/parseFloat s)
(catch NumberFormatException _e
nil)))
(defn parse-number
"Converts a string `s` to a number, by attempting to parse it as an integer
and then as a float. Returns nil if the string isn't numeric."
[s]
{:pre [(string? s)]
:post [(or (number? %) (nil? %))]}
((some-fn parse-int parse-float) s))
;; ## Randomness
(defn rand-weighted-selection
"Given alternating numeric weights and values, produces a randomly-selected
value according to the weights, which should sum to one. If the weights sum
to less than one, then the last value will have its weight adjusted upwards
accordingly. If the weights sum to more than one, then values after the
cumulative sum of the weights exceeds one will never be selected."
[& weights-and-values]
{:pre [(even? (count weights-and-values))
(every? number? (take-nth 2 weights-and-values))]}
(let [weights (take-nth 2 weights-and-values)
values (-> (take-nth 2 (drop 1 weights-and-values)) butlast)
cutoffs (-> (reductions + weights) butlast)
selected? (let [selected-cutoff (rand)]
#(>= % selected-cutoff))
selected (filter (comp selected? first)
(map vector cutoffs values))]
(if (empty? selected)
(last weights-and-values)
(-> (first selected) second))))
(def ascii-character-sets
(let [concatv (comp vec concat)
ALPHA (mapv char (range 65 91))
alpha (mapv char (range 97 123))
digits (mapv char (range 48 58))
symbols (concatv (map char (range 33 48))
(map char (range 91 97))
(map char (range 123 127)))]
{:alpha (concatv alpha ALPHA)
:alpha-lower alpha
:alpha-upper ALPHA
:alpha-digits (concatv alpha ALPHA digits)
:alpha-digits-symbols (concatv alpha ALPHA digits symbols)
:symbols symbols
:digits digits}))
(defn rand-str
"Produces a random string of length n, drawn from the given collection of
characters. The following keywords may be used in place of a character
collection:
:alpha - [a-zA-Z]
:alpha-lower - [a-z]
:alpha-upper - [A-Z]
:alpha-digits - [a-zA-Z0-9]
:alpha-digits-symbols - all printable ASCII characters besides space
:symbols - all visible, non-alpha-numeric ASCII characters (no space)
:digits - [0-9]
If no character collection or keyword is provided, :alpha-digits-symbols is
used by default."
([n] (rand-str :alpha-digits-symbols n))
([characters n]
(let [char-coll (cond
(and (keyword? characters) (contains? ascii-character-sets characters))
(get ascii-character-sets characters)
(keyword? characters)
(throw (IllegalArgumentException.
(str characters " is not a recognized character collection keyword")))
:else (vec characters))]
(apply str (repeatedly n #(rand-nth char-coll))))))
;; ## Collection operations
(defn symmetric-difference
"Computes the symmetric set/difference between 2 sets"
[s1 s2]
(set/union (set/difference s1 s2) (set/difference s2 s1)))
(defn as-collection
"Returns the item wrapped in a collection, if it's not one
already. Returns a list by default, or you can use a constructor func
as the second arg."
([item]
(as-collection item list))
([item constructor]
{:post [(coll? %)]}
(if (coll? item)
item
(constructor item))))
(defn seq-contains?
"True if seq contains elm"
[seq elm]
(some #(= elm %) seq))
(defn enumerate
"Returns a lazy sequence consisting of 0 and the first item of coll,
followed by 1 and the second item in coll, etc, until coll is
exhausted."
[coll]
(map-indexed vector coll))
(def excludes?
"Inverse of `contains?`. Returns false if key is present in the given collectoin,
otherwise returns true."
(complement contains?))
(defn contains-some
"If coll `contains?` any of the keys in ks, returns the first such
key. Otherwise returns nil."
[coll ks]
(some #(when (contains? coll %) %) ks))
(defn excludes-some
"If coll `excludes?` any of the keys in ks, returns the first such
key. Otherwise returns nil."
[coll ks]
(some #(when (excludes? coll %) %) ks))
(defn mapvals
"Return map `m`, with each value transformed by function `f`.
You may also provide an optional list of keys `ks`; if provided, only the
specified keys will be modified."
([f m]
(into {} (for [[k v] m] [k (f v)])))
([f ks m]
;; would prefer to share code between the two implementations here, but
;; the `into` is much faster for the base case and the reduce is much
;; faster for any case where we're operating on a subset of the keys.
;; It seems like `select-keys` is fairly expensive.
(reduce (fn [m k] (update-in m [k] f)) m ks)))
(defn mapkeys
"Return map `m`, with each key transformed by function `f`"
[f m]
(into {} (concat (for [[k v] m]
[(f k) v]))))
(defn maptrans
"Return map `m`, with values transformed according to the key-to-function
mappings specified in `keys-fns`. `keys-fns` should be a map whose keys
are lists of keys from `m`, and whose values are functions to apply to those
keys.
Example: `(maptrans {[:a, :b] inc [:c] dec} {:a 1 :b 1 :c 1})` yields `{:a 2, :c 0, :b 2}`"
[keys-fns m]
{:pre [(map? keys-fns)
(every? (fn [[ks fn]] (and (coll? ks) (ifn? fn))) keys-fns)
(map? m)]}
(let [ks (keys keys-fns)]
(reduce (fn [m k] (mapvals (keys-fns k) k m)) m ks)))
(defn dissoc-if-nil
"Given a map and a key, checks to see if the value for the key is `nil`; if so,
returns a modified map with the specified key removed. If the value is not `nil`,
simply returns the original map."
([m k]
{:pre [(map? m)]
:post [(map? %)]}
(if (nil? (m k))
(dissoc m k)
m))
([m k & ks]
(let [ret (dissoc-if-nil m k)]
(if ks
(recur ret (first ks) (next ks))
ret))))
(defn dissoc-in
"Dissociates an entry from a nested map. ks is a sequence of keys. Any empty maps that result
will not be present in the new map."
[m [k & ks]]
(when m
(if-let [res (and ks (dissoc-in (m k) ks))]
(assoc m k res)
(let [res (dissoc m k)]
(when-not (empty? res)
res)))))
(defn walk-leaves
"Walk a map applying a function to all leaf nodes"
[m f]
(mapvals #(if (map? %) (walk-leaves % f) (f %)) m))
(defn merge-with-key
"Returns a map that consists of the rest of the maps conj-ed onto
the first. If a key `k` occurs in more than one map, the mapping(s)
from the latter (left-to-right) will be combined with the mapping in
the result by calling (f k val-in-result val-in-latter)."
{:added "1.0"
:static true}
[f & maps]
(when (some identity maps)
(let [merge-entry (fn [m e]
(let [k (key e) v (val e)]
(if (contains? m k)
(assoc m k (f k (get m k) v))
(assoc m k v))))
merge2 (fn [m1 m2]
(reduce merge-entry (or m1 {}) (seq m2)))]
(reduce merge2 maps))))
(defn deep-merge
"Deeply merges maps so that nested maps are combined rather than replaced.
For example:
(deep-merge {:foo {:bar :baz}} {:foo {:fuzz :buzz}})
;;=> {:foo {:bar :baz, :fuzz :buzz}}
;; contrast with clojure.core/merge
(merge {:foo {:bar :baz}} {:foo {:fuzz :buzz}})
;;=> {:foo {:fuzz :quzz}} ; note how last value for :foo wins"
[& vs]
(if (every? map? vs)
(apply merge-with deep-merge vs)
(last vs)))
(defn deep-merge-with
"Deeply merges like `deep-merge`, but uses `f` to produce a value from the
conflicting values for a key in multiple maps."
[f & vs]
(if (every? map? vs)
(apply merge-with (partial deep-merge-with f) vs)
(apply f vs)))
(defn deep-merge-with-keys*
"Helper function for deep-merge-with-keys"
[f ks & vs]
(if (every? map? vs)
(apply merge-with-key
(fn [k & vs] (apply deep-merge-with-keys* f (conj ks k) vs))
vs)
(apply f ks vs)))
(defn deep-merge-with-keys
"Deeply merges like `deep-merge`, but uses `f` to produce a value from the
conflicting values for a key path `ks` that appears in multiple maps, by calling
`(f ks val-in-result val-in-latter)`."
[f & vs]
(apply deep-merge-with-keys* f [] vs))
(defn keyset
"Returns the set of keys from the supplied map"
[m]
{:pre [(map? m)]
:post [(set? %)]}
(set (keys m)))
(defn valset
"Returns the set of values from the supplied map"
[m]
{:pre [(map? m)]
:post [(set? %)]}
(set (vals m)))
(def select-values
"Returns the sequence of values from the map for the entries with the specified keys"
(comp vals select-keys))
(defn filter-map
"Like 'filter', but works on maps. Returns a map containing the
key-value pairs in 'm' for which 'pred' returns a truth-y value.
'pred' must be a function which takes two arguments."
[pred m]
(reduce
(fn [result [key value]]
(if (pred key value)
(assoc result key value)
result))
{}
m))
(defn missing?
"Inverse of contains? that supports multiple keys. Will return true if all items are
missing from the collection, false otherwise.
Example:
;; Returns true, as :z :f :h are all missing
(missing? {:a 'a' :b 'b' :c 'c'} :z :f :h)
;; Returns false, as :a is in the collection
(missing? {:a 'a' :b 'b' :c 'c'} :z :b)"
[coll & keys]
{:pre [(coll? coll)]
:post [(boolean? %)]}
(reduce (fn [_ key]
(if (contains? coll key)
(reduced false)
true))
nil
keys))
(defn ordered-comparator
"Given a function and an order (:ascending or :descending),
return a comparator function that takes two objects and compares them in
ascending or descending order based on the value of applying the function
to each."
[f order]
{:pre [(ifn? f)
(contains? #{:ascending :descending} order)]
:post [(fn? %)]}
(fn [x y]
(if (= order :ascending)
(compare (f x) (f y))
(compare (f y) (f x)))))
(defn compose-comparators
"Composes two comparator functions into a single comparator function
which will call the first comparator and return the result if it is
non-zero; otherwise it will call the second comparator and return
its result."
[comp-fn1 comp-fn2]
{:pre [(fn? comp-fn1)
(fn? comp-fn2)]
:post [(fn? %)]}
(fn [x y]
(let [val1 (comp-fn1 x y)]
(if (= val1 0)
(comp-fn2 x y)
val1))))
(defn order-by-expr?
"Predicate that returns true if the argument is a valid expression for use
with the `order-by` function; in other words, returns true if the argument
is a 2-item vector whose first element is an `ifn` and whose second element
is either `:ascending` or `:descending`."
[x]
(and
(vector? x)
(ifn? (first x))
(contains? #{:ascending :descending} (second x))))
(defn order-by
"Sorts a collection based on a sequence of 'order by' expressions. Each expression
is a tuple containing a fn followed by either `:ascending` or `:descending`;
returns a collection that is sorted based on the values of the 'order by' fns
being applied to the elements in the original collection. If multiple 'order by'
expressions are passed in, their precedence is determined by their order in
the argument list."
[order-bys coll]
{:pre [(sequential? order-bys)
(every? order-by-expr? order-bys)
(coll? coll)]}
(let [comp-fns (map (fn [[f order]] (ordered-comparator f order)) order-bys)
final-comp (reduce compose-comparators comp-fns)]
(sort final-comp coll)))
(defn sort-nested-maps
"For a data structure, recursively sort any nested maps and sets descending
into map values, lists, vectors and set members as well. The result should be
that all maps in the data structure become explicitly sorted with natural
ordering. This can be used before serialization to ensure predictable
serialization.
The returned data structure is not a transient so it is still able to be
modified, therefore caution should be taken to avoid modification else the
data will lose its sorted status."
[data]
(cond
(map? data)
(into (sorted-map) (for [[k v] data]
[k (sort-nested-maps v)]))
(sequential? data)
(map sort-nested-maps data)
:else data))
;; ## Date and Time
(defn timestamp
"Returns a timestamp string for the given `time`, or the current time if none
is provided. The format of the timestamp is eg. 2012-02-23T22:01:39.539Z."
([]
(timestamp (time/now)))
([time]
(time-format/unparse (time-format/formatters :date-time) time)))
;; ## Exception handling
(defn without-ns
"Given a clojure keyword that is optionally namespaced, returns
a keyword with the same name but with no namespace."
[kw]
{:pre [(keyword? kw)]
:post [(keyword? %)
(nil? (namespace %))]}
(keyword (name kw)))
(defn keep-going*
"Executes the supplied fn repeatedly. Execution may be stopped with an
InterruptedException."
[f on-error]
(when
(try
(f)
true
(catch InterruptedException _e
false)
(catch Throwable e
(on-error e)
true))
(recur f on-error)))
(defmacro keep-going
"Executes body, repeating the execution of body even if an exception
is thrown"
[on-error & body]
`(keep-going* (fn [] ~@body) ~on-error))
(defmacro with-error-delivery
"Executes body, and delivers an exception to the provided promise if one is
thrown."
[error & body]
`(try
~@body
(catch Throwable e#
(deliver ~error e#))))
(defmacro with-timeout [timeout-s default & body]
`(let [f# (future (do ~@body))
result# (deref f# (* 1000 ~timeout-s) ~default)]
(future-cancel f#)
result#))
;; ## File paths
(defn absolute-path
"Replacement for raynes.fs/absolute-path, which was removed in raynes.fs 1.4.6.
Returns string representation of absolute path, as opposed to fs/absolute, which
returns a File object."
[path]
(.getPath ^File (fs/absolute path)))
(defn normalized-path
"Replacement for raynes.fs/normalized-path, which was removed in raynes.fs 1.4.6.
Returns string representation of absolute path, as opposed to fs/normalized, which
returns a File object."
[path]
(.getPath ^File (fs/normalized path)))
;; ## Temp files
(defn temp-file-name
"Returns a unique name to a temporary file, but does not actually create the file."
[file-name-prefix]
(io/file (fs/tmpdir) (fs/temp-name file-name-prefix)))
(defn delete-on-exit
"Will delete `f` on shutdown of the JVM"
[f]
(.deleteOnExit (fs/file f))
f)
(defn temp-file
"Creates a temporary file that will be deleted on JVM shutdown.
Supported arguments are the same as for me.raynes.fs/temp-file:
[prefix]
[prefix suffix]
[prefix suffix tries]
You may also call with no arguments, in which case the prefix string will be
empty."
[& args]
(if (empty? args)
(delete-on-exit (fs/temp-file nil))
(delete-on-exit (apply fs/temp-file args))))
(defn temp-dir
"Creates a temporary directory that will be deleted on JVM shutdown.
Supported arguments are the same as for me.raynes.fs/temp-dir:
[prefix]
[prefix suffix]
[prefix suffix tries]
You may also call with no arguments, in which case the prefix string will be
empty."
[& args]
(if (empty? args)
(delete-on-exit (fs/temp-dir nil))
(delete-on-exit (apply fs/temp-dir args))))
;; ## Configuration files
(def keywordize
"Normalize INI keys by ensuring they're lower-case and keywords"
(comp keyword string/lower-case))
(defn fetch-int
"Fetch a key from the INI section and convert it
to an integer if it parses, otherwise return the string"
[^BasicProfileSection section key]
(let [val (.fetch section key)]
(or (parse-int val)
val)))
(defn create-section-map
"Given an INI section, create a clojure map of it's key/values"
[^BasicProfileSection section]
(reduce (fn [acc [key _]]
(if (> (.length section key) 1)
(throw (IllegalArgumentException.
(str "Duplicate configuration entry: "
(mapv keyword [(.getName section) key]))))
(assoc acc
(keywordize key)
(fetch-int section key))))
{} section))
(defn parse-ini
"Takes a io/reader that contains an ini file, and returns an Ini object
containing the parsed results"
[^Reader ini-reader]
{:pre [(instance? Reader ini-reader)]
:post [(instance? Ini %)]}
(let [config (Config.)
ini (Ini.)]
(.setMultiOption config true)
(.setConfig ini config)
(.load ini ini-reader)
ini))
(defn ini-to-map
"Takes a .ini filename and returns a nested map of
fully-interpolated values. Strings that look like integers are
returned as integers, and all section names and keys are returned as
symbols."
[filename]
{:pre [(or (string? filename)
(instance? java.io.File filename))]
:post [(map? %)
(every? keyword? (keys %))
(every? map? (vals %))]}
(with-open [ini (io/reader filename)]
(reduce (fn [acc [name section]]
(assoc acc
(keywordize name)
(create-section-map section)))
{}
(parse-ini ini))))
(defn inis-to-map
"Takes a path and converts the pointed-at .ini files into a nested
map (see `ini-to-map` for details). If `path` is a file, the
behavior is exactly the same as `ini-to-map`. If `path` is a
directory, we return a merged version of parsing all the .ini files
in the directory (we do not do a recursive find of .ini files)."
([path]
(inis-to-map path "*.ini"))
([path glob-pattern]
{:pre [(or (string? path)
(instance? java.io.File path))]
:post [(map? %)]}
(let [files (if-not (fs/directory? path)
[path]
(fs/glob (fs/file path glob-pattern)))]
(->> files
(map fs/absolute)
(map ini-to-map)
(apply deep-merge-with-keys
(fn [ks & _]
(throw (IllegalArgumentException.
(str "Duplicate configuration entry: " ks)))))
(merge {})))))
(defn spit-ini
"Writes the `ini-map` to the Ini file at `file`. `ini-map` should
a map similar to the ones created by ini-to-map. The keys are keywords
for the sections and their values are maps of config keypairs."
[^File file ini-map]
(let [ini (org.ini4j.Ini. file)]
(doseq [[section-key section] ini-map
[k v] section]
(.put ini (name section-key) (name k) v))
(.store ini)))
(defn add-shutdown-hook!
"Adds a shutdown hook to the JVM runtime.
`f` is a function that takes 0 arguments; the return value is ignored. This
function will be called if the JVM receiveds an interrupt signal (e.g. from
`kill` or CTRL-C); you can use it to log shutdown messages, handle state
cleanup, etc."
[^Runnable f]
{:pre [(fn? f)]}
(.addShutdownHook (Runtime/getRuntime) (Thread. f)))
(defmacro demarcate
"Executes `body`, but logs `msg` to info before and after `body` is
executed. `body` is executed in an implicit do, and the last
expression's return value is returned by `demarcate`.
user> (demarcate \"reticulating splines\" (+ 1 2 3))
\"Starting reticulating splines\"
\"Finished reticulating splines\"
6
"
[msg & body]
`(do (log/info (str "Starting " ~msg))
(let [result# (do ~@body)]
(log/info (str "Finished " ~msg))
result#)))
;; ## Command-line parsing
(defn cli!
"Validates that required command-line arguments are present. If they are not,
throws a map** with an error message that is intended to be displayed to the user.
Also checks to see whether the user has passed the `--help` flag.
Input:
- args : the command line arguments passed in by the user
- specs : an array of supported argument specifications, as accepted by
`clojure.tools.cli`
- required : an array of keywords (using the long form of the argument spec)
specifying which of the `specs` are required. If any of the
`required` options are not present, the function will cause
the program to exit and display the help message.
** The map is thrown using 'slingshot' (https://github.com/scgilardi/slingshot).
It contains a `:kind` and `:msg`, where type is either `:error` or `:help`,
and the message is either the error message or a help banner.
Returns a three-item vector, containing:
* a map of the parsed options
* a vector containing the remaining cli arguments that were not parsed
* a string containing a summary of all of the options that are available; for
use in printing help messages if the user detects that the arguments are
still invalid in some way."
([args specs] (cli! args specs nil))
([args specs required-args]
(let [specs (conj specs ["-h" "--help" "Show help" :default false])
{:keys [options arguments summary errors]} (cli/parse-opts args specs)]
(when errors
(let [msg (str
"\n\n"
"Error(s) occurred while parsing command-line arguments: "
(apply str errors)
"\n\n"
summary)]
(throw+ (error-map ::cli-error msg))))
(when (:help options)
(throw+ (error-map ::cli-help summary)))
(when-let [missing-field (some #(when-not (contains? options %) %) required-args)]
(let [msg (str
"\n\n"
(format "Missing required argument '--%s'!" (name missing-field))
"\n\n"
summary)]
(throw+ (error-map ::cli-error msg))))
[options arguments summary])))
;; ## SSL Certificate handling
;;
;; NOTE: Prefer functions provided by the jvm-certificate-authority library over these.
;;
;; These functions are only used by PuppetDB and they should likely move back into that
;; project until they can be refactored away over functions from the jvm-ca library.
(defn ^:deprecated cn-for-dn
"Deprecated. Use functions from https://github.com/puppetlabs/jvm-ssl-utils instead.
Extracts the CN (common name) from an LDAP DN (distinguished name).
If more than one CN entry exists in the given DN, we return the most-specific
one (the one that comes last, textually). If no CN is present in the DN, we
return nil.
Example:
(cn-for-dn \"CN=foo.bar.com,OU=meh,C=us\")
\"foo.bar.com\"
(cn-for-dn \"CN=foo.bar.com,CN=baz.goo.com,OU=meh,C=us\")
\"baz.goo.com\"
(cn-for-dn \"OU=meh,C=us\")
nil"
[^String dn]
{:pre [(string? dn)]}
(some->> dn
(LdapName.)
(.getRdns)
(filter #(= "CN" (.getType ^Rdn %)))
(first)
(.getValue)
(str)))
(defn ^:deprecated cn-for-cert
"Deprecated. Use functions from https://github.com/puppetlabs/jvm-ssl-utils instead.
Extract the CN from the DN of an x509 certificate. See `cn-for-dn` for details
on how extraction is performed.
If no CN exists in the certificate DN, nil is returned."
[^java.security.cert.X509Certificate cert]
(-> cert
(.getSubjectX500Principal)
(.getName)
(cn-for-dn)))
;; ## Ring helpers
(defn cn-whitelist->authorizer
"Given a 'whitelist' file containing allowed CNs (one per line),
build a function that takes a Ring request and returns true if the
CN contained in the client certificate appears in the whitelist.
`whitelist` can be either a local filename or a File object.
This makes use of the `:ssl-client-cn` request parameter. See
`com.puppetlabs.middleware/wrap-with-certificate-cn`."
[whitelist]
{:pre [(or (string? whitelist)
(instance? java.io.File whitelist))]
:post [(fn? %)]}
(let [allowed? (set (lines whitelist))]
(fn [{:keys [ssl-client-cn scheme]}]
(or (= scheme :http)
(allowed? ssl-client-cn)))))
;; ## Hashing
(defn utf8-string->sha1
"Compute a SHA-1 hash for the UTF-8 encoded version of the supplied
string"
[^String s]
{:pre [(string? s)]
:post [(string? %)]}
(let [bytes (.getBytes s "UTF-8")]
(digest/sha-1 [bytes])))
(defn utf8-string->sha256
"Compute a SHA-256 hash for the UTF-8 encoded version of the supplied
string"
[^String s]
{:pre [(string? s)]
:post [(string? %)]}
(let [bytes (.getBytes s "UTF-8")]
(digest/sha-256 [bytes])))
(defn stream->sha256
"Compute a SHA-256 hash for the given java.io.InputStream object."
[^java.io.InputStream stream]
{:pre [(instance? java.io.InputStream stream)]
:post [(string? %)]}
(digest/sha-256 stream))
(defn file->sha256
"Compute a SHA-256 hash for the given java.io.File object.
Uses an InputStream to read the file, so it doesn't load all the contents into
memory at once."
[^java.io.File file]
{:pre [(instance? java.io.File file)]
:post [(string? %)]}
(digest/sha-256 file))