summaryrefslogtreecommitdiff
path: root/obsapi/formatter.py
blob: fd5c70fd4e6e31d318a72607030cacfd10071c8d (plain)
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
# -*- coding: utf-8 -*-
"""
    obsapi: formatter module
    ~~~~~~~~~~~~~~~~~~~~~~~~

    This module contains the FateFormatter class


    :copyright: Copyright (c) 2016 Scott Bahling, SUSE Linux GmbH
    :license: GPL-2.0, see COPYING for details
"""
import os
from jinja2 import Environment, FileSystemLoader, TemplateNotFound, Template

pkg_path = os.path.dirname(__file__)

class Formatter(object):
    """Formatter
    Renders a string representation of an object based on Jinja2
    templating.

    :param obj: Object to be formatted
    :param searchpath: Directory or list of directories to
                       search for templates

    A template is selected from the searchpath based on the name
    of the object class with a '.j2' extension. If no template
    is found matching the class name, the default template
    (default.j2) will be used.
    The render() method will create a text output representing
    the object based on the selected template.
    """
    default_searchpath = [os.path.expanduser('~/.obsapi/templates'),
                          os.path.join(pkg_path, 'templates'),
                          ]

    def __init__(self, obj, searchpath=None):
        searchpath = searchpath or self.default_searchpath
        self.env = Environment(loader=FileSystemLoader(searchpath))
        self.obj = obj

    @property
    def template_name(self):
        return "%s.j2" % self.obj.__class__.__name__

    @property
    def searchpath(self):
        return self.env.loader.searchpath

    @searchpath.setter
    def searchpath(self, path):
        self.env.loader.searchpath = path

    @property
    def template(self):
        try:
            return self.env.get_template(self.template_name)
        except TemplateNotFound:
            try:
                return self.env.get_template('default.j2')
            except:
                return Template('{{this.__class__.__name__}}')

    def render(self):
        return self.template.render(this=self.obj)