aboutsummaryrefslogtreecommitdiff
path: root/rss.py
blob: fbf70d113e7f060a88a33960546f627aecc62e77 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by [email protected] at 2015-07-30

import os
import argparse
import yaml

import jinja2


class FilePathLoader(jinja2.BaseLoader):
    """ Custom Jinja2 template loader which just loads a single template file """

    def __init__(self, cwd):
        self.cwd = cwd

    def get_source(self, environment, template):
        # Path
        filename = os.path.join(self.cwd, template)

        # Read
        try:
            with open(filename, 'r') as f:
                contents = f.read()
        except IOError:
            raise jinja2.TemplateNotFound(filename)

        # Finish
        uptodate = lambda: False
        return contents, filename, uptodate


def render_template(cwd, template_path, context):
    env = jinja2.Environment(loader=FilePathLoader(cwd))

    return env \
        .get_template(template_path) \
        .render(context)


def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('--dir', default='.', help='Template directory')
    parser.add_argument('--data', nargs='*', help='One or more YAML data file')
    parser.add_argument('--template', help='Template file to process')
    parser.add_argument('--body', help='Body content')
    args = parser.parse_args()

    context = dict()
    for data_f in args.data if args.data else []:
        key, filename = data_f.split(':')
        if filename:
            context[key] = yaml.load(open(filename).read())
        else:
            context[key] = {'_': True}
    if args.body:
        context['body'] = open(args.body).read()

    return render_template(
        args.dir,
        args.template,
        context
    )

if __name__ == '__main__':
    print(main())
Powered by cgit v1.2.3 (git 2.41.0)