commit-gnue
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[gnue] r9815 - trunk/gnue-common/src/apps


From: johannes
Subject: [gnue] r9815 - trunk/gnue-common/src/apps
Date: Fri, 16 Nov 2007 03:43:52 -0600 (CST)

Author: johannes
Date: 2007-11-16 03:43:52 -0600 (Fri, 16 Nov 2007)
New Revision: 9815

Modified:
   trunk/gnue-common/src/apps/GBaseApp.py
   trunk/gnue-common/src/apps/GConfig.py
Log:
More work on PEP8 and code cleanup


Modified: trunk/gnue-common/src/apps/GBaseApp.py
===================================================================
--- trunk/gnue-common/src/apps/GBaseApp.py      2007-11-16 07:55:33 UTC (rev 
9814)
+++ trunk/gnue-common/src/apps/GBaseApp.py      2007-11-16 09:43:52 UTC (rev 
9815)
@@ -346,8 +346,7 @@
         if application:
             try:
                 self.configurationManager = GConfig.GConfig(application,
-                                 self.configDefaults,
-                                 configFilename=self.CONFIGFILE)
+                        self.configDefaults, self.CONFIGFILE)
 
             except ConfigParser.NoSectionError, msg:
                 raise errors.AdminError, \
@@ -759,7 +758,7 @@
         """
 
         self.printHelpHeader()
-        print o(GConfig.printableConfigOptions(self.configDefaults))
+        print o(GConfig.printable_config_options(self.configDefaults))
 
         sys.exit()
 

Modified: trunk/gnue-common/src/apps/GConfig.py
===================================================================
--- trunk/gnue-common/src/apps/GConfig.py       2007-11-16 07:55:33 UTC (rev 
9814)
+++ trunk/gnue-common/src/apps/GConfig.py       2007-11-16 09:43:52 UTC (rev 
9815)
@@ -24,19 +24,19 @@
 Class that loads the configuration files so gnue apps can get default settings.
 """
 
-from ConfigParser import *
 import os
-import string
 import sys
 import textwrap
+import ConfigParser
 
 from gnue import paths
-from gnue.common.apps import i18n, errors, GDebug
-from gnue.common.utils.FileUtils import openResource
+from gnue.common.base import i18n, errors
 from gnue.common import GCConfig
-import copy
 
 
+__all__ = ['InvalidFormatError', 'GConfig', 'GConfigAlias',
+           'getInstalledBase', 'printable_config_options']
+
 # =============================================================================
 # Configuration file cannot be parsed
 # =============================================================================
@@ -47,17 +47,21 @@
 
 
 # =============================================================================
-# Class handling GNUe Configuration
+# Configuration manager
 # =============================================================================
 
 class GConfig:
+    """
+    Configuration manager for GNU Enterprise Applications
+    """
 
     def __init__(self, section, defaults=None, configFilename="gnue.conf",
             homeConfigDir=".gnue"):
 
-        self._defaultConfigFilename = configFilename
-        self._defaultSection = section
+        self._default_config_filename = configFilename
+        self._default_section = section
         self._loadedConfigs = {}
+
         self.loadApplicationConfig(configFilename, homeConfigDir, section,
                 defaults)
 
@@ -66,8 +70,24 @@
         __builtin__.__dict__['gConfig'] = self.gConfig
         __builtin__.__dict__['gConfigDict'] =  self.gConfigDict
 
+
+    # -------------------------------------------------------------------------
+    # Register an alias
+    # -------------------------------------------------------------------------
+
     def registerAlias(self, name, section):
+        """
+        Register an alias for retrieving options of a given section in the
+        configration file.
+        @param name: function name to use as a 'builtin' for retrieving options
+            of the given section
+        @type name: string
+        @param section: the section of which option values should be read
+        @type section: string
+        """
+
         alias = GConfigAlias(self.gConfig, section)
+
         import __builtin__
         __builtin__.__dict__[name] = alias.gConfig
 
@@ -123,10 +143,10 @@
                 assert gDebug(2, \
                         'Configuration files were read in this order:  %s' % \
                                  fileLocations)
-            except DuplicateSectionError:
+            except ConfigParser.DuplicateSectionError:
                 raise InvalidFormatError, \
                     u_('Configuration file has duplicate sections.')
-            except MissingSectionHeaderError:
+            except ConfigParser.MissingSectionHeaderError:
                 raise InvalidFormatError, \
                     u_('Configuration file has no sections.')
             except:
@@ -159,42 +179,42 @@
     def _integrateDefaultDict(self,filename, section,defaults):
         try:
             self._loadedConfigs[filename].add_section(section)
-        except DuplicateSectionError:
+        except ConfigParser.DuplicateSectionError:
             pass
         for key in defaults.keys():
             # Only set the value to the default if config file didn't contain
             # custom setting.
             try:
                 self._loadedConfigs[filename].get(section,key)
-            except NoOptionError:
+            except ConfigParser.NoOptionError:
                 self._loadedConfigs[filename].set(section,key,defaults[key])
 
 
-    def gConfig(self, varName, configFilename=None, section=None):
-        if not configFilename: configFilename = self._defaultConfigFilename
-        if not section: section = self._defaultSection
+    def gConfig(self, var_name, configFilename=None, section=None):
+        if not configFilename: configFilename = self._default_config_filename
+        if not section: section = self._default_section
         try:
-            return self._loadedConfigs[configFilename].get(section,varName)
-        except NoSectionError:
+            return self._loadedConfigs[configFilename].get(section,var_name)
+        except ConfigParser.NoSectionError:
             self._loadedConfigs[configFilename].add_section(section)
-            return self._loadedConfigs[configFilename].get(section,varName)
-        except NoOptionError:
+            return self._loadedConfigs[configFilename].get(section,var_name)
+        except ConfigParser.NoOptionError:
             section = 'common'
             try:
-                return self._loadedConfigs[configFilename].get(section,varName)
-            except NoSectionError:
+                return 
self._loadedConfigs[configFilename].get(section,var_name)
+            except ConfigParser.NoSectionError:
                 self._loadedConfigs[configFilename].add_section(section)
-                return self._loadedConfigs[configFilename].get(section,varName)
+                return 
self._loadedConfigs[configFilename].get(section,var_name)
 
     def gConfigDict(self, configFilename=None, section=None):
-        if not configFilename: configFilename = self._defaultConfigFilename
-        if not section:      section = self._defaultSection
+        if not configFilename: configFilename = self._default_config_filename
+        if not section:      section = self._default_section
 
         c = self._loadedConfigs[configFilename]
         if c.has_section(section):
             options = {}
             for option in c.options(section):
-                options[option] = c.get(section,string.lower(option))
+                options[option] = c.get(section, option.lower())
             return options
         else:
             return {}
@@ -203,96 +223,196 @@
         defaults = {}
         if defaultDefinitions:
             for definition in defaultDefinitions:
-                defaults[string.lower(definition['Name'])] = \
+                defaults[definition['Name'].lower()] = \
                         str(definition['Default'])
         return defaults
 
 
-class GConfigParser(ConfigParser):
+# =============================================================================
+# GNUe Config Parser class supporting the GTypecast system
+# =============================================================================
+
+class GConfigParser(ConfigParser.ConfigParser):
     """
     Add support for our GTypecast systems to the generic ConfigParser
     """
+
+    # -------------------------------------------------------------------------
+    # Constructor
+    # -------------------------------------------------------------------------
+
     def __init__(self, defaults):
+        """
+        @param defaults: list or tuple of dictionaries describing all available
+            configuration options.
+        """
+
         self.__defaults = defaults
-        ConfigParser.__init__(self)
+        ConfigParser.ConfigParser.__init__(self)
         typecasts = self.__typecasts = {}
-        # FIXME: I don't know what kind of elements are stored in 'defaults'.
-        #        add a correct iteration over the "defaults-dictionary"!
-        if defaults and (len(defaults) > 0):
-            for f in defaults:
-                try:
-                    typecasts[f['Name'].lower()] = f['Typecast']
-                except KeyError:
-                    typecasts[f['Name'].lower()] = str
 
-    def get(self, section, field):
+        for item in defaults:
+            iname = item['Name'].lower()
+            typecasts[iname] = item.get('Typecast', str)
+
+
+    # -------------------------------------------------------------------------
+    # Get an options value
+    # -------------------------------------------------------------------------
+
+    def get(self, section, field, raw=False, defs=None):
+        """
+        Get an option value for the named section, and apply any given
+        typecasts.
+
+        @param section: the section in which to look for the option
+        @param field: name of the option
+        @param raw: if True, do not expand % interpolations
+        @param defs: dictionary whose contents override any pre-existing
+            defaults
+
+        @returns: value of the option
+
+        @raises ValueError: the option value is of wrong type
+        """
         try:
-            val = ConfigParser.get(self, section, field)
+            val = ConfigParser.ConfigParser.get(self, section, field, raw, 
defs)
             return self.__typecasts[field.lower()](val)
+
         except KeyError:
             return val
+
         except ValueError:
-            raise ValueError, u_("Config option %(field)s is of wrong type in "
-                                 "[%(section)s]") \
-                              % {'field': field, 'section': section}
+            raise ValueError, \
+               u_("Config option %(field)s is of wrong type in [%(section)s]")\
+               % {'field': field, 'section': section}
 
 
+# =============================================================================
+# Class for retrieving option values from a configuration file's section
+# =============================================================================
+
 class GConfigAlias:
+    """
+    This class provides access to the configuration options of a given section
+    in a configuration file
+    """
+
+    # -------------------------------------------------------------------------
+    # Constructor
+    # -------------------------------------------------------------------------
+
     def __init__(self, gconfig, name):
+        """
+        @param gconfig: gConfig() method of the configuration manager instance
+            to be used for retrieval
+        @type gconfig: function
+        @param name: the default section to retrieve values from
+        @type name: string
+        """
+
         self._gConfig = gconfig
         self._section = name
 
-    def gConfig(self, varName, configFilename=None, section=None):
+
+    # -------------------------------------------------------------------------
+    # Retrieve an option value
+    # -------------------------------------------------------------------------
+
+    def gConfig(self, var_name, configFilename=None, section=None):
+        """
+        Retrieve an option from a section in a configuration file
+
+        @param var_name: name of the option to retrieve
+        @type var_name: string
+
+        @param configFilename: name of the configuration file to retrieve the
+            option from.  If None, the default configuration file will be used.
+        @type configFilename: string
+
+        @param section: name of the section to retrieve the option from.  If
+            None, the default section will be used.
+
+        @returns: the retrieve option value
+        """
+
         if not section:
             section = self._section
-        return self._gConfig(varName, configFilename=configFilename,
+
+        return self._gConfig(var_name, configFilename=configFilename,
                 section=section)
 
 
+# -----------------------------------------------------------------------------
+# get the install location of a given group
+# -----------------------------------------------------------------------------
+
 def getInstalledBase(*parameters):
+    """
+    Returns the first matching item of the arguments in the _site_config
+    dictionary.
+    """
     for param in parameters:
-        try:
+        if param in _site_config:
             return _site_config[param]
-        except KeyError:
-            pass
 
     return None
 
-def printableConfigOptions(options, outputWidth=60):
+
+# -----------------------------------------------------------------------------
+# Create a printable description of configuration options
+# -----------------------------------------------------------------------------
+
+def printable_config_options(options, output_width=60):
+    """
+    Create a human readable description of the given set of configuration
+    options.
+
+    @param options: list of dictionaries with at least 'Name', 'Default' and
+        'Description' keys
+    @param output_width: maximum length of a single text line
+
+    @returns: the human readable description of all options
+    @rtype: unicode
+    """
     output = "Valid config file options.....\n"
+
     if options:
         for option in options:
-            output += '='*outputWidth+"\n"
+            output += '=' * output_width + "\n"
             nameString = "Name:%s" % option['Name']
             defaultString = "Default Value:%s" % option['Default']
             output += "%s%s%s\n" % \
                     (nameString, ' ' * \
-                    (outputWidth - len(nameString + defaultString)),
+                    (output_width - len(nameString + defaultString)),
                     defaultString)
+                    
             # FIXME: This allows for non-unicode descriptions. Remove at some
             # point.
             description = option['Description']
             if isinstance(description, str):
-                description = unicode(description, i18n.getencoding())
-            output += "%s\n" % textwrap.fill(description, outputWidth)
+                description = unicode(description, i18n.get_encoding())
+
+            output += "%s\n" % textwrap.fill(description, output_width)
     else:
         output += "No options defined"
+
     return output
 
-############################
-#
-# Site configuration stuff
-#
-############################
 
+# =============================================================================
+# Site configuration
+# =============================================================================
+
+
 _site_config = {}
 
 # highest priority: site_config.cfg (depreciated -- will be removed)
 
 if os.environ.has_key('GNUE_INSTALLED_SITE_CFG'):
-    input = open(os.environ['GNUE_INSTALLED_SITE_CFG'],'r')
-    text = input.read()
-    input.close()
+    fhd = open(os.environ['GNUE_INSTALLED_SITE_CFG'], 'r')
+    text = fhd.read()
+    fhd.close()
 
     # This evaluates the text file as a python script (hope you secured it)
     # The resulting namespace is stored as a dict in _site_config.
@@ -306,16 +426,17 @@
     install_prefix = os.environ['INSTALL_PREFIX']
     _site_config = {
         'install_prefix': install_prefix,
-        'common_etc': os.path.join(install_prefix,'etc'),
-        'common_images': os.path.join(install_prefix,'shared','images'),
+        'common_etc': os.path.join(install_prefix, 'etc'),
+        'common_images': os.path.join(install_prefix, 'shared', 'images'),
         'common_appbase': install_prefix,
-        'common_shared': os.path.join(install_prefix,'shared')
+        'common_shared': os.path.join(install_prefix, 'shared')
     }
 
 else:
     _site_config = {
-      "install_prefix": paths.data,
-      "common_etc": paths.config,
-      "common_images": os.path.join(paths.data, "share", "gnue", "images"),
-      "common_appbase": paths.data,
-      "common_shared": os.path.join(paths.data, "share", "gnue")}
+        "install_prefix": paths.data,
+        "common_etc": paths.config,
+        "common_images": os.path.join(paths.data, "share", "gnue", "images"),
+        "common_appbase": paths.data,
+        "common_shared": os.path.join(paths.data, "share", "gnue")
+    }





reply via email to

[Prev in Thread] Current Thread [Next in Thread]