~subsetpark/bagatto

ref: a2831049b80eb871c4e6d6538c1de54648766965 bagatto/src/loaders.janet -rw-r--r-- 2.0 KiB
a2831049 — Zach Smith Ignore jpm-managed deps 8 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
(import src/error)
(import src/threads)
(import src/env)

(defn- set-cxt! [spec-name]
  (setdyn :error-context {:spec-name spec-name}))

(defn- make-attrs [parser filename &opt file-contents]
  (let [base-attrs @{:path filename :contents file-contents}]
    (if file-contents
      (try (parser file-contents base-attrs)
           ([err fib] (propagate (error/attrs-error err parser) fib)))
      base-attrs)))

(defn from-file-spec-loader
  ```
  A loader that takes either a single file spec or a sequence of file
  specs and sends back a list of attributes.
  ```
  [spec-name loader parser transform-f]
  (fn [parent]
    (set-cxt! spec-name)
    (threads/print "Loading " spec-name "...")

    (let [loader-specs (try (loader)
                            ([err fib] (propagate (error/loader-spec-error spec-name loader) fib)))
          res (match loader-specs
                {:each ind}
                (do
                  (threads/print "[" spec-name "] Loading " (length ind) " files")
                  (-> (seq [spec :in ind]
                        (if (indexed? spec)
                          (make-attrs parser ;spec)
                          (make-attrs parser spec)))
                      (transform-f)))

                {:some spec}
                (make-attrs parser ;spec)

                _ (error/loader-spec-error spec-name loader))]
      (:send parent [:res spec-name res]))))

(defn from-path-loader
  ```
  A loader that takes a literal file path and generates file
  attributes.
  ```
  [spec-name path parser]
  (fn [parent]
    (set-cxt! spec-name)
    (threads/print "Loading " spec-name " (" path ")...")

    (let [file-contents (slurp path)
          res (make-attrs parser path file-contents)]
      (:send parent [:res spec-name res]))))

(defn bare-attr-loader
  ```
  A loader that takes an attributes literal and returns it.
  ```
  [spec-name attrs]
  (set-cxt! spec-name)

  (fn [parent]
    (threads/print "Loaded " spec-name)
    (:send parent [:res spec-name attrs])))