/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/registry.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-18 15:28:38 UTC
  • mto: This revision was merged to the branch mainline in revision 6386.
  • Revision ID: jelmer@samba.org-20111218152838-5wxpfnugk2jd625k
UseĀ absolute_import.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2010 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
from __future__ import absolute_import
 
18
 
 
19
"""Classes to provide name-to-object registry-like support."""
 
20
 
 
21
 
 
22
from bzrlib.pyutils import get_named_object
 
23
 
 
24
 
 
25
class _ObjectGetter(object):
 
26
    """Maintain a reference to an object, and return the object on request.
 
27
 
 
28
    This is used by Registry to make plain objects function similarly
 
29
    to lazily imported objects.
 
30
 
 
31
    Objects can be any sort of python object (class, function, module,
 
32
    instance, etc)
 
33
    """
 
34
 
 
35
    __slots__ = ['_obj']
 
36
 
 
37
    def __init__(self, obj):
 
38
        self._obj = obj
 
39
 
 
40
    def get_module(self):
 
41
        """Get the module the object was loaded from."""
 
42
        return self._obj.__module__
 
43
 
 
44
    def get_obj(self):
 
45
        """Get the object that was saved at creation time"""
 
46
        return self._obj
 
47
 
 
48
 
 
49
class _LazyObjectGetter(_ObjectGetter):
 
50
    """Keep a record of a possible object.
 
51
 
 
52
    When requested, load and return it.
 
53
    """
 
54
 
 
55
    __slots__ = ['_module_name', '_member_name', '_imported']
 
56
 
 
57
    def __init__(self, module_name, member_name):
 
58
        self._module_name = module_name
 
59
        self._member_name = member_name
 
60
        self._imported = False
 
61
        super(_LazyObjectGetter, self).__init__(None)
 
62
 
 
63
    def get_module(self):
 
64
        """Get the module the referenced object will be loaded from.
 
65
        """
 
66
        return self._module_name
 
67
 
 
68
    def get_obj(self):
 
69
        """Get the referenced object.
 
70
 
 
71
        Upon first request, the object will be imported. Future requests will
 
72
        return the imported object.
 
73
        """
 
74
        if not self._imported:
 
75
            self._obj = get_named_object(self._module_name, self._member_name)
 
76
            self._imported = True
 
77
        return super(_LazyObjectGetter, self).get_obj()
 
78
 
 
79
    def __repr__(self):
 
80
        return "<%s.%s object at %x, module=%r attribute=%r imported=%r>" % (
 
81
            self.__class__.__module__, self.__class__.__name__, id(self),
 
82
            self._module_name, self._member_name, self._imported)
 
83
 
 
84
 
 
85
class Registry(object):
 
86
    """A class that registers objects to a name.
 
87
 
 
88
    There are many places that want to collect related objects and access them
 
89
    by a key. This class is designed to allow registering the mapping from key
 
90
    to object. It goes one step further, and allows registering a name to a
 
91
    hypothetical object which has not been imported yet. It also supports
 
92
    adding additional information at registration time so that decisions can be
 
93
    made without having to import the object (which may be expensive).
 
94
 
 
95
    The functions 'get', 'get_info', and 'get_help' also support a
 
96
    'default_key' (settable through my_registry.default_key = XXX, XXX must
 
97
    already be registered.) Calling my_registry.get() or my_registry.get(None),
 
98
    will return the entry for the default key.
 
99
    """
 
100
 
 
101
    def __init__(self):
 
102
        """Create a new Registry."""
 
103
        self._default_key = None
 
104
        # Map from key => (is_lazy, info)
 
105
        self._dict = {}
 
106
        self._help_dict = {}
 
107
        self._info_dict = {}
 
108
 
 
109
    def register(self, key, obj, help=None, info=None,
 
110
                 override_existing=False):
 
111
        """Register a new object to a name.
 
112
 
 
113
        :param key: This is the key to use to request the object later.
 
114
        :param obj: The object to register.
 
115
        :param help: Help text for this entry. This may be a string or
 
116
                a callable. If it is a callable, it should take two
 
117
                parameters (registry, key): this registry and the key that
 
118
                the help was registered under.
 
119
        :param info: More information for this entry. Registry.get_info()
 
120
                can be used to get this information. Registry treats this as an
 
121
                opaque storage location (it is defined by the caller).
 
122
        :param override_existing: Raise KeyErorr if False and something has
 
123
                already been registered for that key. If True, ignore if there
 
124
                is an existing key (always register the new value).
 
125
        """
 
126
        if not override_existing:
 
127
            if key in self._dict:
 
128
                raise KeyError('Key %r already registered' % key)
 
129
        self._dict[key] = _ObjectGetter(obj)
 
130
        self._add_help_and_info(key, help=help, info=info)
 
131
 
 
132
    def register_lazy(self, key, module_name, member_name,
 
133
                      help=None, info=None,
 
134
                      override_existing=False):
 
135
        """Register a new object to be loaded on request.
 
136
 
 
137
        :param key: This is the key to use to request the object later.
 
138
        :param module_name: The python path to the module. Such as 'os.path'.
 
139
        :param member_name: The member of the module to return.  If empty or
 
140
                None, get() will return the module itself.
 
141
        :param help: Help text for this entry. This may be a string or
 
142
                a callable.
 
143
        :param info: More information for this entry. Registry.get_info()
 
144
                can be used to get this information. Registry treats this as an
 
145
                opaque storage location (it is defined by the caller).
 
146
        :param override_existing: If True, replace the existing object
 
147
                with the new one. If False, if there is already something
 
148
                registered with the same key, raise a KeyError
 
149
        """
 
150
        if not override_existing:
 
151
            if key in self._dict:
 
152
                raise KeyError('Key %r already registered' % key)
 
153
        self._dict[key] = _LazyObjectGetter(module_name, member_name)
 
154
        self._add_help_and_info(key, help=help, info=info)
 
155
 
 
156
    def _add_help_and_info(self, key, help=None, info=None):
 
157
        """Add the help and information about this key"""
 
158
        self._help_dict[key] = help
 
159
        self._info_dict[key] = info
 
160
 
 
161
    def get(self, key=None):
 
162
        """Return the object register()'ed to the given key.
 
163
 
 
164
        May raise ImportError if the object was registered lazily and
 
165
        there are any problems, or AttributeError if the module does not
 
166
        have the supplied member.
 
167
 
 
168
        :param key: The key to obtain the object for. If no object has been
 
169
            registered to that key, the object registered for self.default_key
 
170
            will be returned instead, if it exists. Otherwise KeyError will be
 
171
            raised.
 
172
        :return: The previously registered object.
 
173
        :raises ImportError: If the object was registered lazily, and there are
 
174
            problems during import.
 
175
        :raises AttributeError: If registered lazily, and the module does not
 
176
            contain the registered member.
 
177
        """
 
178
        return self._dict[self._get_key_or_default(key)].get_obj()
 
179
 
 
180
    def _get_module(self, key):
 
181
        """Return the module the object will be or was loaded from.
 
182
 
 
183
        :param key: The key to obtain the module for.
 
184
        :return: The name of the module
 
185
        """
 
186
        return self._dict[key].get_module()
 
187
 
 
188
    def get_prefix(self, fullname):
 
189
        """Return an object whose key is a prefix of the supplied value.
 
190
 
 
191
        :fullname: The name to find a prefix for
 
192
        :return: a tuple of (object, remainder), where the remainder is the
 
193
            portion of the name that did not match the key.
 
194
        """
 
195
        for key in self.keys():
 
196
            if fullname.startswith(key):
 
197
                return self.get(key), fullname[len(key):]
 
198
 
 
199
    def _get_key_or_default(self, key=None):
 
200
        """Return either 'key' or the default key if key is None"""
 
201
        if key is not None:
 
202
            return key
 
203
        if self.default_key is None:
 
204
            raise KeyError('Key is None, and no default key is set')
 
205
        else:
 
206
            return self.default_key
 
207
 
 
208
    def get_help(self, key=None):
 
209
        """Get the help text associated with the given key"""
 
210
        the_help = self._help_dict[self._get_key_or_default(key)]
 
211
        if callable(the_help):
 
212
            return the_help(self, key)
 
213
        return the_help
 
214
 
 
215
    def get_info(self, key=None):
 
216
        """Get the extra information associated with the given key"""
 
217
        return self._info_dict[self._get_key_or_default(key)]
 
218
 
 
219
    def remove(self, key):
 
220
        """Remove a registered entry.
 
221
 
 
222
        This is mostly for the test suite, but it can be used by others
 
223
        """
 
224
        del self._dict[key]
 
225
 
 
226
    def __contains__(self, key):
 
227
        return key in self._dict
 
228
 
 
229
    def keys(self):
 
230
        """Get a list of registered entries"""
 
231
        return sorted(self._dict.keys())
 
232
 
 
233
    def iteritems(self):
 
234
        for key, getter in self._dict.iteritems():
 
235
            yield key, getter.get_obj()
 
236
 
 
237
    def items(self):
 
238
        # We should not use the iteritems() implementation below (see bug
 
239
        # #430510)
 
240
        return sorted([(key, getter.get_obj())
 
241
                       for key, getter in self._dict.items()])
 
242
 
 
243
    def _set_default_key(self, key):
 
244
        if not self._dict.has_key(key):
 
245
            raise KeyError('No object registered under key %s.' % key)
 
246
        else:
 
247
            self._default_key = key
 
248
 
 
249
    def _get_default_key(self):
 
250
        return self._default_key
 
251
 
 
252
    default_key = property(_get_default_key, _set_default_key,
 
253
                            doc="Current value of the default key."
 
254
                                " Can be set to any existing key.")
 
255
 
 
256
 
 
257
class FormatRegistry(Registry):
 
258
    """Registry specialised for handling formats."""
 
259
 
 
260
    def __init__(self, other_registry=None):
 
261
        Registry.__init__(self)
 
262
        self._other_registry = other_registry
 
263
 
 
264
    def register(self, key, obj, help=None, info=None,
 
265
                 override_existing=False):
 
266
        Registry.register(self, key, obj, help=help, info=info,
 
267
            override_existing=override_existing)
 
268
        if self._other_registry is not None:
 
269
            self._other_registry.register(key, obj, help=help,
 
270
                info=info, override_existing=override_existing)
 
271
 
 
272
    def register_lazy(self, key, module_name, member_name,
 
273
                      help=None, info=None,
 
274
                      override_existing=False):
 
275
        # Overridden to allow capturing registrations to two seperate
 
276
        # registries in a single call.
 
277
        Registry.register_lazy(self, key, module_name, member_name,
 
278
                help=help, info=info, override_existing=override_existing)
 
279
        if self._other_registry is not None:
 
280
            self._other_registry.register_lazy(key, module_name, member_name,
 
281
                help=help, info=info, override_existing=override_existing)
 
282
 
 
283
    def remove(self, key):
 
284
        Registry.remove(self, key)
 
285
        if self._other_registry is not None:
 
286
            self._other_registry.remove(key)
 
287
 
 
288
    def get(self, format_string):
 
289
        r = Registry.get(self, format_string)
 
290
        if callable(r):
 
291
            r = r()
 
292
        return r