Source

hh-web-tags / templates.lisp

  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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
;; Copyright (c) 2010 Haphazard House LLC

;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:

;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.

;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.

(in-package :hh-web)

(export 
 (list

  'template
  'deftemplate
  'deftemplates
  '*template*
  '*template-provider-registry*
  'create-folder-template-provider
  'create-asdf-system-template-provider

  )
)

;;;------------------------------------------------------------------------------------
;;; Dynamic variables
;;;------------------------------------------------------------------------------------

(defvar *template-provider-registry* ()
  "List of template providers, each of which will be called to resolve a template name
  to locate an appropriate template"
)

(defvar *template-cache* (make-hash-table :test 'equal)
  "Cache of template names to template obejcts"
  )

(defvar *template* ()
  "While reading a template, this is the current template object for whom
   a definition is being read"
  )

(defvar *minimum-template-stale-time* 1
  "Minimum time in seconds for which a template must remain stale (e.g. not expire,
   before reloading from its source"
)

;;;------------------------------------------------------------------------------------
;;; Conditions
;;;------------------------------------------------------------------------------------

(define-condition template-not-found-error (error) 
  (
   (template-path
    :initarg :path
    :reader template-path
    )
   )
  (:report (lambda (condition stream)
             (format stream "Could not find template ~a~%."
                     (template-path condition)
		     )
	     )
	   )
  )

;;;------------------------------------------------------------------------------------
;;; Templates
;;;------------------------------------------------------------------------------------

(defclass template ()
  (
   (path
    :initarg :path
    :reader template-path
    )
   (provider
    :initarg :provider
    :accessor template-provider
    )
   (libraries
    :initform nil
    :accessor tag-libraries-used
    )
   (modified-time
    :initform (now)
    :accessor modified-time-of
    )
   (package
    :initform (make-package (gensym))
    :initarg :package
    :accessor template-package
    )
   (args
    :initform ()
    :initarg :args
    :accessor template-args
    )
   (kwargs
    :initform ()
    :initarg :kwargs
    :accessor template-keyword-args
    )
   (definition
    :initform ()
    :initarg :definition
    :accessor definition-of
    )
   )
)

(defgeneric template-stalep (tmpl)
  (:method ( (tmpl template) )
    (if (definition-of tmpl)
	(timestamp> (now) 
	   (timestamp+ (modified-time-of tmpl) *minimum-template-stale-time* :sec)
	   )
	t
	)
    )
  )

(defgeneric template-tags-expiredp (tmpl)
  (:documentation "Return t if any of the known required tag libraries
   used in the template have expired; nil otherwise"
		  )
  (:method ( (tmpl template) )
    (find-if #'(lambda (library-name) 
		 (let (
		       (library (find-cached-tag-library library-name))
		       )
		   (if library
		       (tag-library-expiredp (hh-web::find-cached-tag-library library-name) )
		       t
		       )
		   )
		 )
	     (hh-web::tag-libraries-used tmpl )
	     )
    )
  )

(defgeneric template-expiredp (tmpl)
  (:method ( (tmpl template) )
    (when (template-stalep tmpl)
      (or (template-tags-expiredp tmpl)
	  (not (slot-boundp tmpl 'provider) )
	  (provider-template-expiredp tmpl (template-provider tmpl) )
	  )
      )
    )
  )

;;;------------------------------------------------------------------------------------
;;; Template providers
;;;------------------------------------------------------------------------------------

(defclass template-provider ()
  ()
  )

; -- Base functions suggested all providers implement

(defgeneric provider-template-expiredp (*template* provider)
  (:documentation "Return t if the provider considers
   the template expired, otherwise nil"
		  )
  (:method ( tmpl (provider template-provider)  )
    t
    )
  )

(defgeneric load-template-from-provider (*template* template-path provider)
  (:documentation "If the provider can provide a template with the indicated path,
   return the template; otherwise, return nil"
		  )
  )

; -- Helper and framework functions

(defun process-directive (expr)
  "Useful for pre-processing specific expressions as directives inside a template;
  returns nil if the expression is *not* a directive--returns t if the expr
  should be regarded as a directive and discarded"
  (if (listp expr)
      (cond ;; will likely need to add more cases over time
	( (eql '+tag-library (car expr) ) (eval expr) t )
	)	   ; defaults to nil if no match, meaning no directive
      nil
      )
  )

(defgeneric read-template-definition (input-stream template-package template-args template-keyword-args)
  (:documentation "Read a template definition from a stream"
		  )

  (:method ( (input-stream stream) (template-package package) (template-args list) (template-keyword-args list) )
    (let (
	  (*package* template-package)
	  (*read-eval* nil) 
	  )
					; import arguments into the template package--otherwise reader will create different symbols
      (dolist (arg template-args)
	(import arg template-package)
	)
      (dolist (kwarg template-keyword-args)
	(import kwarg template-package)
	)
					; setup template package for use
      (use-package 'cl template-package)
      (use-package 'cl-user template-package)
      (use-package 'hh-web template-package)
					; read template
      (loop 
	 while (listen input-stream)
	 for expr = (read input-stream) then (read input-stream)
	 unless (process-directive expr) collect expr
	 )
      )
    )
  (:method ( (input-string string) (template-package package) (template-args list) (template-keyword-args list) )
    (with-input-from-string (input-stream input-string)
      (read-template-definition input-stream template-package template-args template-keyword-args)
      )
    )
  )

(defun load-template-definition (*template* template-path &optional (*template-provider-registry* *template-provider-registry*) )
  "Load the indicated template definition from the first provider that can"
  (when *template-provider-registry*
    (let* (
	   (template-provider (car *template-provider-registry*) )
	   (found-template-definition (when template-provider
					(load-template-from-provider *template* template-path template-provider ) 
					)
	     )
	   )
      (if found-template-definition
	  found-template-definition
	  (load-template-definition *template* template-path (cdr *template-provider-registry*) )
	  )
      )
    )
  )

(defgeneric load-template (template-path &optional template-args template-keyword-args)
  (:method (template-path &optional (template-args nil) (template-keyword-args nil) )
    (let* (
	  (*template* (make-instance 'template 
			       :path template-path
			       :args template-args 
			       :kwargs template-keyword-args
			       ) 
	    )
	  (definition (eval `(lambda (,@template-args ,@(if template-keyword-args `(&key ,@template-keyword-args)) )
				,@(or (load-template-definition *template* template-path)
				      `( 
					(error 'template-not-found-error :path ,template-path) 
					)
				      )
			       )
		      )
	    )
	  )
      (setf (definition-of *template*) definition)
      (setf (gethash template-path *template-cache*) *template*)
      *template*
      )
    )
  )

(defun flush-template (template-path cached-template)
  "Safely a cached template, typically for reloading"
  ;; remove the template from the cache
  (remhash template-path *template-cache*)
  ;; also, delete the template's package...could clutter up the runtime
  (when (template-package cached-template)
    (delete-package (template-package cached-template))
    )
  )

(defun find-cached-template (template-path)
  (let (
	(cached-template (gethash template-path *template-cache* nil) )
	)
    (if cached-template
	(if (template-expiredp cached-template) 
	    (progn
	      (flush-template template-path cached-template)
	      nil
	      )
	    cached-template
	    )
	)
    )
  )

;; -------- File-based template provider ---------------------
;; 
;;  Generalized definitions designed to aid any template provider
;;  that serves templates from a filesystem

(defclass file-based-template-provider (template-provider)
  (
   )
  (:documentation "Generalized type for providers serving templates from the filesystem")
)

(defgeneric template-provider-base-directory (provider)
  (:documentation "Returns the base directory on a fileystem for templates 
    served by the provider.  Directory name should end in /."
		  )
  )

(defgeneric template-full-path (template-path provider)
  (:method (template-path (provider file-based-template-provider) )
    (let (
	   (provider-path (template-provider-base-directory provider) )
					; folder-name should be an absolute path, ending / to indicate directory
	   )
      (merge-pathnames (make-pathname :directory (pathname-directory template-path)
				      :name (pathname-name template-path)
				      :type (pathname-type template-path)
				      ) 
		       (make-pathname :host (pathname-host provider-path)
				      :directory (pathname-directory provider-path)
				      )
		       )
      )
    )
)

(defgeneric template-file-modified-time (template-path provider)
  (:method (template-path (provider file-based-template-provider) )
    (let (
	  (full-path (template-full-path template-path provider) )
	  )
      (unix-to-timestamp (sb-posix:stat-mtime (sb-posix:stat full-path)) )
      )
    )
  )

; -- Implementation of base template-provider functions

(defmethod provider-template-expiredp (*template* (provider file-based-template-provider) )
  (let (
	(full-path (template-full-path (template-path *template*) provider) )
	)
    (timestamp> (template-file-modified-time full-path provider)
		(modified-time-of *template*)
		)
    )
  )

(defmethod load-template-from-provider ( (*template* template) template-path (provider file-based-template-provider) )
  (let (
	(full-path (template-full-path template-path provider) )
	)
    (when (probe-file full-path)
      (setf (template-provider *template*) provider)
      (setf (modified-time-of *template*) 
	    (template-file-modified-time template-path provider)
	    )
      (read-template-definition (open full-path :direction :input) (template-package *template*)
				(template-args *template*)
				(template-keyword-args *template*)
				)
      )
    )
  )

;; -------- Folder provider ---------------------
;; 
;;  provides templates in individual files of a specified 
;;  folder on the filesystem

(defclass folder-template-provider (file-based-template-provider)
  (
   (folder
    :initarg :folder
    :accessor folder-of
    )
   )
)

(defmethod template-provider-base-directory ( (provider folder-template-provider) )
  (folder-of provider)
  )

(defun create-folder-template-provider (folder)
  (make-instance 'folder-template-provider :folder folder)
  )

;; -------- ASDF system provider ---------------------
;; 
;;  Services for templates a "templates" folder using 
;;  asdf:system-relative-pathname and the indicated system, and provides
;;  templates in individual files from any of those locations
;;

(defclass asdf-system-provider (file-based-template-provider)
  (
   (system
    :initform nil
    :initarg :system
    :accessor system-of
    )
   )
)

(defmethod template-provider-base-directory ( (provider asdf-system-provider) )
  (asdf:system-relative-pathname (system-of provider) (make-pathname :directory `(:relative "templates")) )
  )

(defun create-asdf-system-template-provider (system)
  (make-instance 'asdf-system-provider :system system)
)

; -- Implementation of base template-provider functions

(defmethod provider-template-expiredp (*template* (provider asdf-system-provider) )
  (let (
	(full-path (template-full-path (template-path *template*) provider) )
	)
    (when (probe-file full-path) ;; if file does not exist, no point in declaring it expired--can't reload anyway
      (timestamp> (template-file-modified-time full-path provider)
		  (modified-time-of *template*)
		  )
      )
    )
  )

(defmethod load-template-from-provider ( (*template* template) template-path (provider asdf-system-provider) )
  (let (
	(full-path (template-full-path template-path provider) )
	)
    (when (probe-file full-path)
      (setf (template-provider *template*) provider)
      (setf (modified-time-of *template*) 
	    (template-file-modified-time template-path provider)
	    )
      (read-template-definition (open full-path :direction :input) (template-package *template*)
				(template-args *template*)
				(template-keyword-args *template*)
				)
      )
    )
  )


;;;------------------------------------------------------------------------------------
;;;  Template declaration
;;;
;;;  Templates can have arguments, both positional and keyword.  It is important
;;;  that these argument lists have no specializers or other qualifiers (such as 
;;;  default values), as the same lists will be used both to declare arguments to 
;;;  the template invocation macro and to pass values to the template's definition 
;;;  function.
;;;
;;;------------------------------------------------------------------------------------

(defmacro deftemplate (name
		       path
		       &key
		       ((:args template-args) nil)
		       ((:kwargs template-keyword-args) nil)
		       )
  `(progn

     ;; pre-load -- note that this will likely create definitions in error, because a template cannot be found
     ;; doing this so that a "reload" later can find all the templates to reload
     (load-template ,path (quote ,template-args) (quote ,template-keyword-args) )

     ;; create a macro to invoke the template
     (defmacro ,name (,@template-args ,@(if template-keyword-args `(&key ,@template-keyword-args)) )
       (let (
	     (path (quote ,path) )
	     (template-args (quote ,template-args) )
	     (template-arg-values (list ,@template-args) )
	     (template-keyword-args (quote ,template-keyword-args) )
	     )
	 `(let (
		(tmpl (or (find-cached-template ,path) 
			  (load-template ,path (quote ,template-args) (quote ,template-keyword-args) )
			  )
		  )
		)
	    (when tmpl
	      (funcall (definition-of tmpl) ,@template-arg-values ,@template-keyword-args)
	      )
	    )
	 )
       )
     )
  )

(defun local-template-provider-registry-symbol () 
  "Returns a symbol in the current package for storing the template provider registry expected by the package"
  (intern "*PACKAGE-TEMPLATE-PROVIDER-REGISTRY*" *package*) 
  )

(defun local-tag-library-provider-registry-symbol () 
  "Returns a symbol in the current package for storing the tag library provider registry expected by the package"
  (intern "*PACKAGE-TAG-LIBRARY-PROVIDER-REGISTRY*" *package*) 
  )

(defmacro deftemplates (
			&key
			((:tag-library-packages tag-library-packages) nil)
			((:template-packages template-packages) nil)
			((:templates templates) nil)
			)
  (let (
	(template-provider-registry (local-template-provider-registry-symbol) )
	(tag-library-provider-registry (local-tag-library-provider-registry-symbol) )
	)
    `(progn
       (defparameter ,template-provider-registry
	 (list ,@(append (mapcar (lambda (template-package)
				   `(create-asdf-system-template-provider (quote ,template-package))
				   )
				 template-packages
				 )
			 (list `(create-asdf-system-template-provider 'hh-web ) ) ;; always here by default
			 )
	       )
	 )

       (defparameter ,tag-library-provider-registry
	 (list ,@(append (mapcar (lambda (tag-library-package)
				   `(create-asdf-system-tag-library-provider (quote ,tag-library-package) )
				   )
			       tag-library-packages
			       )
		       (list `(create-asdf-system-tag-library-provider 'hh-web ) ) ;; always here by default
		       ) 
	     )
       )

       (let (
	     (*tag-library-provider-registry* ,tag-library-provider-registry)
	     (*template-provider-registry* ,template-provider-registry)
	     )
	 ,@(mapcar (lambda (template)
		     `(deftemplate ,@template)
		     )
		   templates
		   )
	 )
     )
  )
  )

;;;------------------------------------------------------------------------------------
;;;  Tag library use in templates
;;;
;;;  Used at top of template files; modifies the template's package (actually, *package*)
;;;  to use the tag library's package.
;;;

(defun +tag-library (library-name)
  "Find the tag-library (if possible), and import it into the
   current package (e.g., found by looking at *package* in
   dynamic environment
   "
  (let (
	  (library (import-tag-library library-name) )
	  )
     (when library
       (when *template*
	 (putendnew library-name (tag-libraries-used *template*) :test 'equal)
	 )
       library
       )
     )
  nil
  )