import logging
import logging.config

import yaml
import markdown
from docopt import docopt
from webhelpers import html, date

import kajiki

log = None

loader = kajiki.FileLoader('templates', autoescape_text=True)

def remake_blog():
    global log
    args = docopt("""Usage:
        remake-blog [options]

    Options:
        -h --help                   show this help message and exit
        -c --config=CONFIG          use the given config file [default: blog.yml]
    """)
    with open(args['--config']) as fp:
        config = yaml.load(fp)
    logging.config.dictConfig(config['logging'])
    log = logging.getLogger(__name__)
    log.info('Logging configured')
    helpers = dict(
        html=html,
        date=date)
    for slug, pg in config['pages'].items():
        render_page(
            config,
            fn_out='public/{}.html'.format(slug),
            fn_template=pg.get('template', 'page.html'),
            fn_content=pg.get('content', None),
            page=pg,
            blog=config['blog'],
            h=helpers)

def render_page(config, fn_out, fn_template, fn_content, **kwargs):
    Template = loader.import_(fn_template)
    if fn_content is not None:
        with open(fn_content) as fp:
            content = markdown.markdown(fp.read())
    else:
        content = ''
    with open(fn_out, 'w') as fp:
        context = dict(content=content, **kwargs)
        for chunk in Template(Object.ify(context)):
            fp.write(chunk)

class Object(dict):

    def __getattr__(self, name):
        try:
            return self.__getitem__(name)
        except IndexError:
            raise AttributeError(name)

    @classmethod
    def ify(cls, d):
        if isinstance(d, dict):
            return Object(
                (k, Object.ify(v))
                for k, v in d.items())
        elif isinstance(d, list):
            return [Object.ify(v) for v in d]
        else:
            return d



@@ -1,20 +1,42 @@
+import os%0Aimport glob%0A
 import logging%0Aimpor
@@ -135,16 +135,22 @@
 rt html,
+ text,
  date%0A%0Ai
@@ -236,16 +236,77 @@
 xt=True)
+%0Ahelpers = dict(%0A    html=html,%0A    text=text,%0A    date=date)
 %0A%0Adef re
@@ -764,41 +764,268 @@
     
-helpers = dict(%0A        html=
+posts = %5B%5D%0A    for fn_content in glob.glob('posts/*.md'):%0A        slug = os.path.basename(fn_content).rsplit('.', 1)%5B0%5D%0A        entry = render_page(%0A            config,%0A            fn_out='public/posts/%7B%7D.html'.format(slug),%0A            fn_template='post.
 html
+'
 ,%0A  
@@ -1030,24 +1030,192 @@
         
+  
-date=dat
+  fn_content=fn_content,%0A            blog=config%5B'blog'%5D,%0A            h=helpers)%0A        posts.append(Object.ify(entry))%0A    posts.sort(key=lambda p: p.meta.date, reverse=Tru
 e)%0A    f
@@ -1525,16 +1525,41 @@
 =helpers
+,%0A            posts=posts
 )%0A%0Adef r
@@ -1621,16 +1621,165 @@
 wargs):%0A
+    path = '/' + '/'.join(fn_out.split('/')%5B1:%5D)%0A    md = markdown.Markdown(extensions=%5B'meta'%5D)%0A    md_pre = markdown.Markdown(extensions=%5B'meta'%5D)%0A
     Temp
@@ -1885,32 +1885,35 @@
 fp:%0A            
+md_
 content = markdo
@@ -1910,34 +1910,138 @@
 t = 
-markdown.markdown(fp.read(
+fp.read()%0A        content = md.convert(md_content)%0A        preview = md_pre.convert(text.truncate(md_content, 300, whole_word=True
 ))%0A 
@@ -2066,16 +2066,26 @@
 ontent =
+ preview =
  ''%0A    
@@ -2141,34 +2141,145 @@
 ict(
-content=content, **kwargs)
+%0A            path=path, content=content, preview=preview, **kwargs)%0A        if hasattr(md, 'Meta'):%0A            context%5B'meta'%5D = md.Meta
 %0A   
@@ -2354,16 +2354,35 @@
 e(chunk)
+%0A    return context
 %0A%0Aclass 

Add basic blog functionality