migrate configuration system to the stdlib ConfigParser
[logparse.git] / logparse / formatting.py
index ab6266efc5233840d3e1369b21c03ff3aa5adec9..7b666d818d50a01a97e465fe2d602af1d54e807b 100644 (file)
@@ -15,7 +15,7 @@ from math import floor, ceil
 from tabulate import tabulate
 
 import logparse
-from . import interface, util, config, mail
+from logparse import interface, util, mail, config
 
 import logging
 logger = logging.getLogger(__name__)
@@ -36,6 +36,27 @@ JXNCHARS_SINGLE = ['├', '┤', '┬', '┴', '┼']
 BULLET = "• "
 INDENT = "  "
 
+global VARSUBST
+
+def init_var():
+    global VARSUBST
+    css_path = config.prefs.get("html", "css")
+    if config.prefs.getboolean("html", "css-relpath"):
+        if interface.argparser.parse_args().no_write:
+            css_path = os.path.relpath(css_path, ".")
+        elif interface.argparser.parse_args().destination:
+            css_path = os.path.relpath(css_path, interface.argparser.parse_args().destination())
+        elif config.prefs.get("logparse", "output"):
+            css_path = os.path.relpath(css_path, config.prefs.get("logparse", "output"))
+    VARSUBST = {
+        "title": config.prefs.get("logparse", "title"),
+        "date": interface.start.strftime(DATEFMT),
+        "time": interface.start.strftime(TIMEFMT),
+        "hostname": util.hostname(config.prefs.get("logparse", "hostname-path")),
+        "version": logparse.__version__,
+        "css": css_path
+    }
+
 
 class Output:
     """
@@ -65,6 +86,20 @@ class Output:
             f.write(self.content)
             logger.info("Written output to {}".format(destination))
 
+    def print_stdout(self, lines=False):
+        """
+        Echo the contents to the console
+        """
+        print()
+        if lines:
+            line = PlaintextLine(linewidth=config.prefs.getint("plain", "linewidth"), double=True)
+            print(line.draw())
+        print(self.content)
+        if lines:
+            print(line.draw())
+        print()
+
+
 
 class PlaintextOutput(Output):
     """
@@ -80,8 +115,7 @@ class PlaintextOutput(Output):
         """
         Print details with some primitive formatting
         """
-        init_varfilter()
-        box = PlaintextBox(content=Template("$title $version on $hostname\n\n$time $date").safe_substitute(varsubst), vpadding=2, hpadding="\t\t", linewidth=config.prefs['linewidth'])
+        box = PlaintextBox(content=Template("$title $version on $hostname\n\n$time $date").safe_substitute(VARSUBST), vpadding=2, hpadding="\t\t", linewidth=self.linewidth)
         line = PlaintextLine(self.linewidth)
         self.append(box.draw() + line.draw())
 
@@ -89,9 +123,8 @@ class PlaintextOutput(Output):
         """
         Append a horizontal line and some details
         """
-        init_varfilter()
         self.append(PlaintextLine(self.linewidth, vpadding=1).draw())
-        self.append(Template("$hostname $time $date").safe_substitute(varsubst))
+        self.append(Template("$hostname $time $date").safe_substitute(VARSUBST))
 
     def append_section(self, section):
         """
@@ -128,13 +161,13 @@ class PlaintextOutput(Output):
                 itemoutput = subtitle + '\n'
                 for datum in data:
                     datum = BULLET + datum
-                    if len(datum) > config.prefs['linewidth'] - 3:
+                    if len(datum) > self.linewidth - 3:
                         words = datum.split()
-                        if max(map(len, words)) > config.prefs['linewidth'] - len(INDENT):
+                        if max(map(len, words)) > self.linewidth - len(INDENT):
                             continue
                         res, part, others = [], words[0], words[1:]
                         for word in others:
-                            if 1 + len(word) > config.prefs['linewidth'] - len(part):
+                            if 1 + len(word) > self.linewidth - len(part):
                                 res.append(part)
                                 part = word
                             else:
@@ -156,21 +189,22 @@ class HtmlOutput(Output):
         self.content = ""
         self.destination = ""
         self.css = ""
+        self._embedded = ""
 
     def embed_css(self, css):
         """
         Convert stylesheet to inline tags
         """
-        self.content = mail.mailprep(self.content, css)
-        return self.content
+        if not self._embedded:
+            self._embedded = mail.mailprep(self.content, css)
+        return self._embedded
 
     def append_header(self, template):
         """
         Insert variables into header template file and append HTML tags
         """
-        init_varfilter()
         headercontent = Template(open(template, 'r').read())
-        self.append(headercontent.safe_substitute(varsubst))
+        self.append(headercontent.safe_substitute(VARSUBST))
         self.append(opentag('div', id='main'))
 
     def append_footer(self):
@@ -491,7 +525,7 @@ class PlaintextLine:
 
     def __init__(self, linewidth=80, double=True, vpadding=1, hpadding=""):
         self.linewidth = linewidth
-        self.double = False
+        self.double = double
         self.vpadding = vpadding
         self.hpadding = hpadding
 
@@ -576,15 +610,6 @@ class PlaintextBox:
         return ('\n').join(contentlines)
 
 
-def init_varfilter():
-    global varfilter
-    global varpattern
-    global varsubst
-    varfilter = {"$title$": config.prefs['title'], "$date$": interface.start.strftime(DATEFMT),"$time$": interface.start.strftime(TIMEFMT), "$hostname$": util.hostname(config.prefs['hostname-path']), "$version$": logparse.__version__, "$css$": os.path.relpath(config.prefs['css'], os.path.dirname(config.prefs['output']))}
-    varfilter = dict((re.escape(k), v) for k, v in varfilter.items())
-    varpattern = re.compile("|".join(varfilter.keys()))
-    varsubst = dict(title=config.prefs['title'], date=interface.start.strftime(DATEFMT), time=interface.start.strftime(TIMEFMT), hostname=util.hostname(config.prefs['hostname-path']), version=logparse.__version__, css=os.path.relpath(config.prefs['css'], os.path.dirname(config.prefs['output'])))
-
 def backticks(l):
     return ["`" + x + "`" for x in l]
 
@@ -616,11 +641,11 @@ def parsesize(num, suffix='B'):
     return "%.1f%s%s" % (num, 'Yi', suffix)
 
 
-def fsubject(template):
+def fsubject(subject):
     """
     Replace variables in the title template provided in config
     """
-    r = varpattern.sub(lambda m: varfilter[re.escape(m.group(0))], template)
+    r = Template(subject).safe_substitute(VARSUBST)
     logger.debug("Returning subject line " + r)
     return r