constance

Scripts for generating (an earlier obsolete version of) my personal web site
git clone https://code.djc.id.au/git/constance/
commit ded2937411793278c2a9cd87fa79c96280be50ae
parent 62a672115d4213fc14c3b23ffbc8ed1f2473d29b
Author: Dan Callaghan <djc@djc.id.au>
Date:   Wed, 17 Sep 2008 18:59:11 +1000

use builtin email module instead of mdx_meta for header parsing

Diffstat:
Mblog.py | 30+++++++++++++++++-------------
Dlib/mdx_meta.py | 81-------------------------------------------------------------------------------
2 files changed, 17 insertions(+), 94 deletions(-)
diff --git a/blog.py b/blog.py
@@ -1,4 +1,4 @@
-import os, re, uuid
+import os, re, uuid, email
 from datetime import datetime
 import markdown
 import genshi
@@ -11,12 +11,14 @@ def count(iterable):
         count += 1
     return count
 
-def cleanup_metadata(meta):
+def cleanup_metadata(header_items):
     cleaned = {}
-    for k, v in meta.iteritems():
-        v = '\n'.join(v)
+    for k, v in header_items:
+        k = k.lower()
         if k.endswith('date'):
             v = datetime.strptime(v, '%Y-%m-%d %H:%M:%S')
+        else:
+            v = v.decode('utf8') # XXX encoding
         cleaned[k] = v
     return cleaned
 
@@ -88,10 +90,12 @@ class BlogEntry(object):
         if not os.access(self.dir, os.R_OK):
             raise EntryForbiddenError()
 
-        self.raw = open(os.path.join(self.dir, 'content.txt'), 'r').read().decode('utf-8')
-        md = markdown.Markdown(extensions=['meta', 'typography'])
-        self.body = genshi.Markup(md.convert(self.raw))
-        self.metadata = cleanup_metadata(md.Meta)
+        # not really a MIME document, but parse it like one
+        msg = email.message_from_file(open(os.path.join(self.dir, 'content.txt'), 'r'))
+        self.metadata = cleanup_metadata(msg.items())
+        self.raw_body = msg.get_payload().decode('utf8') # XXX encoding
+        md = markdown.Markdown(extensions=['typography'])
+        self.body = genshi.Markup(md.convert(self.raw_body))
         self.title = self.metadata['title']
 
         raw_tags = self.metadata.get('tags', '').strip()
@@ -164,11 +168,11 @@ class Comment(object):
             raise CommentForbiddenError()
 
         self.id = id
-        self.raw = open(path, 'r').read().decode('utf-8')
-        md = markdown.Markdown(extensions=['meta', 'typography'], safe_mode='escape')
-        self.body = genshi.Markup(md.convert(self.raw))
-        if not hasattr(md, 'Meta'): raise Exception(self.raw)
-        self.metadata = md.Meta
+        msg = email.message_from_file(open(path, 'r'))
+        self.metadata = cleanup_metadata(msg.items())
+        self.raw_body = msg.get_payload().decode('utf8') # XXX encoding
+        md = markdown.Markdown(extensions=['typography'], safe_mode='escape')
+        self.body = genshi.Markup(md.convert(self.raw_body))
         
         self.author = self.metadata.get('from', None)
         self.author_url = self.metadata.get('author-url', None)
diff --git a/lib/mdx_meta.py b/lib/mdx_meta.py
@@ -1,81 +0,0 @@
-#!usr/bin/python
-
-'''
-Meta Data Extension for Python-Markdown
-==========================================
-
-This extension adds Meta Data handling to markdown.
-
-    >>> import markdown
-    >>> text = """Title: A Test Doc.
-    ... Author: Waylan Limberg
-    ...         John Doe
-    ... Blank_Data:
-    ...
-    ... The body. This is paragraph one.
-    ... """
-    >>> md = markdown.Markdown(text, ['meta'])
-    >>> str(md)
-    '<p>The body. This is paragraph one.\\n</p>'
-    >>> md.Meta
-    {'blank_data': [''], 'author': ['Waylan Limberg', 'John Doe'], 'title': ['A Test Doc.']}
-
-Make sure text without Meta Data still works (markdown < 1.6b returns a <p>).
-
-    >>> text = '    Some Code - not extra lines of meta data.'
-    >>> md = markdown.Markdown(text, ['meta'])
-    >>> str(md)
-    '<pre><code>Some Code - not extra lines of meta data.\\n</code></pre>'
-    >>> md.Meta
-    {}
-
-'''
-
-import markdown, re
-
-# Global Vars
-META_RE = re.compile(r'^[ ]{0,3}(?P<key>[A-Za-z0-9_-]+):\s*(?P<value>.*)')
-META_MORE_RE = re.compile(r'^[ ]{4,}(?P<value>.*)')
-
-class MetaExtension (markdown.Extension) :
-    def __init__(self, configs):
-        pass
-
-    def extendMarkdown(self, md, md_globals) :
-        self.md = md
-
-        # Insert meta preprocessor first
-        META_PREPROCESSOR = MetaPreprocessor()
-        META_PREPROCESSOR.md = md
-        md.preprocessors.insert(0, META_PREPROCESSOR)
-        
-class MetaPreprocessor(markdown.Preprocessor) :
-    def run(self, lines) :
-        meta = {}
-        key = None
-        while 1:
-            line = lines.pop(0)
-            if line.strip() == '':
-                break # blank line - done
-            m1 = META_RE.match(line)
-            if m1:
-                key = m1.group('key').lower().strip()
-                meta[key] = [m1.group('value').strip()]
-            else:
-                m2 = META_MORE_RE.match(line)
-                if m2 and key:
-                    # Add another line to existing key
-                    meta[key].append(m2.group('value').strip())
-                else:
-                    lines.insert(0, line)
-                    break # no meta data - done
-        self.md.Meta = meta
-        return lines
-        
-
-def makeExtension(configs=None) :
-    return MetaExtension(configs=configs)
-
-if __name__ == "__main__":
-    import doctest
-    doctest.testmod()