~azzar1/unity/add-show-desktop-key

1092.1.14 by Matt Giuca
Added module ivle.config, which takes care of some work interfacing with
1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2009 The University of Melbourne
3
#
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18
# Author: Matt Giuca, Will Grant
19
20
"""
21
Provides programmatic access to the IVLE configuration file.
22
"""
23
24
import os
1092.1.59 by William Grant
Move the plugin loading/indexing logic into ivle.config.Config.
25
import glob
26
import inspect
1092.1.14 by Matt Giuca
Added module ivle.config, which takes care of some work interfacing with
27
28
from configobj import ConfigObj
1092.1.15 by Matt Giuca
Added config validation spec: ivle/config/ivle-spec.conf.
29
from validate import Validator
1092.1.14 by Matt Giuca
Added module ivle.config, which takes care of some work interfacing with
30
31
__all__ = ["ConfigError", "Config"]
32
33
class ConfigError(Exception):
34
    """
35
    An error reading or writing the configuration file.
36
    """
37
    pass
38
1092.1.59 by William Grant
Move the plugin loading/indexing logic into ivle.config.Config.
39
def search_confdir():
1092.1.14 by Matt Giuca
Added module ivle.config, which takes care of some work interfacing with
40
    """
1185 by Matt Giuca
ivle.config: Fixed docstring.
41
    Search for the config file, and return the directory it is in.
1092.1.54 by William Grant
./etc is no longer a special case in the ivle.conf search path.
42
    1. Environment var IVLECONF (path to directory)
1185 by Matt Giuca
ivle.config: Fixed docstring.
43
    2. /etc/ivle
1092.1.14 by Matt Giuca
Added module ivle.config, which takes care of some work interfacing with
44
    Raises a ConfigError on error.
45
    """
46
    if 'IVLECONF' in os.environ:
1092.1.59 by William Grant
Move the plugin loading/indexing logic into ivle.config.Config.
47
        fname = os.path.join(os.environ['IVLECONF'])
1092.1.14 by Matt Giuca
Added module ivle.config, which takes care of some work interfacing with
48
        if os.path.exists(fname):
49
            return fname
1092.1.59 by William Grant
Move the plugin loading/indexing logic into ivle.config.Config.
50
    if os.path.exists('/etc/ivle'):
51
        return '/etc/ivle'
52
    raise ConfigError("Could not find IVLE config directory")
53
54
def get_plugin(pluginstr):
55
    plugin_path, classname = pluginstr.split('#')
56
    # Load the plugin module from somewhere in the Python path
57
    # (Note that plugin_path is a fully-qualified Python module name).
58
    return (plugin_path,
59
            getattr(__import__(plugin_path, fromlist=[classname]), classname))
1092.1.14 by Matt Giuca
Added module ivle.config, which takes care of some work interfacing with
60
1092.1.39 by Matt Giuca
setup.configure: Replaced the use of an intermediate dictionary for storing
61
_NO_VALUE = []
1092.1.14 by Matt Giuca
Added module ivle.config, which takes care of some work interfacing with
62
class Config(ConfigObj):
63
    """
64
    The configuration object. Can be instantiated with no arguments (will
65
    implicitly find the ivle.conf file and load it).
1092.1.15 by Matt Giuca
Added config validation spec: ivle/config/ivle-spec.conf.
66
67
    Automatically validates the file against the spec (found in
68
    ./ivle-spec.conf relative to this module).
1092.1.14 by Matt Giuca
Added module ivle.config, which takes care of some work interfacing with
69
    """
1092.1.59 by William Grant
Move the plugin loading/indexing logic into ivle.config.Config.
70
    def __init__(self, blank=False, plugins=True, *args, **kwargs):
1092.1.35 by Matt Giuca
ivle.config.Config: __init__ now takes a 'blank' argument, which allows it to
71
        """Initialises a new Config object. Searches for the config file,
72
        loads it, and validates it.
73
        @param blank: If blank=True, will create a blank config instead, and
74
        not search for the config file.
1092.1.59 by William Grant
Move the plugin loading/indexing logic into ivle.config.Config.
75
        @param plugins: If True, will find and index plugins.
1092.1.35 by Matt Giuca
ivle.config.Config: __init__ now takes a 'blank' argument, which allows it to
76
        @raise ConfigError: If the config file cannot be found.
77
        """
1092.1.15 by Matt Giuca
Added config validation spec: ivle/config/ivle-spec.conf.
78
        specfile = os.path.join(os.path.dirname(__file__), 'ivle-spec.conf')
1092.1.35 by Matt Giuca
ivle.config.Config: __init__ now takes a 'blank' argument, which allows it to
79
        if blank:
80
            super(Config, self).__init__(configspec=specfile, *args, **kwargs)
81
        else:
1092.1.59 by William Grant
Move the plugin loading/indexing logic into ivle.config.Config.
82
            confdir = search_confdir()
83
            conffile = os.path.join(confdir, 'ivle.conf')
1092.1.35 by Matt Giuca
ivle.config.Config: __init__ now takes a 'blank' argument, which allows it to
84
            super(Config, self).__init__(infile=conffile, configspec=specfile,
1216 by William Grant
Allow template string interpolation in the config.
85
                                         interpolation='template',
1092.1.35 by Matt Giuca
ivle.config.Config: __init__ now takes a 'blank' argument, which allows it to
86
                                         *args, **kwargs)
87
            # XXX This doesn't raise errors if it doesn't validate
88
            self.validate(Validator())
1092.1.34 by Matt Giuca
setup.configure: Replaced use of legacy conf.py for loading existing values.
89
1092.1.59 by William Grant
Move the plugin loading/indexing logic into ivle.config.Config.
90
            if not plugins:
91
                return
92
            self.plugins = {}
93
            self.plugin_configs = {}
94
            # Go through the plugin config files, looking for plugins.
95
            for pconfn in glob.glob(os.path.join(confdir, 'plugins.d/*.conf')):
96
                pconf = ConfigObj(pconfn)
97
                for plugin_section in pconf:
98
                    # We have a plugin path. Resolve it into a class...
99
                    plugin_path, plugin = get_plugin(plugin_section)
100
                    self.plugins[plugin_path] = plugin
101
                    # ... and add it to the registry.
102
                    self.plugin_configs[plugin] = pconf[plugin_section]
103
104
            # Create a registry mapping plugin classes to paths.
105
            self.reverse_plugins = dict([(v, k) for (k, v) in
106
                                         self.plugins.items()])
107
108
            # Create an index of plugins by base class.
109
            self.plugin_index = {}
110
            for plugin in self.plugins.values():
111
                # Getmro returns a tuple of all the super-classes of the plugin
112
                for base in inspect.getmro(plugin):
113
                    if base not in self.plugin_index:
114
                        self.plugin_index[base] = []
115
                    self.plugin_index[base].append(plugin)
116
1092.1.39 by Matt Giuca
setup.configure: Replaced the use of an intermediate dictionary for storing
117
    def set_by_path(self, path, value=_NO_VALUE, comment=None):
1092.1.36 by Matt Giuca
ivle.config.Config: Added set_by_path method (based on code from
118
        """Writes a value to an option, given a '/'-separated path.
119
        @param path: '/'-separated path to configuration option.
1092.1.39 by Matt Giuca
setup.configure: Replaced the use of an intermediate dictionary for storing
120
        @param value: Optional - value to write to the option.
121
        @param comment: Optional - comment string (lines separated by '\n's).
1092.1.45 by Matt Giuca
setup.configure: Fixed bug if usrmgt_magic is None. Does not write comment if
122
        Note: If only a comment is being inserted, and the value does not
123
        exist, fails silently.
1092.1.36 by Matt Giuca
ivle.config.Config: Added set_by_path method (based on code from
124
        """
125
        path = path.split('/')
126
        # Iterate over each segment of the path, and find the section in conf
127
        # file to insert the value into (use all but the last path segment)
128
        conf_section = self
129
        for seg in path[:-1]:
130
            # Create the section if it isn't there
131
            if seg not in conf_section:
132
                conf_section[seg] = {}
133
            conf_section = conf_section[seg]
134
        # The final path segment names the key to insert into
135
        keyname = path[-1]
1092.1.39 by Matt Giuca
setup.configure: Replaced the use of an intermediate dictionary for storing
136
        if value is not _NO_VALUE:
137
            conf_section[keyname] = value
1092.1.36 by Matt Giuca
ivle.config.Config: Added set_by_path method (based on code from
138
        if comment is not None:
1092.1.45 by Matt Giuca
setup.configure: Fixed bug if usrmgt_magic is None. Does not write comment if
139
            try:
140
                conf_section[keyname]
141
            except KeyError:
142
                pass        # Fail silently
143
            else:
144
                conf_section.comments[keyname] = comment.split('\n')
1092.1.36 by Matt Giuca
ivle.config.Config: Added set_by_path method (based on code from
145
1092.1.34 by Matt Giuca
setup.configure: Replaced use of legacy conf.py for loading existing values.
146
    def get_by_path(self, path):
147
        """Gets an option's value, given a '/'-separated path.
148
        @param path: '/'-separated path to configuration option.
149
        @raise KeyError: if no config option is at that path.
150
        """
151
        # Iterate over each segment of the path, and find the value in conf file
152
        value = self
153
        for seg in path.split('/'):
154
            value = value[seg]      # May raise KeyError
155
        return value