ciclostile/src/ciclostile/__init__.py

96 lines
2.7 KiB
Python

#!/usr/bin/env python3
import os
import markdown
import jinja2
def parse(mdtext, parser=None):
if parser is None:
parser = markdown.Markdown(extensions=['meta'], output_format='html5')
html = parser.convert(mdtext)
# get markdown metadata
data = {key: parser.Meta[key][0] for key in parser.Meta.keys()}
data.update({
'content': html,
})
return data
def parse_file(filepath, parser=None):
with open(filepath) as fh:
return parse(fh.read(), parser=parser)
def index(folder):
data = {'pages': []}
parser = markdown.Markdown(extensions=['meta'], output_format='html5')
for dirpath, _, files in os.walk(folder):
valid_files = (os.path.join(dirpath, f)
for f in files
if f.endswith('.md'))
for fpath in valid_files:
data['pages'].append(parse_file(fpath, parser=parser))
return data
def compile(template, data):
t = jinja2.Template(template)
return t.render(**data)
def compile_all(root_path):
md_path = os.path.join(root_path, 'markdown')
template_path = os.path.join(root_path, 'templates')
target_path = os.path.join(root_path, 'target')
data = {'pages': {}}
templates = {}
md_files = [f
for f in os.listdir(md_path)
if f.endswith('.md')]
template_files = [f
for f in os.listdir(template_path)
if f.endswith('.html')]
rss_file = 'templates/rss.xml'
for md_fname in md_files:
full_path = os.path.join(md_path, md_fname)
name, _ = os.path.splitext(md_fname)
data['pages'][name] = parse_file(full_path)
data['pages'][name]['link'] = f"/{name}.html"
for file_name in template_files:
full_path = os.path.join(template_path, file_name)
name, _ = os.path.splitext(file_name)
templates[name] = full_path
for page_name, page in data['pages'].items():
t_name = page.get('template', 'default')
with open(templates[t_name]) as tf:
t = jinja2.Template(tf.read())
out_path = os.path.join(target_path, page_name + '.html')
out = t.render(**data['pages'][page_name])
with open(out_path, 'w') as f:
f.write(out)
# index
with open(templates['index']) as fh:
index_template = jinja2.Template(fh.read())
out = index_template.render(**data)
out_path = os.path.join(target_path, 'index.html')
with open(out_path, "w") as f:
f.write(out)
# rss
with open(rss_file) as fh:
rss_template = jinja2.Template(fh.read())
out = rss_template.render(**data)
out_path = os.path.join(target_path, 'rss.xml')
with open(out_path, "w") as f:
f.write(out)