~subsetpark/bagatto

ref: import-syntax-update bagatto/bagatto.janet -rw-r--r-- 11.0 KiB
34918929 — Zach Smith Add ignore file 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
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
(import sh)
(import temple)
(import markable)
(import path)
(import jdn)
(import json)

(import /src/multimarkdown)

(defn- set-error-context!
  [k v]
  (let [error-context (or (dyn :error-context) @{})
        updated (merge error-context @{k v})]
    (setdyn :error-context updated)))

#
# API
#

(defn set-defaults!
  ```
  Set the defaults for the values specified in data and site
  specifications. For instance, setting the default of `:attrs` to
  `bagatto/parse-json` will attempt to set the attributes for any file
  by parsing it as JSON. `:attrs` could still be set on any entry in
  the data spec in order to override the default.
  ```
  [defaults]
  (setdyn :bagatto-defaults defaults))

(defn get-default
  ```
  Get the value set in the bagatto defaults for the specified key. Can
  be used for a simple form of inheritence; if you have a default
  callback or value set, and you have some specific handler that needs
  to build on top of that functionality, you can call
  `bagatto/get-default` to get or evaluate it inside of the handler
  and then implement your more specific logic.

  (see `bagatto/set-defaults!` for more information.)
  ```
  [attribute]
  (-> (dyn :bagatto-defaults) (in attribute)))

(defn set-output-dir!
  ```
  Name a directory for all produced files to be placed. For instance,

  `(bagatto/set-output-dir! "site")` will place your generated file
  hierarchy in a directory called `site`.
  ```
  [dir]
  (setdyn :bagatto-output-dir dir))

#
# DATA
#

(defn mmarkdown-data
  "Get metadata from a markdown string using multimarkdown."
  [md]
  (multimarkdown/metadata md))

(defn jdn-data
  "Get metadata from a JDN-formatted string."
  [src]
  (jdn/decode src))

(defn json-data
  "Get metadata from a JSON-formatted string."
  [src]
  (json/decode src))

(defn- adjust-for-display [date]
  (-> (fn [[k v]]
        (if (and (number? v)
                 (index-of k [:month-day :month :year-day :week-day]))
          [k (inc v)]
          [k v]))
      (mapcat (pairs date))
      (splice)
      (struct)))

(defn datestr->secs
  ```
  Given a string representation of a date or datetime, return the
  epoch seconds value for that date.
  ```
  [datestr]
  (-> (sh/$< date -d ,datestr "+%s") (string/trim) (parse)))

(defn datestr->date
  ```
  Given a string representation of a date or datetime, return a struct
  of the kind returned by `os/date`. Pass a truthy value in the second
  argument to adjust for human display (setting values like day and
  month to be 1-indexed).
  ```
  [datestr &opt for-display?]
  (let [parsed (-> datestr
                   (datestr->secs)
                   (os/date))]
    (if for-display? (adjust-for-display parsed) parsed)))

#
# Loaders
#

(def- core-* *)

(defn glob
  [pattern]
  (try
    (sh/glob pattern :x)
    ([err fib]
      (print "[" pattern "] " err)
      @[])))

(defn *
  ```
  Generate a function that will return all the filenames that match a given
  file blob.
  ```
  [pattern]
  (fn [] {:each (glob pattern)}))

(defn slurp-*
  ```
  Generate a function that will slurp all the files that match a given
  file blob.
  ```
  [pattern]
  (fn [] {:each (map |[$0 (slurp $0)] (glob pattern))}))

#
# Attribute Parsers
#

(defn parse-base
  ```
  Base attribute parser: bypasses the input source and returns the
  default attributes that are provided for every file. These are:
  - `:path`: the file path
  - `:contents`: (if the file was read) the contents of the file 
  ```
  [_src attrs]
  attrs)

(defn parse-mmarkdown
  ```
  Attribute parser for multimarkdown.

  (requires the presence of the multimarkdown executable.)
  ```
  [src attrs]
  (merge-into attrs (mmarkdown-data src)))

(defn parse-jdn
  "Attribute parser for JDN."
  [src attrs]
  (merge-into attrs (jdn-data src)))

(defn parse-json
  "Attribute parser for JSON."
  [src attrs]
  (merge-into attrs (json-data src)))

#
# SITE
#

(defn render
  ``` 
  Given site data and an optional item, render the specified Temple template.

  All the attributes will be available in the template under `args`.

  If a single item was passed in in addition to the site, that item
  will be available at `(args :_item)`.

  In addition to the standard Janet library, the same additional
  libraries that Bagatto makes available when writing an index module
  are also available (without explicitly importing them) from within a
  template.

  See the [Temple](https://git.sr.ht/~bakpakin/temple) site for more details.
  ```
  [template site &opt item]

  (def render-context @{:current-template template})
  (set-error-context! :render-context render-context)

  (comptime (def- bufsize (core-* 12 1024)))
  (let [res (buffer/new bufsize)
        env (require template)
        render-dict ((env 'render-dict) :value)
        attrs (merge site {:_item item})]
    (with-dyns [:out res :cxt render-context]
      (render-dict attrs))
    res))

(defn slugify
  "Normalize a string for use as a slug, eg., in a file path."
  [s]
  (def not-alpha (comptime (peg/compile '(if-not (+ :w "-") 1))))
  (def space-underscore (comptime (peg/compile '(set " _"))))
  (if s
    (->> s
         (string/trim)
         (string/ascii-lower)
         (peg/replace-all space-underscore "-")
         (peg/replace-all not-alpha "")
         (string))
    ""))

(defn slug-from-attr
  ```
  Given an object and a key, get the value of that key in the object
  it make the value into a slug.

  (see `bagatto/slugify` for more details.)
  ```
  [item key]
  (string (slugify (item key))))

#
# FOFs
#

(defn renderer
  ```
  Return a function, given a template and optional extra attributes,
  that will call `render` with that template on any input.

  (see `bagatto/render` for more details.)
  ```
  [template-path &opt extra-attrs]
  (default extra-attrs {})
  (fn [site &opt item]
    (let [attrs (table ;(kvs site))]
      (merge-into attrs extra-attrs)
      (render template-path attrs item))))

(defn site-getter
  ```
  Return a function that, given site data or site and item data, gets
  the value at the given path in the site.

  The path should be a tuple of keys, eg.: `[:blog :description]`. 
  ```
  [path]
  (fn [site &opt _item] (get-in site path)))

(defn item-getter
  ```
  Return a function that, given site and item data, gets the value at
  the given path in the item.
  
  The path should be a tuple of keys, eg.: `[:user :full-name]`. 
  ```
  [path]
  (fn [site item] (get-in item path)))

(defn %p
  ````
  Simple DSL for generating paths. 

  Given any number of string or keyword arguments, will return a
  function that takes an item and returns a file path.

  The arguments make up the components of the path. To include an
  element directly in the path, put it as an argument. To indicate
  that an element should be treated as a key in `site`, precede it by
  a `'%s`. To indicate that an element should be treated as a key in
  `item`, precede it by a `'%i`. To join two elements directly,
  without a path separator, put a `'%` between them. For instance,

  ```clj
  repl:9:> (def f (bagatto/%p "site" '%s "author" '%i :title '% ".html"))
  <function 0x55F38B3B3880>
  repl:10:> (f {"author" "Z. D. Smith"} {:title "My first post"})
  "site/z-d-smith/my-first-post.html"
  repl:11:> (f {"author" "Z. D. Smith"} {:title "My second post"})
  "site/z-d-smith/my-second-post.html"
  ```
  ````
  [& elements]
  (fn [site &opt item]
    (default item {})

    (def path-parts @[])

    (var item-key? false)
    (var site-key? false)
    (var push-to-last? false)

    (defn reset-flags! []
      (set item-key? false)
      (set site-key? false))

    (defn reset-push! [] (set push-to-last? false))

    (defn handle-element [x]
      (cond
        (= x '%) (set push-to-last? true)
        (= x '%i) (set item-key? true)
        (= x '%s) (set site-key? true)
        (let [path-component (cond item-key? (do (reset-flags!) (slug-from-attr item x))
                               site-key? (do (reset-flags!) (slug-from-attr site x))
                               x)]
          (if push-to-last?
            (do (reset-push!) (buffer/push-string (last path-parts) path-component))
            (array/push path-parts (buffer path-component))))))

    (each element elements (handle-element element))
    (path/join (splice path-parts))))

(defn- make-path-from-base
  ```
  Generate a new path from a base and an item, using the specified
  attribute in the item (or :path by default)
  ```
  [base item key]
  (path/join base (path/basename (item key))))

(defn path-copier
  ````
  Return a function that will generate a new path with the same
  base, from the same key, for any item.

  eg.:

  ```clj
  repl:2:> (def f (bagatto/path-copier "destination"))
  <function 0x55F38B3AE640>
  repl:3:> (f {} {:path "original/source/directory/filename.md"})
  "destination/filename.md"
  repl:4:> (f {} {:path "original/source/directory/newfile.png"})
  "destination/newfile.png"
  ```
  ````
  [base &opt key]
  (default key :path)
  (fn [_data item]
    (make-path-from-base base item key)))

(defn attr-sorter
  ```
  Return a sorter function that, given a list of items, sorts
  according to the items' values at the specified key.
  ```
  [key &opt descending?]
  (def by (fn [x y] ((if descending? > <) (x key) (y key))))
  (fn [items] (sort items by)))

#
# REPL
#

#
# TEMPLATE
#

(defmacro include
  ````
  Require and render the named template.

  In addition to being a convenient wrapper around

  ```
  {$ (import foo) $}
  {% (foo/render-dict args) %}
  ```

  `include` will update the error-tracking context with the name of
  the included template. This makes it much easier to trace rendering
  errors in nested templates.

  ````
  [template]
  ~(do
     # Write to the template context to track currently rendered template
     (def prev-template ((dyn :cxt) :current-template))
     (put (dyn :cxt) :current-template ,template)
     (let [env (require ,template)
           render-dict ((env 'render-dict) :value)
           out (render-dict args)]
       (put (dyn :cxt) :current-template prev-template)
       out)))

(defn markdown->html
  "Render a markdown string into HTML."
  [md &keys {:opts opts :exts exts}]
  (default opts [:footnotes :smart])
  (default exts [])
  (markable/markdown->html (string md) opts exts))

(defn mmarkdown->html
  ```
  Render a markdown string using multimarkdown.

  Accepts &keys flags :
  - :smart [default: true] enable/disable conversion of typographic
    characters (apostrophes, dashes) into their styled counterparts.

  (requires the presence of the multimarkdown executable.)
  ```
  [md &keys {:smart smart}]
  (multimarkdown/snippet md smart))

(defn format
  ```
  A simple wrapper around `string/format` to ease development. If one
  of `xs` is nil, it will output an empty string rather than crashing
  the template.
  ```
  [templ & xs]
  (let [escaped (map |(or $0 "") xs)]
    (string/format templ ;escaped)))

(defn epp
  ```
  Pretty-print to stderr. Since Temple templates operate over stdout,
  we should use stderr instead if we need to print something to the
  console for debugging purposes.
  ```
  [x]
  (eprint (string/format (dyn :pretty-format "%q") x)))