1
0
Fork 0
forked from github/pelican
pelican-theme/pelican/generator.py

182 lines
5.8 KiB
Python
Raw Normal View History

2010-08-17 15:04:12 +02:00
# -*- coding: utf-8 -*-
2010-08-14 05:45:16 +02:00
import os
2010-08-17 15:04:12 +02:00
import re
from codecs import open
from datetime import datetime
from docutils import core
2010-08-14 05:45:16 +02:00
from functools import partial
from operator import attrgetter
2010-08-14 05:45:16 +02:00
2010-08-17 15:04:12 +02:00
from jinja2 import Environment, FileSystemLoader
import rstdirectives # import the directives to have pygments support
2010-08-14 05:45:16 +02:00
_TEMPLATES = ('index', 'tag', 'tags', 'article', 'category', 'categories',
'archives')
_DIRECT_TEMPLATES = ('index', 'tags', 'categories', 'archives')
_DEFAULT_TEMPLATE_PATH =\
os.sep.join([os.path.dirname(os.path.abspath(__file__)), "themes"])
2010-08-14 05:45:16 +02:00
def generate_output(files, templates_path=None, output_path=None, markup=None,
settings=None):
2010-08-14 05:45:16 +02:00
"""Given a list of files, a template and a destination,
output the static files.
:param files: the list of files to parse
:param templates_path: where to search for templates
:param output_path: where to output the generated files
:param markup: the markup language to use while parsing
:param settings: the settings file to use
2010-08-14 05:45:16 +02:00
"""
if not templates_path:
templates_path = _DEFAULT_TEMPLATE_PATH
if not output_path:
output_path = './output'
output_path = os.path.realpath(output_path)
articles, dates, years, tags, categories = [], {}, {}, {}, {}
2010-08-14 05:45:16 +02:00
# for each file, get the informations.
for f in files:
f = os.path.abspath(f)
2010-08-17 15:04:12 +02:00
article = Article(open(f, encoding='utf-8').read(), markup)
2010-08-14 05:45:16 +02:00
articles.append(article)
if hasattr(article, 'date'):
update_dict(dates, article.date.strftime('%Y-%m-%d'), article)
2010-08-14 05:45:16 +02:00
update_dict(years, article.date.year, article)
if hasattr(article, 'tags'):
for tag in article.tags:
update_dict(tags, tag, article)
if hasattr(article, 'category'):
update_dict(categories, article.category, article)
# order the articles by date
articles.sort(key=attrgetter('date'), reverse=True)
2010-08-14 05:45:16 +02:00
templates = get_templates(templates_path)
context = {}
for item in ('articles', 'dates', 'years', 'tags', 'categories'):
value = locals()[item]
if hasattr(value, 'items'):
value = value.items()
context[item] = value
read_settings(context, settings)
2010-08-14 05:45:16 +02:00
generate = partial(generate_file, output_path)
for template in _DIRECT_TEMPLATES:
generate('%s.html' % template, templates[template], context)
2010-08-14 05:45:16 +02:00
for tag in tags:
generate('tag/%s.html' % tag, templates['tag'], context, tag=tag)
2010-08-14 05:45:16 +02:00
for cat in categories:
generate('category/%s.html' % cat, templates['category'], context,
2010-08-14 05:45:16 +02:00
category=cat)
for article in articles:
generate('%s' % article.url,
templates['article'], context, article=article)
def generate_file(path, name, template, context, **kwargs):
context.update(kwargs)
output = template.render(context)
filename = os.sep.join((path, name))
2010-08-14 05:45:16 +02:00
try:
os.makedirs(os.path.dirname(filename))
except Exception:
pass
2010-08-17 15:04:12 +02:00
with open(filename, 'w', encoding='utf-8') as f:
2010-08-14 05:45:16 +02:00
f.write(output)
print filename
def get_templates(path=None):
env = Environment(loader=FileSystemLoader(path))
templates = {}
for template in _TEMPLATES:
templates[template] = env.get_template('%s.html' % template)
return templates
def update_dict(mapping, key, value):
if key not in mapping:
mapping[key] = []
mapping[key].append(value)
def read_settings(context, filename):
2010-08-18 15:08:35 +02:00
"""Load a Python file into a dictionary.
"""
if filename:
2010-08-18 15:08:35 +02:00
tempdict = {}
execfile(filename, tempdict)
for key in tempdict:
if key.isupper():
2010-08-18 15:08:35 +02:00
context[key] = tempdict[key]
return context
_METADATA = re.compile('.. ([a-z]+): (.*)', re.M)
_METADATAS_FIELDS = {'tags': lambda x: x.split(', '),
'date': lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M'),
'category': lambda x: x,
'author': lambda x: x}
def parse_metadata(string):
"""Return a dict, containing a list of metadata informations, found
2010-08-14 05:45:16 +02:00
whithin the given string.
:param string: the string to search the metadata in
"""
output = {}
for m in _METADATA.finditer(string):
name = m.group(1)
value = m.group(2)
if name in _METADATAS_FIELDS:
output[name] = _METADATAS_FIELDS[name](value)
return output
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
Took from django sources.
"""
import unicodedata
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return re.sub('[-\s]+', '-', value)
class Article(object):
"""Represents an article.
Given a string, complete it's properties from here.
:param string: the string to parse, containing the original content.
:param markup: the markup language to use while parsing.
"""
def __init__(self, string, markup=None):
if markup == None:
markup = 'rest'
for key, value in parse_metadata(string).items():
2010-08-14 05:45:16 +02:00
setattr(self, key, value)
if markup == 'rest':
2010-08-17 15:04:12 +02:00
extra_params = {'input_encoding': 'unicode',
'initial_header_level': '2'}
rendered_content = core.publish_parts(string, writer_name='html',
settings_overrides=extra_params)
2010-08-14 05:45:16 +02:00
self.title = rendered_content.get('title')
self.content = rendered_content.get('body')
@property
def url(self):
return '%s.html' % slugify(self.title)
2010-08-14 05:45:16 +02:00
@property
def summary(self):
return self.content
2010-08-14 05:45:16 +02:00
def __repr__(self):
return '<%s "%s">' % (self.__class__.__name__, self.title)