~subsetpark/bagatto

ref: 075f758e48bb282b35b0df18a703af68da96e0c1 bagatto/src/env.janet -rw-r--r-- 1.4 KiB
075f758e — Zach Smith Tweak subtitle 9 months ago
                                                                                
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
(import temple)
(import sh)

(def required-checks @{})

(defmacro defrequire
  ```
  Define a function, preceded by the name of an external program. If
  this program is not present when Bagatto is run, this function will
  raise an error.
  ```
  [program name args & body]
  ~((put env/required-checks ,program true)
     (defn ,name
       ,args
       (when (in (dyn :executable-blacklist) ,program)
         (error (string "Required executable not installed: " ,program)))
       ,;body)))

(defn- on-path?
  [prog]
  (let [f (file/open "/dev/null")]
    (case (os/execute ["which" prog] :p {:out f :err f})
      0 true
      false)))

(defn- prepare-syspath! []
  (match (os/getenv "JANET_PATH")
    nil :ok
    janet-path (put root-env :syspath janet-path)))

(defn add-exec-blacklist
  ```
  Iterate through all the executables declared with `defrequire` and
  check for their existence in the path. Add a blacklist of all
  executables that are absent from the path to the given environment.
  ```
  [env]
  (let [blacklist @{}]
    (loop [check :keys required-checks]
      (unless (on-path? check)
        (put blacklist check true)))
    (put env :executable-blacklist blacklist)))

(defn prepare-environment!
  [env]
  (prepare-syspath!)
  (temple/add-loader)
  # Monkey-patch the temple environment with the functions defined
  # in the index module.
  (merge-into temple/base-env env)
  (setdyn :executable-blacklist (env :executable-blacklist)))