aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/world/environment.lux
blob: 53c05aa3cb19f31dcd9405f07f69dca5a2dce133 (plain)
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
(.`` (.`` (.require
           [library
            [lux (.except)
             [abstract
              ["[0]" monad (.only Monad do)]]
             [control
              ["[0]" function]
              ["[0]" io (.only IO)]
              ["[0]" maybe (.use "[1]#[0]" functor)]
              ["[0]" try (.only Try)]
              ["[0]" exception (.only Exception)]
              [concurrency
               ["[0]" atom]
               ["[0]" async (.only Async)]]]
             [data
              ["[0]" bit (.use "[1]#[0]" equivalence)]
              ["[0]" text (.only)
               ["%" \\format (.only format)]]
              [collection
               ["[0]" array (.only Array)]
               ["[0]" dictionary (.only Dictionary)]
               ["[0]" list (.use "[1]#[0]" functor)]]]
             ["[0]" ffi (.only import)
              (.,, (.for "JavaScript" (.,, (.these ["[0]" node_js]))
                         "{old}" (.,, (.these ["node_js" //math]))
                         (.,, (.these))))]
             [math
              [number
               ["i" int]]]
             [meta
              ["[0]" macro (.only)
               ["[0]" template]]
              [compiler
               ["@" target]]]]]
           ["[0]" \\parser]
           [//
            [file (.only Path)]
            [shell (.only Exit)]])))

(exception.def .public (unknown_environment_variable name)
  (Exception Text)
  (exception.report
   (list ["Name" (%.text name)])))

(type .public (Environment !)
  (Interface
   (is (-> Any (! (List Text)))
       available_variables)
   (is (-> Text (! (Try Text)))
       variable)
   (is Path
       home)
   (is Path
       directory)
   (is (-> Exit (! Nothing))
       exit)))

(def .public (environment monad environment)
  (All (_ !) (-> (Monad !) (Environment !) (! \\parser.Environment)))
  (do [! monad]
    [variables (of environment available_variables [])
     entries (monad.each ! (function (_ name)
                             (of ! each (|>> [name]) (of environment variable name)))
                         variables)]
    (in (|> entries
            (list.all (function (_ [name value])
                        (when value
                          {try.#Success value}
                          {.#Some [name value]}
                          
                          {try.#Failure _}
                          {.#None})))
            (dictionary.of_list text.hash)))))

(`` (def .public (async environment)
      (-> (Environment IO) (Environment Async))
      (implementation
       (,, (with_template [<method>]
             [(def <method>
                (of environment <method>))]

             [home]
             [directory]
             ))

       (,, (with_template [<method>]
             [(def <method>
                (|>> (of environment <method>) async.future))]

             [available_variables]
             [variable]
             [exit]
             )))))

(def .public (mock environment home directory)
  (-> \\parser.Environment Path Path (Environment IO))
  (let [@dead? (atom.atom false)]
    (implementation
     (def available_variables
       (function.constant (io.io (dictionary.keys environment))))
     (def (variable name)
       (io.io (when (dictionary.value name environment)
                {.#Some value}
                {try.#Success value}

                {.#None}
                (exception.except ..unknown_environment_variable [name]))))
     (def home
       home)
     (def directory
       directory)
     (def exit
       (|>> %.int panic! io.io)))))

... Do not trust the values of environment variables
... https://wiki.sei.cmu.edu/confluence/display/java/ENV02-J.+Do+not+trust+the+values+of+environment+variables

(with_expansions [<jvm> (these (import java/lang/String
                                 "[1]::[0]")

                               (import (java/util/Iterator a)
                                 "[1]::[0]"
                                 (hasNext [] boolean)
                                 (next [] a))

                               (import (java/util/Set a)
                                 "[1]::[0]"
                                 (iterator [] (java/util/Iterator a)))

                               (import (java/util/Map k v)
                                 "[1]::[0]"
                                 (keySet [] (java/util/Set k)))

                               (import java/lang/System
                                 "[1]::[0]"
                                 ("static" getenv [] (java/util/Map java/lang/String java/lang/String))
                                 ("static" getenv "as" resolveEnv [java/lang/String] "io" "?" java/lang/String)
                                 ("static" getProperty [java/lang/String] "?" java/lang/String)
                                 ("static" exit [int] "io" void))

                               (def (jvm::consume iterator)
                                 (All (_ a) (-> (java/util/Iterator a) (List a)))
                                 (if (ffi.of_boolean (java/util/Iterator::hasNext iterator))
                                   {.#Item (java/util/Iterator::next iterator)
                                           (jvm::consume iterator)}
                                   {.#End}))
                               )]
  (for @.old (these <jvm>)
       @.jvm (these <jvm>)
       @.js (these (def default_exit!
                     (-> Exit (IO Nothing))
                     (|>> %.int panic! io.io))

                   (import NodeJs_Process
                     "[1]::[0]"
                     (exit [ffi.Number] "io" Nothing)
                     (cwd [] "io" Path))

                   (def (exit_node_js! code)
                     (-> Exit (IO Nothing))
                     (when (ffi.global ..NodeJs_Process [process])
                       {.#Some process}
                       (NodeJs_Process::exit (i.frac code) process)
                       
                       {.#None}
                       (..default_exit! code)))

                   (import Browser_Window
                     "[1]::[0]"
                     (close [] Nothing))

                   (import Browser_Location
                     "[1]::[0]"
                     (reload [] Nothing))

                   (def (exit_browser! code)
                     (-> Exit (IO Nothing))
                     (when [(ffi.global ..Browser_Window [window])
                            (ffi.global ..Browser_Location [location])]
                       [{.#Some window} {.#Some location}]
                       (exec
                         (Browser_Window::close window)
                         (Browser_Location::reload location)
                         (..default_exit! code))

                       [{.#Some window} {.#None}]
                       (exec
                         (Browser_Window::close window)
                         (..default_exit! code))

                       [{.#None} {.#Some location}]
                       (exec
                         (Browser_Location::reload location)
                         (..default_exit! code))
                       
                       [{.#None} {.#None}]
                       (..default_exit! code)))

                   (import Object
                     "[1]::[0]"
                     ("static" entries [Object] (Array (Array ffi.String))))

                   (import NodeJs_OS
                     "[1]::[0]"
                     (homedir [] "io" Path)))
       @.python (these (import os
                         "[1]::[0]"
                         ("static" getcwd [] "io" ffi.String)
                         ("static" _exit [ffi.Integer] "io" Nothing))

                       (import os/path
                         "[1]::[0]"
                         ("static" expanduser [ffi.String] "io" ffi.String))

                       (import os/environ
                         "[1]::[0]"
                         ("static" keys [] "io" (Array ffi.String))
                         ("static" get [ffi.String] "io" "?" ffi.String)))
       @.lua (these (ffi.import LuaFile
                      "[1]::[0]"
                      (read [ffi.String] "io" "?" ffi.String)
                      (close [] "io" ffi.Boolean))

                    (ffi.import (io/popen [ffi.String] "io" "try" "?" LuaFile))
                    (ffi.import (os/getenv [ffi.String] "io" "?" ffi.String))
                    (ffi.import (os/exit [ffi.Integer] "io" Nothing))

                    (def (run_command default command)
                      (-> Text Text (IO Text))
                      (do [! io.monad]
                        [outcome (io/popen [command])]
                        (when outcome
                          {try.#Success outcome}
                          (when outcome
                            {.#Some file}
                            (do !
                              [?output (LuaFile::read "*l" file)
                               _ (LuaFile::close file)]
                              (in (maybe.else default ?output)))
                            
                            {.#None}
                            (in default))
                          
                          {try.#Failure _}
                          (in default)))))
       @.ruby (these (ffi.import Env
                       "[1]::[0]"
                       ("static" keys [] (Array Text))
                       ("static" fetch [Text] "io" "?" Text))

                     (ffi.import "fileutils" FileUtils
                       "[1]::[0]"
                       ("static" pwd Path))
                     
                     (ffi.import Dir
                       "[1]::[0]"
                       ("static" home Path))

                     (ffi.import Kernel
                       "[1]::[0]"
                       ("static" exit [Int] "io" Nothing)))

       ... @.php
       ... (these (ffi.import (exit [Int] "io" Nothing))
       ...        ... https://www.php.net/manual/en/function.exit.php
       ...        (ffi.import (getcwd [] "io" ffi.String))
       ...        ... https://www.php.net/manual/en/function.getcwd.php
       ...        (ffi.import (getenv "as" getenv/1 [ffi.String] "io" ffi.String))
       ...        (ffi.import (getenv "as" getenv/0 [] "io" (Array ffi.String)))
       ...        ... https://www.php.net/manual/en/function.getenv.php
       ...        ... https://www.php.net/manual/en/function.array-keys.php
       ...        (ffi.import (array_keys [(Array ffi.String)] (Array ffi.String)))
       ...        )

       ... @.scheme
       ... (these (ffi.import (exit [Int] "io" Nothing))
       ...        ... https://srfi.schemers.org/srfi-98/srfi-98.html
       ...        (nominal.def Pair Any)
       ...        (nominal.def PList Any)
       ...        (ffi.import (get-environment-variables [] "io" PList))
       ...        (ffi.import (car [Pair] Text))
       ...        (ffi.import (cdr [Pair] Text))
       ...        (ffi.import (car "as" head [PList] Pair))
       ...        (ffi.import (cdr "as" tail [PList] PList)))
       
       (these)))

(def .public default
  (Environment IO)
  (implementation
   (def (available_variables _)
     (with_expansions [<jvm> (|> (java/lang/System::getenv)
                                 java/util/Map::keySet
                                 java/util/Set::iterator
                                 ..jvm::consume
                                 (list#each (|>> ffi.of_string))
                                 io.io)]
       (for @.old <jvm>
            @.jvm <jvm>
            @.js (io.io (if ffi.on_node_js?
                          (when (ffi.global Object [process env])
                            {.#Some process/env}
                            (|> (Object::entries [process/env])
                                (array.list {.#None})
                                (list#each (|>> (array.item 0) maybe.trusted)))

                            {.#None}
                            (list))
                          (list)))
            @.python (of io.monad each (array.list {.#None}) (os/environ::keys []))
            ... Lua offers no way to get all the environment variables available.
            @.lua (io.io (list))
            @.ruby (io.io (array.list {.#None} (Env::keys [])))
            ... @.php (do io.monad
            ...         [environment (..getenv/0 [])]
            ...         (in (|> environment
            ...                   ..array_keys
            ...                   (array.list {.#None})
            ...                   (list#each (function (_ variable)
            ...                               [variable ("php array read" (as Nat variable) environment)]))
            ...                   (dictionary.of_list text.hash))))
            ... @.scheme (do io.monad
            ...            [input (..get-environment-variables [])]
            ...            (loop (again [input input
            ...                          output \\parser.empty])
            ...              (if ("scheme object nil?" input)
            ...                (in output)
            ...                (let [entry (..head input)]
            ...                  (again (..tail input)
            ...                         (dictionary.has (..car entry) (..cdr entry) output))))))
            )))

   (def (variable name)
     (template.let [(!fetch <method> <post>)
                    [(do io.monad
                       [value (|> name <method>)]
                       (in (when value
                             {.#Some value}
                             {try.#Success (<post> value)}

                             {.#None}
                             (exception.except ..unknown_environment_variable [name]))))]]
       (with_expansions [<jvm> (!fetch (<| java/lang/System::resolveEnv ffi.as_string) ffi.of_string)]
         (for @.old <jvm>
              @.jvm <jvm>
              @.js (io.io (if ffi.on_node_js?
                            (when (do maybe.monad
                                    [process/env (ffi.global Object [process env])]
                                    (array.item (as Nat name)
                                                (as (Array Text) process/env)))
                              {.#Some value}
                              {try.#Success value}

                              {.#None}
                              (exception.except ..unknown_environment_variable [name]))
                            (exception.except ..unknown_environment_variable [name])))
              @.python (!fetch os/environ::get |>)
              @.lua (!fetch os/getenv |>)
              @.ruby (!fetch Env::fetch |>)
              ))))
   
   (def home
     (io.run!
      (with_expansions [<default> (io.io "~")
                        <jvm> (|> (java/lang/System::getProperty (ffi.as_string "user.home"))
                                  (maybe#each (|>> ffi.of_string))
                                  (maybe.else "")
                                  io.io)]
        (for @.old <jvm>
             @.jvm <jvm>
             @.js (if ffi.on_node_js?
                    (|> (node_js.require "os")
                        maybe.trusted
                        (as NodeJs_OS)
                        NodeJs_OS::homedir)
                    <default>)
             @.python (os/path::expanduser "~")
             @.lua (..run_command "~" "echo ~")
             @.ruby (Dir::home)
             ... @.php (do io.monad
             ...         [output (..getenv/1 ["HOME"])]
             ...         (in (if (bit#= false (as Bit output))
             ...                 "~"
             ...                 output)))
             
             ... TODO: Replace dummy implementation.
             <default>))))

   (def directory
     (io.run!
      (with_expansions [<default> "."
                        <jvm> (|> (java/lang/System::getProperty (ffi.as_string "user.dir"))
                                  (maybe#each (|>> ffi.of_string))
                                  (maybe.else "")
                                  io.io)]
        (for @.old <jvm>
             @.jvm <jvm>
             @.js (if ffi.on_node_js?
                    (when (ffi.global ..NodeJs_Process [process])
                      {.#Some process}
                      (NodeJs_Process::cwd process)
                      
                      {.#None}
                      (io.io <default>))
                    (io.io <default>))
             @.python (os::getcwd [])
             @.lua (do io.monad
                     [.let [default <default>]
                      on_windows (..run_command default "cd")]
                     (if (same? default on_windows)
                       (..run_command default "pwd")
                       (in on_windows)))
             @.ruby (FileUtils::pwd)
             ... @.php (do io.monad
             ...         [output (..getcwd [])]
             ...         (in (if (bit#= false (as Bit output))
             ...                 "."
             ...                 output)))
             
             ... TODO: Replace dummy implementation.
             (io.io <default>)))))
   
   (def (exit code)
     (with_expansions [<jvm> (do io.monad
                               [_ (java/lang/System::exit (ffi.as_int code))]
                               (in (undefined)))]
       (for @.old <jvm>
            @.jvm <jvm>
            @.js (cond ffi.on_node_js?
                       (..exit_node_js! code)

                       ffi.on_browser?
                       (..exit_browser! code)

                       ... else
                       (..default_exit! code))
            @.python (os::_exit code)
            @.lua (os/exit code)
            @.ruby (Kernel::exit code)
            ... @.php (..exit [code])
            ... @.scheme (..exit [code])
            )))))