Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic Templates #825

Merged
merged 2 commits into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/std/build-spec.ss
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@
"misc/path"
"misc/symbol"
"misc/rwlock"
"misc/template"
;; :std/protobuf
"protobuf/io"
"protobuf/macros"
Expand Down
61 changes: 61 additions & 0 deletions src/std/misc/template.ss
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
;;; -*- Gerbil -*-
;;; © vyzo
;;; string templates
(export write-template
apply-template)
(import :std/io
(only-in :std/srfi/1 reverse!))

(def (write-template template output . args)
(let (str (apply apply-template template args))
(cond
((input-port? output)
(display str output))
((is-StringWriter? output)
(StringWriter-write-string output str))
((is-BufferedWriter? output)
(BufferedWriter-write-string output str))
(else
(error "Bad argument; expected port, StringWriter or BufferedWriter" output)))))

(def (apply-template template . args)
(def vars (make-hash-table))

(let lp ((rest args))
(match rest
([(? keyword? key) val . rest]
(hash-put! vars (keyword->string key) val)
(lp rest))
([] (void))))

(call-with-output-string ""
(lambda (output)
(let lp ((rest (string->list template)))
(match rest
([char . rest]
(if (eqv? char #\$)
(match rest
([char . rest]
(if (eqv? char #\{)
(let lp-inner ((rest rest) (var []))
(match rest
([char . rest]
(if (eqv? char #\})
(begin
(display (hash-ref vars (list->string (reverse! var)))
output)
(lp rest))
(lp-inner rest (cons char var))))
(else
(error "incomplete variable substitution"))))
(begin
(display #\$ output)
(display char output)
(lp rest))))
(else
(display #\$ output)
(lp rest)))
(begin
(display char output)
(lp rest))))
(else (void)))))))