1# _________________________________________________________________________ 2# 3# PyUtilib: A Python utility library. 4# Copyright (c) 2008 Sandia Corporation. 5# This software is distributed under the BSD License. 6# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, 7# the U.S. Government retains certain rights in this software. 8# _________________________________________________________________________ 9"""A plugin that supports configuration of environment options.""" 10 11import os.path 12import os 13import re 14import logging 15 16from pyutilib.component.core import Interface, IPluginLoadPath, Plugin, implements 17from pyutilib.component.config.options import DictOption, declare_option 18 19logger = logging.getLogger('pyutilib.component.core.pca') 20 21 22class IEnvironmentConfig(Interface): 23 """Interface for environment configuration.""" 24 25 def get_option(self, option): 26 """Return the value of the specified option.""" 27 28 def matches(self, namespace): 29 """ 30 Returns a tuple (flag,count). The flag is true if this 31 environment is a parent of the specified namespace. If the flag is 32 true, then the count is the number of levels in the namespace. 33 """ 34 35 36class EnvironmentConfig(Plugin): 37 """A plugin that supports configuration of environment options.""" 38 39 implements(IEnvironmentConfig) 40 implements(IPluginLoadPath) 41 42 def __init__(self, namespace): 43 self.namespace = namespace 44 self.p = re.compile(namespace) 45 declare_option("options", cls=DictOption, section=namespace) 46 47 def get_option(self, option): 48 try: 49 return getattr(self.options, option) 50 except AttributeError: 51 return None 52 53 def matches(self, namespace): 54 if self.p.match(namespace) is None: 55 return (False, 0) 56 return (True, namespace.count('.') + 1) 57 58 def get_load_path(self): 59 ans = [] 60 # 61 # Look for load_path in the environment 62 # 63 try: 64 ans.append( 65 os.path.normcase(os.path.realpath(self.options.load_path))) 66 except OptionError: 67 pass 68 except AttributeError: 69 pass 70 # 71 # Look for the $HOME/.$name/plugin directory 72 # 73 if "HOME" in os.environ: 74 dir = os.path.normcase( 75 os.path.realpath( 76 os.path.join(os.environ["HOME"], "." + self.namespace, 77 "plugins"))) 78 if os.path.exists(dir): 79 ans.append(dir) 80 # 81 # Look for the $PLUGINPATH environment 82 # 83 if "PLUGINPATH" in os.environ: 84 tmp = os.environ["PLUGINPATH"] 85 if ';' in tmp: 86 ans += tmp.split(';') 87 elif ':' in tmp: 88 ans += tmp.split(':') 89 else: 90 ans += re.split('[ \t]+', tmp) 91 if __debug__ and logger.isEnabledFor(logging.DEBUG): 92 logger.debug("Created load path: %s" % ans) 93 return ans 94