~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/registry.py

  • Committer: Aaron Bentley
  • Date: 2008-10-16 21:27:10 UTC
  • mfrom: (0.15.26 unshelve)
  • mto: (0.16.74 shelf-ui)
  • mto: This revision was merged to the branch mainline in revision 3820.
  • Revision ID: aaron@aaronbentley.com-20081016212710-h9av3nhk76dvmsv5
Merge with unshelve

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""Classes to provide name-to-object registry-like support."""
 
18
 
 
19
 
 
20
class _ObjectGetter(object):
 
21
    """Maintain a reference to an object, and return the object on request.
 
22
 
 
23
    This is used by Registry to make plain objects function similarly
 
24
    to lazily imported objects.
 
25
 
 
26
    Objects can be any sort of python object (class, function, module,
 
27
    instance, etc)
 
28
    """
 
29
 
 
30
    __slots__ = ['_obj']
 
31
 
 
32
    def __init__(self, obj):
 
33
        self._obj = obj
 
34
 
 
35
    def get_obj(self):
 
36
        """Get the object that was saved at creation time"""
 
37
        return self._obj
 
38
 
 
39
 
 
40
class _LazyObjectGetter(_ObjectGetter):
 
41
    """Keep a record of a possible object.
 
42
 
 
43
    When requested, load and return it.
 
44
    """
 
45
 
 
46
    __slots__ = ['_module_name', '_member_name', '_imported']
 
47
 
 
48
    def __init__(self, module_name, member_name):
 
49
        self._module_name = module_name
 
50
        self._member_name = member_name
 
51
        self._imported = False
 
52
        super(_LazyObjectGetter, self).__init__(None)
 
53
 
 
54
    def get_obj(self):
 
55
        """Get the referenced object.
 
56
 
 
57
        Upon first request, the object will be imported. Future requests will
 
58
        return the imported object.
 
59
        """
 
60
        if not self._imported:
 
61
            self._do_import()
 
62
        return super(_LazyObjectGetter, self).get_obj()
 
63
 
 
64
    def _do_import(self):
 
65
        obj = __import__(self._module_name, globals(), locals(),
 
66
                         [self._member_name])
 
67
        if self._member_name:
 
68
            obj = getattr(obj, self._member_name)
 
69
        self._obj = obj
 
70
        self._imported = True
 
71
 
 
72
    def __repr__(self):
 
73
        return "<%s.%s object at %x, module=%r attribute=%r>" % (
 
74
            self.__class__.__module__, self.__class__.__name__, id(self),
 
75
            self._module_name, self._member_name)
 
76
 
 
77
 
 
78
class Registry(object):
 
79
    """A class that registers objects to a name.
 
80
 
 
81
    There are many places that want to collect related objects and access them
 
82
    by a key. This class is designed to allow registering the mapping from key
 
83
    to object. It goes one step further, and allows registering a name to a
 
84
    hypothetical object which has not been imported yet. It also supports
 
85
    adding additional information at registration time so that decisions can be
 
86
    made without having to import the object (which may be expensive).
 
87
 
 
88
    The functions 'get', 'get_info', and 'get_help' also support a
 
89
    'default_key' (settable through my_registry.default_key = XXX, XXX must
 
90
    already be registered.) Calling my_registry.get() or my_registry.get(None),
 
91
    will return the entry for the default key.
 
92
    """
 
93
 
 
94
    def __init__(self):
 
95
        """Create a new Registry."""
 
96
        self._default_key = None
 
97
        # Map from key => (is_lazy, info)
 
98
        self._dict = {}
 
99
        self._help_dict = {}
 
100
        self._info_dict = {}
 
101
 
 
102
    def register(self, key, obj, help=None, info=None,
 
103
                 override_existing=False):
 
104
        """Register a new object to a name.
 
105
 
 
106
        :param key: This is the key to use to request the object later.
 
107
        :param obj: The object to register.
 
108
        :param help: Help text for this entry. This may be a string or
 
109
                a callable. If it is a callable, it should take two
 
110
                parameters (registry, key): this registry and the key that 
 
111
                the help was registered under.
 
112
        :param info: More information for this entry. Registry.get_info()
 
113
                can be used to get this information. Registry treats this as an
 
114
                opaque storage location (it is defined by the caller).
 
115
        :param override_existing: Raise KeyErorr if False and something has
 
116
                already been registered for that key. If True, ignore if there
 
117
                is an existing key (always register the new value).
 
118
        """
 
119
        if not override_existing:
 
120
            if key in self._dict:
 
121
                raise KeyError('Key %r already registered' % key)
 
122
        self._dict[key] = _ObjectGetter(obj)
 
123
        self._add_help_and_info(key, help=help, info=info)
 
124
 
 
125
    def register_lazy(self, key, module_name, member_name,
 
126
                      help=None, info=None,
 
127
                      override_existing=False):
 
128
        """Register a new object to be loaded on request.
 
129
 
 
130
        :param module_name: The python path to the module. Such as 'os.path'.
 
131
        :param member_name: The member of the module to return.  If empty or 
 
132
                None, get() will return the module itself.
 
133
        :param help: Help text for this entry. This may be a string or
 
134
                a callable.
 
135
        :param info: More information for this entry. Registry 
 
136
        :param override_existing: If True, replace the existing object
 
137
                with the new one. If False, if there is already something
 
138
                registered with the same key, raise a KeyError
 
139
        """
 
140
        if not override_existing:
 
141
            if key in self._dict:
 
142
                raise KeyError('Key %r already registered' % key)
 
143
        self._dict[key] = _LazyObjectGetter(module_name, member_name)
 
144
        self._add_help_and_info(key, help=help, info=info)
 
145
 
 
146
    def _add_help_and_info(self, key, help=None, info=None):
 
147
        """Add the help and information about this key"""
 
148
        self._help_dict[key] = help
 
149
        self._info_dict[key] = info
 
150
 
 
151
    def get(self, key=None):
 
152
        """Return the object register()'ed to the given key.
 
153
 
 
154
        May raise ImportError if the object was registered lazily and
 
155
        there are any problems, or AttributeError if the module does not 
 
156
        have the supplied member.
 
157
 
 
158
        :param key: The key to obtain the object for. If no object has been
 
159
            registered to that key, the object registered for self.default_key
 
160
            will be returned instead, if it exists. Otherwise KeyError will be
 
161
            raised.
 
162
        :return: The previously registered object.
 
163
        :raises ImportError: If the object was registered lazily, and there are
 
164
            problems during import.
 
165
        :raises AttributeError: If registered lazily, and the module does not
 
166
            contain the registered member.
 
167
        """
 
168
        return self._dict[self._get_key_or_default(key)].get_obj()
 
169
 
 
170
    def get_prefix(self, fullname):
 
171
        """Return an object whose key is a prefix of the supplied value.
 
172
 
 
173
        :fullname: The name to find a prefix for
 
174
        :return: a tuple of (object, remainder), where the remainder is the
 
175
            portion of the name that did not match the key.
 
176
        """
 
177
        for key, value in self.iteritems():
 
178
            if fullname.startswith(key):
 
179
                return value, fullname[len(key):]
 
180
 
 
181
    def _get_key_or_default(self, key=None):
 
182
        """Return either 'key' or the default key if key is None"""
 
183
        if key is not None:
 
184
            return key
 
185
        if self.default_key is None:
 
186
            raise KeyError('Key is None, and no default key is set')
 
187
        else:
 
188
            return self.default_key
 
189
 
 
190
    def get_help(self, key=None):
 
191
        """Get the help text associated with the given key"""
 
192
        the_help = self._help_dict[self._get_key_or_default(key)]
 
193
        if callable(the_help):
 
194
            return the_help(self, key)
 
195
        return the_help
 
196
 
 
197
    def get_info(self, key=None):
 
198
        """Get the extra information associated with the given key"""
 
199
        return self._info_dict[self._get_key_or_default(key)]
 
200
 
 
201
    def remove(self, key):
 
202
        """Remove a registered entry.
 
203
 
 
204
        This is mostly for the test suite, but it can be used by others
 
205
        """
 
206
        del self._dict[key]
 
207
 
 
208
    def __contains__(self, key):
 
209
        return key in self._dict
 
210
 
 
211
    def keys(self):
 
212
        """Get a list of registered entries"""
 
213
        return sorted(self._dict.keys())
 
214
 
 
215
    def iteritems(self):
 
216
        for key, getter in self._dict.iteritems():
 
217
            yield key, getter.get_obj()
 
218
 
 
219
    def _set_default_key(self, key):
 
220
        if not self._dict.has_key(key):
 
221
            raise KeyError('No object registered under key %s.' % key)
 
222
        else:
 
223
            self._default_key = key
 
224
 
 
225
    def _get_default_key(self):
 
226
        return self._default_key
 
227
 
 
228
    default_key = property(_get_default_key, _set_default_key,
 
229
                            doc="Current value of the default key."
 
230
                                " Can be set to any existing key.")