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

« back to all changes in this revision

Viewing changes to ivle/config/__init__.py

  • Committer: drtomc
  • Date: 2007-12-04 00:18:29 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:1
AnĀ initialĀ checkin.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
25
 
import glob
26
 
import inspect
27
 
 
28
 
from configobj import ConfigObj
29
 
from validate import Validator
30
 
 
31
 
__all__ = ["ConfigError", "Config"]
32
 
 
33
 
class ConfigError(Exception):
34
 
    """
35
 
    An error reading or writing the configuration file.
36
 
    """
37
 
    pass
38
 
 
39
 
def search_confdir():
40
 
    """
41
 
    Search for the config file, and return the directory it is in.
42
 
    1. Environment var IVLECONF (path to directory)
43
 
    2. /etc/ivle
44
 
    Raises a ConfigError on error.
45
 
    """
46
 
    if 'IVLECONF' in os.environ:
47
 
        fname = os.path.join(os.environ['IVLECONF'])
48
 
        if os.path.exists(fname):
49
 
            return fname
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))
60
 
 
61
 
_NO_VALUE = []
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).
66
 
 
67
 
    Automatically validates the file against the spec (found in
68
 
    ./ivle-spec.conf relative to this module).
69
 
    """
70
 
    def __init__(self, blank=False, plugins=True, *args, **kwargs):
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.
75
 
        @param plugins: If True, will find and index plugins.
76
 
        @raise ConfigError: If the config file cannot be found.
77
 
        """
78
 
        specfile = os.path.join(os.path.dirname(__file__), 'ivle-spec.conf')
79
 
        if blank:
80
 
            super(Config, self).__init__(configspec=specfile, *args, **kwargs)
81
 
        else:
82
 
            confdir = search_confdir()
83
 
            conffile = os.path.join(confdir, 'ivle.conf')
84
 
            super(Config, self).__init__(infile=conffile, configspec=specfile,
85
 
                                         *args, **kwargs)
86
 
            # XXX This doesn't raise errors if it doesn't validate
87
 
            self.validate(Validator())
88
 
 
89
 
            if not plugins:
90
 
                return
91
 
            self.plugins = {}
92
 
            self.plugin_configs = {}
93
 
            # Go through the plugin config files, looking for plugins.
94
 
            for pconfn in glob.glob(os.path.join(confdir, 'plugins.d/*.conf')):
95
 
                pconf = ConfigObj(pconfn)
96
 
                for plugin_section in pconf:
97
 
                    # We have a plugin path. Resolve it into a class...
98
 
                    plugin_path, plugin = get_plugin(plugin_section)
99
 
                    self.plugins[plugin_path] = plugin
100
 
                    # ... and add it to the registry.
101
 
                    self.plugin_configs[plugin] = pconf[plugin_section]
102
 
 
103
 
            # Create a registry mapping plugin classes to paths.
104
 
            self.reverse_plugins = dict([(v, k) for (k, v) in
105
 
                                         self.plugins.items()])
106
 
 
107
 
            # Create an index of plugins by base class.
108
 
            self.plugin_index = {}
109
 
            for plugin in self.plugins.values():
110
 
                # Getmro returns a tuple of all the super-classes of the plugin
111
 
                for base in inspect.getmro(plugin):
112
 
                    if base not in self.plugin_index:
113
 
                        self.plugin_index[base] = []
114
 
                    self.plugin_index[base].append(plugin)
115
 
 
116
 
    def set_by_path(self, path, value=_NO_VALUE, comment=None):
117
 
        """Writes a value to an option, given a '/'-separated path.
118
 
        @param path: '/'-separated path to configuration option.
119
 
        @param value: Optional - value to write to the option.
120
 
        @param comment: Optional - comment string (lines separated by '\n's).
121
 
        Note: If only a comment is being inserted, and the value does not
122
 
        exist, fails silently.
123
 
        """
124
 
        path = path.split('/')
125
 
        # Iterate over each segment of the path, and find the section in conf
126
 
        # file to insert the value into (use all but the last path segment)
127
 
        conf_section = self
128
 
        for seg in path[:-1]:
129
 
            # Create the section if it isn't there
130
 
            if seg not in conf_section:
131
 
                conf_section[seg] = {}
132
 
            conf_section = conf_section[seg]
133
 
        # The final path segment names the key to insert into
134
 
        keyname = path[-1]
135
 
        if value is not _NO_VALUE:
136
 
            conf_section[keyname] = value
137
 
        if comment is not None:
138
 
            try:
139
 
                conf_section[keyname]
140
 
            except KeyError:
141
 
                pass        # Fail silently
142
 
            else:
143
 
                conf_section.comments[keyname] = comment.split('\n')
144
 
 
145
 
    def get_by_path(self, path):
146
 
        """Gets an option's value, given a '/'-separated path.
147
 
        @param path: '/'-separated path to configuration option.
148
 
        @raise KeyError: if no config option is at that path.
149
 
        """
150
 
        # Iterate over each segment of the path, and find the value in conf file
151
 
        value = self
152
 
        for seg in path.split('/'):
153
 
            value = value[seg]      # May raise KeyError
154
 
        return value