summaryrefslogtreecommitdiff
path: root/obsapi/formatter.py
diff options
context:
space:
mode:
authorScott Bahling <sbahling@suse.de>2016-03-03 02:19:13 +0100
committerScott Bahling <sbahling@suse.de>2016-03-03 02:19:13 +0100
commit3ea5bd07c23838b1a96357089e8173a094dfaed1 (patch)
tree0ee4b228a35a37c6d120e85cc2b7cc6ebacaa8fc /obsapi/formatter.py
parent224e2ce1d43045e567a1c782830a24432531aa8b (diff)
downloadobsapi-3ea5bd07c23838b1a96357089e8173a094dfaed1.tar.gz
obsapi-3ea5bd07c23838b1a96357089e8173a094dfaed1.tar.xz
obsapi-3ea5bd07c23838b1a96357089e8173a094dfaed1.zip
Add formatter class and extend FileInfo class
Diffstat (limited to 'obsapi/formatter.py')
-rw-r--r--obsapi/formatter.py65
1 files changed, 65 insertions, 0 deletions
diff --git a/obsapi/formatter.py b/obsapi/formatter.py
new file mode 100644
index 0000000..fd5c70f
--- /dev/null
+++ b/obsapi/formatter.py
@@ -0,0 +1,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)