diff piecrust/cache.py @ 3:f485ba500df3

Gigantic change to basically make PieCrust 2 vaguely functional. - Serving works, with debug window. - Baking works, multi-threading, with dependency handling. - Various things not implemented yet.
author Ludovic Chabant <ludovic@chabant.com>
date Sun, 10 Aug 2014 23:43:16 -0700
parents a212a3f2e3ee
children 474c9882decf
line wrap: on
line diff
--- a/piecrust/cache.py	Wed Dec 25 22:16:46 2013 -0800
+++ b/piecrust/cache.py	Sun Aug 10 23:43:16 2014 -0700
@@ -1,13 +1,43 @@
 import os
 import os.path
 import codecs
+import logging
+import threading
+
+
+logger = logging.getLogger(__name__)
+
+
+class ExtensibleCache(object):
+    def __init__(self, base_dir):
+        self.base_dir = base_dir
+        self.lock = threading.Lock()
+        self.caches = {}
+
+    @property
+    def enabled(self):
+        return True
+
+    def getCache(self, name):
+        c = self.caches.get(name)
+        if c is None:
+            with self.lock:
+                c = self.caches.get(name)
+                if c is None:
+                    c_dir = os.path.join(self.base_dir, name)
+                    if not os.path.isdir(c_dir):
+                        os.makedirs(c_dir, 0755)
+
+                    c = SimpleCache(c_dir)
+                    self.caches[name] = c
+        return c
 
 
 class SimpleCache(object):
     def __init__(self, base_dir):
+        self.base_dir = base_dir
         if not os.path.isdir(base_dir):
-            os.makedirs(base_dir, 0755)
-        self.base_dir = base_dir
+            raise Exception("Cache directory doesn't exist: %s" % base_dir)
 
     def isValid(self, path, time):
         cache_time = self.getCacheTime(path)
@@ -33,6 +63,7 @@
 
     def read(self, path):
         cache_path = self.getCachePath(path)
+        logger.debug("Reading cache: %s" % cache_path)
         with codecs.open(cache_path, 'r', 'utf-8') as fp:
             return fp.read()
 
@@ -44,3 +75,40 @@
         with codecs.open(cache_path, 'w', 'utf-8') as fp:
             fp.write(content)
 
+    def getCachePath(self, path):
+        if path.startswith('.'):
+            path = '__index__' + path
+        return os.path.join(self.base_dir, path)
+
+
+class NullCache(object):
+    def isValid(self, path, time):
+        return False
+
+    def getCacheTime(self, path):
+        return None
+
+    def has(self, path):
+        return False
+
+    def read(self, path):
+        raise Exception("Null cache has no data.")
+
+    def write(self, path, content):
+        pass
+
+    def getCachePath(self, path):
+        raise Exception("Null cache can't make paths.")
+
+
+class NullExtensibleCache(object):
+    def __init__(self):
+        self.null_cache = NullCache()
+
+    @property
+    def enabled(self):
+        return False
+
+    def getCache(self, name):
+        return self.null_cache
+