-
Notifications
You must be signed in to change notification settings - Fork 28
/
platform.clj
119 lines (94 loc) · 2.48 KB
/
platform.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
(ns cli-matic.platform
"
## Platform-specific functions for the JVM.
If running on ClojureScript, we can have a different file for JS.
BTW, in this NS, we avoid using Spec / Orchestra.
**DO NOT** define macros in this namespace - see [[cli-matic.platform-macros]]
"
(:require [clojure.edn :as edn]
[cli-matic.optionals :as OPT])
(:import (clojure.lang IPending)))
(defn read-env
"Reads an environment variable.
If undefined, returns nil."
[var]
(System/getenv var))
(defn exit-script
"Terminates execution with a return value."
[retval]
(System/exit retval))
(defn add-shutdown-hook
"Add a shutdown hook. If `nil`, simply ignores it.
The shutdown hook is run in a new thread.
"
[fnToCallOnShutdown]
(when (ifn? fnToCallOnShutdown)
(.addShutdownHook
(Runtime/getRuntime)
(Thread. fnToCallOnShutdown))))
(defn slurp-file
"No slurping in JavaScript. So we have to move this to
platform."
[f]
(slurp f))
;
; Conversions
;
(defn parseInt
"Converts a string to an integer. "
[s]
(Integer/parseInt s))
(defn parseFloat
"Converts a string to a float."
[s]
(Float/parseFloat s))
(def ^:private formatter
(java.time.format.DateTimeFormatter/ofPattern "yyyy-MM-dd"))
(defn asDate
"Converts a string in format yyyy-mm-dd to a
Date object; if conversion
fails, returns nil."
[s]
(try
(java.sql.Date/valueOf
(java.time.LocalDate/parse s formatter))
(catch Throwable _
nil)))
(defn parseEdn
" Decodes EDN through clojure.edn. "
[edn-in]
(edn/read-string edn-in))
(defn- isJvmPromise?
"Checks whether the value is a JVM promise."
[x]
(instance? IPending x))
(defn isDeferredValue?
"Is this a deferred value for this platform?"
[v]
(cond
(isJvmPromise? v) true
(future? v) true
(OPT/is-core-async-channel? v) true
:else false))
(defn waitForDeferredValue
"Given that value is a deferred value for this platform,
block termination until it's realized.
On the JVM, we support:
- promises
- futures
- core.async channels (if they exist)
"
[v]
(cond
(isJvmPromise? v) (deref v)
(future? v) (deref v)
(OPT/is-core-async-channel? v) (OPT/read-value-from-core-async-channel v)
:else (throw (ex-info
(str "Value is not deferred " v)
{}))))
(defn printError
"On ClojureScript, STDERR is not *err* but it's platform dependent.
On JVM, standard approach."
[o]
(binding [*out* *err*]
(println o)))