"Fossies" - the Fresh Open Source Software Archive

Member "sk1-2.0rc4/src/uc2/utils/config.py" (25 May 2019, 4859 Bytes) of package /linux/misc/sk1-2.0rc4.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "config.py" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.0rc3_vs_2.0rc4.

    1 # -*- coding: utf-8 -*-
    2 #
    3 #  Copyright (C) 2012 by Igor E. Novikov
    4 #
    5 #  This program is free software: you can redistribute it and/or modify
    6 #  it under the terms of the GNU General Public License as published by
    7 #  the Free Software Foundation, either version 3 of the License, or
    8 #  (at your option) any later version.
    9 #
   10 #  This program is distributed in the hope that it will be useful,
   11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
   12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   13 #  GNU General Public License for more details.
   14 #
   15 #  You should have received a copy of the GNU General Public License
   16 #  along with this program.  If not, see <https://www.gnu.org/licenses/>.
   17 
   18 import logging
   19 
   20 import xml.sax
   21 from xml.sax import handler
   22 from xml.sax.saxutils import XMLGenerator
   23 from xml.sax.xmlreader import InputSource
   24 
   25 from uc2.utils.fs import path_system, path_unicode
   26 from uc2.utils import fsutils
   27 from uc2.utils.fsutils import get_fileptr
   28 
   29 LOG = logging.getLogger(__name__)
   30 
   31 IDENT = '\t'
   32 
   33 
   34 def encode_quotes(line):
   35     result = line.replace('"', '&quot;')
   36     result = result.replace("'", "&#039;")
   37     return result
   38 
   39 
   40 def decode_quotes(line):
   41     result = line.replace('&quot;', '"')
   42     result = result.replace("&#039;", "'")
   43     return result
   44 
   45 
   46 def escape_quote(line):
   47     ret = line.replace("\\", "\\\\")
   48     return ret.replace("'", "\\'")
   49 
   50 
   51 class XmlConfigParser(object):
   52     """
   53     Represents parent class for application config.
   54     """
   55     filename = ''
   56 
   57     def update(self, cnf=None):
   58         cnf = cnf or {}
   59         if cnf:
   60             for key in cnf.keys():
   61                 if hasattr(self, key):
   62                     setattr(self, key, cnf[key])
   63 
   64     def load(self, filename=None):
   65         self.filename = filename
   66         if fsutils.lexists(filename):
   67             content_handler = XMLPrefReader(pref=self)
   68             error_handler = ErrorHandler()
   69             entity_resolver = EntityResolver()
   70             dtd_handler = DTDHandler()
   71             try:
   72                 input_file = get_fileptr(filename)
   73                 input_source = InputSource()
   74                 input_source.setByteStream(input_file)
   75                 xml_reader = xml.sax.make_parser()
   76                 xml_reader.setContentHandler(content_handler)
   77                 xml_reader.setErrorHandler(error_handler)
   78                 xml_reader.setEntityResolver(entity_resolver)
   79                 xml_reader.setDTDHandler(dtd_handler)
   80                 xml_reader.parse(input_source)
   81                 input_file.close()
   82             except Exception as e:
   83                 LOG.error('Cannot read preferences from %s %s', filename, e)
   84 
   85     def save(self, filename=None):
   86         if self.filename and filename is None:
   87             filename = self.filename
   88         if len(self.__dict__) == 0 or filename is None:
   89             return
   90 
   91         try:
   92             fileobj = get_fileptr(filename, True)
   93         except Exception as e:
   94             LOG.error('Cannot write preferences into %s %s', filename, e)
   95             return
   96 
   97         writer = XMLGenerator(out=fileobj, encoding=self.system_encoding)
   98         writer.startDocument()
   99         defaults = XmlConfigParser.__dict__
  100         items = self.__dict__.items()
  101         items.sort()
  102         writer.startElement('preferences', {})
  103         writer.characters('\n')
  104         for key, value in items:
  105             if key in defaults and defaults[key] == value:
  106                 continue
  107             if key in ['filename', 'app']:
  108                 continue
  109             writer.characters('\t')
  110             writer.startElement('%s' % key, {})
  111 
  112             str_value = path_unicode(value.__str__())
  113             if isinstance(value, str):
  114                 str_value = "'%s'" % (escape_quote(str_value))
  115 
  116             writer.characters(str_value)
  117 
  118             writer.endElement('%s' % key)
  119             writer.characters('\n')
  120         writer.endElement('preferences')
  121         writer.endDocument()
  122         fileobj.close()
  123 
  124 
  125 class XMLPrefReader(handler.ContentHandler):
  126     """Handler for xml file reading"""
  127 
  128     def __init__(self, pref=None):
  129         handler.ContentHandler.__init__(self)
  130         self.key = None
  131         self.value = None
  132         self.pref = pref
  133 
  134     def startElement(self, name, attrs):
  135         self.key = name
  136 
  137     def endElement(self, name):
  138         if name != 'preferences':
  139             try:
  140                 line = path_system('self.value=' + self.value)
  141                 code = compile(line, '<string>', 'exec')
  142                 exec code
  143                 self.pref.__dict__[self.key] = self.value
  144             except Exception as e:
  145                 LOG.error('Error in "%s" %s', line, e)
  146 
  147     def characters(self, data):
  148         self.value = data
  149 
  150 
  151 class ErrorHandler(handler.ErrorHandler):
  152     pass
  153 
  154 
  155 class EntityResolver(handler.EntityResolver):
  156     pass
  157 
  158 
  159 class DTDHandler(handler.DTDHandler):
  160     pass