-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.clj
61 lines (49 loc) · 1.34 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
(ns dotty.core
(:require [clojure.string :as s]
[clojure.java.io :as io]))
(defn comment? [val]
(s/starts-with? val "#"))
(defn wrapped-in? [s wrapper]
(and (s/starts-with? s wrapper)
(s/ends-with? s wrapper)))
(defn strip-ends [s]
(subs s 1 (dec (count s))))
(defn strip-single-quotes [s]
(if (wrapped-in? s "'")
(strip-ends s)
s))
(defn decode-var
"Decode a single environment var into hash-map.
Return `nil` if invalid."
[var-str]
(let [[k v] (s/split (s/trim var-str) #"=" 2)]
(when (and (not-any? nil? [k v])
(not-empty k))
{k (strip-single-quotes v)})))
(defn decode-vars
"Decode env vars by line"
[vars-str]
(into {}
(->> (s/split-lines vars-str)
(remove comment?)
(map decode-var)
(remove nil?))))
(defn read-env-file
"Read and parse env file e.g \".env\""
[file-name]
(if (.exists (io/as-file file-name))
(slurp file-name)
(do (println "Dotty: file not found: " file-name)
"")))
(defn system-env []
(into {} (System/getenv)))
(defn load-env []
(merge (system-env)
(decode-vars (read-env-file ".env"))))
(def ^:dynamic env-vars (load-env))
(defn env
"Retrieve env var by name"
([] env-vars)
([var-name] (get env-vars var-name)))
(defn reload-env-vars []
(set! env-vars (load-env)))