You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
pollen/cache.rkt

47 lines
1.5 KiB
Racket

#lang racket/base
(require racket/rerequire)
10 years ago
(require "debug.rkt" sugar/coercion/values)
10 years ago
;; The cache is a hash with paths as keys.
;; The cache values are also hashes, with key/value pairs for that path.
10 years ago
(provide current-cache make-cache cached-require cache-ref)
;; Don't initialize a cache when the module is loaded. This induces reliance.
;; The cache only makes sense if a single one is used across a whole session (e.g., via parameterize).
(define current-cache (make-parameter #f))
10 years ago
(define (make-cache) (make-hash))
10 years ago
(define (cache-ref path-string)
10 years ago
(hash-ref (current-cache) (->complete-path path-string)))
10 years ago
(define (cache-has-key? path)
(hash-has-key? (current-cache) path))
10 years ago
(define (cache path)
(dynamic-rerequire path)
(hash-set! (current-cache) path (make-hash))
(define cache-hash (cache-ref path))
(hash-set! cache-hash 'mod-time (file-or-directory-modify-seconds path))
(hash-set! cache-hash 'main (dynamic-require path 'main))
(hash-set! cache-hash 'metas (dynamic-require path 'metas))
(void))
10 years ago
(define (cached-require path-string key)
(when (not (current-cache)) (error "cached-require: No cache set up."))
10 years ago
(define path
(with-handlers ([exn:fail? (λ(exn) (displayln (format "cached-require: ~a is not a valid path" path-string)))])
10 years ago
(->complete-path path-string)))
10 years ago
(when (or (not (cache-has-key? path))
(> (file-or-directory-modify-seconds path) (hash-ref (cache-ref path) 'mod-time)))
(cache path))
10 years ago
(hash-ref (cache-ref path) key))