sema-dotenv 0.1.0

Parse .env files and load environment variables

Source

package.sema

116 lines 9df0d02198e1
File details

Source stored with sema-dotenv 0.1.0. Line links refer to these exact bytes.

SHA-256 9df0d02198e1c315b4b221e434de8364be8dee252f9b9cb625e49693b716ead7

1;; sema-dotenv — parse .env files and load them into the process environment
2
3(module sema-dotenv
4  (export dotenv/parse
5          dotenv/read
6          dotenv/load
7          dotenv/load-if-exists
8          dotenv/get
9          dotenv/require)
10
11  ;; -------------------------------------------------------------------------
12  ;; Private helpers
13  ;; -------------------------------------------------------------------------
14
15  ;; The UTF-8 byte-order mark as a one-character string.
16  (define bom (char->string (integer->char 65279)))
17
18  ;; Strip a leading UTF-8 BOM so it doesn't glue onto the first key.
19  (define (strip-bom s)
20    (if (string/starts-with? s bom)
21      (substring s 1 (string-length s))
22      s))
23
24  ;; Strip an inline " #..." comment from an unquoted value, then trim.
25  ;; A # with no whitespace before it is part of the value (KEY=abc#def).
26  (define (strip-inline-comment s)
27    (let ((idx (string/index-of s " #")))
28      (if (nil? idx)
29        s
30        (string/trim (substring s 0 idx)))))
31
32  ;; Parse the raw text after "=" into a value string.
33  ;; - "quoted" / 'quoted': contents kept verbatim (no escape processing,
34  ;;   # inside quotes is literal); anything after the closing quote —
35  ;;   typically a trailing comment — is ignored.
36  ;; - unquoted: trimmed, inline " #" comments stripped. A # separated from
37  ;;   the = by whitespace starts a comment (KEY= # note → ""), but a #
38  ;;   directly after = is the value (COLOR=#ff0000).
39  (define (parse-value raw)
40    (let ((v (string/trim raw)))
41      (cond
42        ((= v "") "")
43        ((or (string/starts-with? v "\"") (string/starts-with? v "'"))
44         (let* ((quote-ch (substring v 0 1))
45                (body (substring v 1 (string-length v)))
46                (close (string/index-of body quote-ch)))
47           (if (nil? close)
48             (strip-inline-comment v)   ; unterminated quote: treat as literal
49             (substring body 0 close))))
50        ((and (string/starts-with? v "#")
51              (not (string/starts-with? raw "#")))
52         "")
53        (#t (strip-inline-comment v)))))
54
55  ;; Parse one line into (key value), or nil for blanks, comments, and
56  ;; lines without "=" or with an empty key.
57  (define (parse-line line)
58    (let ((trimmed (string/trim line)))
59      (if (or (= trimmed "")
60              (string/starts-with? trimmed "#"))
61        nil
62        (let* ((effective (if (string/starts-with? trimmed "export ")
63                            (string/trim (substring trimmed 7 (string-length trimmed)))
64                            trimmed))
65               (eq-pos (string/index-of effective "=")))
66          (if (or (nil? eq-pos) (= eq-pos 0))
67            nil
68            (list (string/trim (substring effective 0 eq-pos))
69                  (parse-value (substring effective (+ eq-pos 1) (string-length effective)))))))))
70
71  ;; -------------------------------------------------------------------------
72  ;; Public API
73  ;; -------------------------------------------------------------------------
74
75  (define (dotenv/parse content)
76    "Parse .env file contents into a {\"KEY\" \"value\"} map. Handles comments, export prefixes, quoted values, inline comments, and CRLF line endings; strips a leading UTF-8 BOM; malformed lines are skipped. When a key repeats, the last line wins."
77    (map/from-entries
78      (filter (fn (entry) (not (nil? entry)))
79              (map parse-line (string/lines (strip-bom content))))))
80
81  (define (dotenv/read path)
82    "Read and parse a .env file from disk into a map. Errors if the file does not exist."
83    (dotenv/parse (file/read path)))
84
85  (define (dotenv/load path . opts)
86    "Read a .env file and set its variables in the process environment. Already-set env vars are NOT overridden unless {:override #t} is passed. Returns the full parsed map."
87    (let* ((o (if (null? opts) {} (first opts)))
88           (override (get o :override #f))
89           (vars (dotenv/read path)))
90      (for-each (fn (entry)
91                  (let ((k (first entry))
92                        (v (nth entry 1)))
93                    (when (or override (nil? (env k)))
94                      (sys/set-env k v))))
95                (map/entries vars))
96      vars))
97
98  (define (dotenv/load-if-exists path . opts)
99    "Like dotenv/load, but returns {} instead of erroring when the file does not exist. Accepts the same {:override #t} option."
100    (if (file/exists? path)
101      (apply dotenv/load (cons path opts))
102      (hash-map)))
103
104  (define (dotenv/get key . default)
105    "Get an environment variable, falling back to default (nil when omitted)."
106    (let ((val (env key)))
107      (if (nil? val)
108        (if (null? default) nil (first default))
109        val)))
110
111  (define (dotenv/require . required-keys)
112    "Assert that every listed environment variable is set — errors naming the missing ones."
113    (let ((missing (filter (fn (k) (nil? (env k))) required-keys)))
114      (when (not (null? missing))
115        (error (format "dotenv/require: missing required environment variables: ~a — set them or add them to your .env"
116                       (string/join missing ", ")))))))