]> Frank Brehm's Git Trees - pixelpark/puppetmaster-webhooks.git/commitdiff
Reading cache YAML file
authorFrank Brehm <frank.brehm@pixelpark.com>
Fri, 24 Aug 2018 15:17:26 +0000 (17:17 +0200)
committerFrank Brehm <frank.brehm@pixelpark.com>
Fri, 24 Aug 2018 15:17:26 +0000 (17:17 +0200)
lib/webhooks/__init__.py
lib/webhooks/show_modules.py

index ed997e8c66182d1c9858119ad8c543db98839136..c960ac60c0717cf4203034c069946f7a47b51806 100644 (file)
@@ -1,6 +1,6 @@
 #!/bin/env python3
 # -*- coding: utf-8 -*-
 
-__version__ = '0.10.1'
+__version__ = '0.10.2'
 
 # vim: ts=4 et list
index e4a194e1c245926a3cbdfb21581f3fe18608e96a..1ed6bed21192528ae58147988895c28210e3780f 100644 (file)
@@ -17,25 +17,46 @@ import copy
 import json
 
 # Third party modules
+import six
+import yaml
 
 # Own modules
 from . import __version__
 
 from .common import pp, to_str
 
-from .base_app import BaseHookApp
+from .base_app import BaseHookError, BaseHookApp
+
+from .module_info import ModuleInfo
 
 LOG = logging.getLogger(__name__)
 
 DEFAULT_PARENT_DIR = '/etc/puppetlabs/code/fileserver'
 
 
+# =============================================================================
+class ShowModulesError(BaseHookError):
+
+    pass
+
+# =============================================================================
+class ShowModulesUncriticalError(ShowModulesError):
+
+    pass
+
 # =============================================================================
 class ShowModulesApp(BaseHookApp):
     """
     Class for the application objects.
     """
 
+    open_args = {}
+    if six.PY3:
+        open_args = {
+            'encoding': 'utf-8',
+            'errors': 'surrogateescape',
+        }
+
     # -------------------------------------------------------------------------
     def __init__(self, appname=None, verbose=0, version=__version__):
         """Constructor."""
@@ -52,18 +73,20 @@ class ShowModulesApp(BaseHookApp):
 
         self._html_title = "All Puppet modules."
 
-#    # -------------------------------------------------------------------------
-#    def as_dict(self, short=True):
-#        """
-#        Transforms the elements of the object into a dict
-#
-#        @return: structure as dict
-#        @rtype:  dict
-#        """
-#
-#        res = super(ShowModulesApp, self).as_dict()
-#
-#        return res
+    # -------------------------------------------------------------------------
+    def as_dict(self, short=True):
+        """
+        Transforms the elements of the object into a dict
+
+        @return: structure as dict
+        @rtype:  dict
+        """
+
+        res = super(ShowModulesApp, self).as_dict()
+
+        res['open_args'] = self.open_args
+
+        return res
 
     # -------------------------------------------------------------------------
     def evaluate_config(self, config, yaml_file):
@@ -82,13 +105,51 @@ class ShowModulesApp(BaseHookApp):
     def run(self):
         """Main routine."""
 
-        if self.output_type == 'txt':
-            self.print_out("Hallo!")
-        elif self.output_type == 'json':
-            data = {'msg': self.html_title}
-            self.print_out(json.dumps(data))
-        elif self.output_type == 'html':
+        if self.output_type == 'html':
             self.print_out('<h1>{t}</h1>'.format(t=self.html_title))
+        elif self.output_type == 'txt':
+            len_title = len(self.html_title)
+            self.print_out("\n{}".format(self.html_title))
+            self.print_out("#" * len_title)
+            self.print_out('')
+
+        try:
+            self.read_cache_file()
+        except ShowModulesUncriticalError as e:
+            LOG.error(str(e))
+        else:
+            if self.output_type == 'json':
+                data = {'msg': self.html_title}
+                self.print_out(json.dumps(data))
+
+    # -------------------------------------------------------------------------
+    def read_cache_file(self):
+
+        LOG.debug("Searching for {!r} ...".format(self.cache_file))
+        if not os.path.exists(self.cache_file):
+            raise ShowModulesUncriticalError(
+                "Cache file {!r} not found.".format(self.cache_file))
+
+        if not os.access(self.cache_file, os.R_OK):
+            raise ShowModulesUncriticalError(
+                "Cache file {!r} not readable.".format(self.cache_file))
+
+        data = []
+        LOG.debug("Reading {!r} ...".format(self.cache_file))
+        try:
+            with open(self.cache_file, 'r', **self.open_args) as fh:
+                for struct in yaml.load_all(fh):
+                    data.append(struct)
+        except yaml.YAMLError as e:
+            raise ShowModulesUncriticalError(
+                "Could not evaluate content of {f!r}: {e}".format(f=self.cache_file, e=e))
+        if self.verbose > 3:
+            LOG.debug("Content of {f!r}:\n{c}".format(f=self.cache_file, c=pp(data)))
+        if not data:
+            raise ShowModulesUncriticalError(
+                "Cache file {!r} has no content.".format(self.cache_file))
+
+        return data
 
 # =============================================================================