~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/registry.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Classes to provide name-to-object registry-like support."""
18
18
 
19
 
from __future__ import absolute_import
20
 
 
21
 
from bzrlib.pyutils import get_named_object
22
 
 
23
19
 
24
20
class _ObjectGetter(object):
25
21
    """Maintain a reference to an object, and return the object on request.
36
32
    def __init__(self, obj):
37
33
        self._obj = obj
38
34
 
39
 
    def get_module(self):
40
 
        """Get the module the object was loaded from."""
41
 
        return self._obj.__module__
42
 
 
43
35
    def get_obj(self):
44
36
        """Get the object that was saved at creation time"""
45
37
        return self._obj
59
51
        self._imported = False
60
52
        super(_LazyObjectGetter, self).__init__(None)
61
53
 
62
 
    def get_module(self):
63
 
        """Get the module the referenced object will be loaded from.
64
 
        """
65
 
        return self._module_name
66
 
 
67
54
    def get_obj(self):
68
55
        """Get the referenced object.
69
56
 
71
58
        return the imported object.
72
59
        """
73
60
        if not self._imported:
74
 
            self._obj = get_named_object(self._module_name, self._member_name)
75
 
            self._imported = True
 
61
            self._do_import()
76
62
        return super(_LazyObjectGetter, self).get_obj()
77
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
 
78
72
    def __repr__(self):
79
 
        return "<%s.%s object at %x, module=%r attribute=%r imported=%r>" % (
 
73
        return "<%s.%s object at %x, module=%r attribute=%r>" % (
80
74
            self.__class__.__module__, self.__class__.__name__, id(self),
81
 
            self._module_name, self._member_name, self._imported)
 
75
            self._module_name, self._member_name)
82
76
 
83
77
 
84
78
class Registry(object):
113
107
        :param obj: The object to register.
114
108
        :param help: Help text for this entry. This may be a string or
115
109
                a callable. If it is a callable, it should take two
116
 
                parameters (registry, key): this registry and the key that
 
110
                parameters (registry, key): this registry and the key that 
117
111
                the help was registered under.
118
112
        :param info: More information for this entry. Registry.get_info()
119
113
                can be used to get this information. Registry treats this as an
133
127
                      override_existing=False):
134
128
        """Register a new object to be loaded on request.
135
129
 
136
 
        :param key: This is the key to use to request the object later.
137
130
        :param module_name: The python path to the module. Such as 'os.path'.
138
 
        :param member_name: The member of the module to return.  If empty or
 
131
        :param member_name: The member of the module to return.  If empty or 
139
132
                None, get() will return the module itself.
140
133
        :param help: Help text for this entry. This may be a string or
141
134
                a callable.
142
 
        :param info: More information for this entry. Registry.get_info()
143
 
                can be used to get this information. Registry treats this as an
144
 
                opaque storage location (it is defined by the caller).
 
135
        :param info: More information for this entry. Registry 
145
136
        :param override_existing: If True, replace the existing object
146
137
                with the new one. If False, if there is already something
147
138
                registered with the same key, raise a KeyError
161
152
        """Return the object register()'ed to the given key.
162
153
 
163
154
        May raise ImportError if the object was registered lazily and
164
 
        there are any problems, or AttributeError if the module does not
 
155
        there are any problems, or AttributeError if the module does not 
165
156
        have the supplied member.
166
157
 
167
158
        :param key: The key to obtain the object for. If no object has been
176
167
        """
177
168
        return self._dict[self._get_key_or_default(key)].get_obj()
178
169
 
179
 
    def _get_module(self, key):
180
 
        """Return the module the object will be or was loaded from.
181
 
 
182
 
        :param key: The key to obtain the module for.
183
 
        :return: The name of the module
184
 
        """
185
 
        return self._dict[key].get_module()
186
 
 
187
170
    def get_prefix(self, fullname):
188
171
        """Return an object whose key is a prefix of the supplied value.
189
172
 
191
174
        :return: a tuple of (object, remainder), where the remainder is the
192
175
            portion of the name that did not match the key.
193
176
        """
194
 
        for key in self.keys():
 
177
        for key, value in self.iteritems():
195
178
            if fullname.startswith(key):
196
 
                return self.get(key), fullname[len(key):]
 
179
                return value, fullname[len(key):]
197
180
 
198
181
    def _get_key_or_default(self, key=None):
199
182
        """Return either 'key' or the default key if key is None"""
233
216
        for key, getter in self._dict.iteritems():
234
217
            yield key, getter.get_obj()
235
218
 
236
 
    def items(self):
237
 
        # We should not use the iteritems() implementation below (see bug
238
 
        # #430510)
239
 
        return sorted([(key, getter.get_obj())
240
 
                       for key, getter in self._dict.items()])
241
 
 
242
219
    def _set_default_key(self, key):
243
220
        if not self._dict.has_key(key):
244
221
            raise KeyError('No object registered under key %s.' % key)
251
228
    default_key = property(_get_default_key, _set_default_key,
252
229
                            doc="Current value of the default key."
253
230
                                " Can be set to any existing key.")
254
 
 
255
 
 
256
 
class FormatRegistry(Registry):
257
 
    """Registry specialised for handling formats."""
258
 
 
259
 
    def __init__(self, other_registry=None):
260
 
        Registry.__init__(self)
261
 
        self._other_registry = other_registry
262
 
 
263
 
    def register(self, key, obj, help=None, info=None,
264
 
                 override_existing=False):
265
 
        Registry.register(self, key, obj, help=help, info=info,
266
 
            override_existing=override_existing)
267
 
        if self._other_registry is not None:
268
 
            self._other_registry.register(key, obj, help=help,
269
 
                info=info, override_existing=override_existing)
270
 
 
271
 
    def register_lazy(self, key, module_name, member_name,
272
 
                      help=None, info=None,
273
 
                      override_existing=False):
274
 
        # Overridden to allow capturing registrations to two seperate
275
 
        # registries in a single call.
276
 
        Registry.register_lazy(self, key, module_name, member_name,
277
 
                help=help, info=info, override_existing=override_existing)
278
 
        if self._other_registry is not None:
279
 
            self._other_registry.register_lazy(key, module_name, member_name,
280
 
                help=help, info=info, override_existing=override_existing)
281
 
 
282
 
    def remove(self, key):
283
 
        Registry.remove(self, key)
284
 
        if self._other_registry is not None:
285
 
            self._other_registry.remove(key)
286
 
 
287
 
    def get(self, format_string):
288
 
        r = Registry.get(self, format_string)
289
 
        if callable(r):
290
 
            r = r()
291
 
        return r