/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 breezy/registry.py

  • Committer: Gustav Hartvigsson
  • Date: 2021-01-09 21:36:27 UTC
  • Revision ID: gustav.hartvigsson@gmail.com-20210109213627-h1xwcutzy9m7a99b
Added 'Case Preserving Working Tree Use Cases' from Canonical Wiki

* Addod a page from the Canonical Bazaar wiki
  with information on the scmeatics of case
  perserving filesystems an a case insensitive
  filesystem works.
  
  * Needs re-work, but this will do as it is the
    same inforamoton as what was on the linked
    page in the currint documentation.

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