/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/hooks.py

  • Committer: Robert Collins
  • Date: 2009-05-12 03:50:39 UTC
  • mto: This revision was merged to the branch mainline in revision 4593.
  • Revision ID: robertc@robertcollins.net-20090512035039-6x0pahpjpkdnm9zb
Note another possible error.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007, 2008 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
 
 
18
"""Support for plugin hooking logic."""
 
19
from bzrlib import registry
 
20
from bzrlib.lazy_import import lazy_import
 
21
from bzrlib.symbol_versioning import deprecated_method
 
22
lazy_import(globals(), """
 
23
import textwrap
 
24
 
 
25
from bzrlib import (
 
26
        _format_version_tuple,
 
27
        errors,
 
28
        )
 
29
from bzrlib.help_topics import help_as_plain_text
 
30
""")
 
31
 
 
32
 
 
33
known_hooks = registry.Registry()
 
34
# known_hooks registry contains
 
35
# tuple of (module, member name) which is the hook point
 
36
# module where the specific hooks are defined
 
37
# callable to get the empty specific Hooks for that attribute
 
38
known_hooks.register_lazy(('bzrlib.branch', 'Branch.hooks'), 'bzrlib.branch',
 
39
    'BranchHooks')
 
40
known_hooks.register_lazy(('bzrlib.bzrdir', 'BzrDir.hooks'), 'bzrlib.bzrdir',
 
41
    'BzrDirHooks')
 
42
known_hooks.register_lazy(('bzrlib.commands', 'Command.hooks'),
 
43
    'bzrlib.commands', 'CommandHooks')
 
44
known_hooks.register_lazy(('bzrlib.info', 'hooks'),
 
45
    'bzrlib.info', 'InfoHooks')
 
46
known_hooks.register_lazy(('bzrlib.lock', 'Lock.hooks'), 'bzrlib.lock',
 
47
    'LockHooks')
 
48
known_hooks.register_lazy(('bzrlib.msgeditor', 'hooks'), 'bzrlib.msgeditor',
 
49
    'MessageEditorHooks')
 
50
known_hooks.register_lazy(('bzrlib.mutabletree', 'MutableTree.hooks'),
 
51
    'bzrlib.mutabletree', 'MutableTreeHooks')
 
52
known_hooks.register_lazy(('bzrlib.smart.client', '_SmartClient.hooks'),
 
53
    'bzrlib.smart.client', 'SmartClientHooks')
 
54
known_hooks.register_lazy(('bzrlib.smart.server', 'SmartTCPServer.hooks'),
 
55
    'bzrlib.smart.server', 'SmartServerHooks')
 
56
known_hooks.register_lazy(
 
57
    ('bzrlib.version_info_formats.format_rio', 'RioVersionInfoBuilder.hooks'),
 
58
    'bzrlib.version_info_formats.format_rio', 'RioVersionInfoBuilderHooks')
 
59
 
 
60
 
 
61
def known_hooks_key_to_object((module_name, member_name)):
 
62
    """Convert a known_hooks key to a object.
 
63
 
 
64
    :param key: A tuple (module_name, member_name) as found in the keys of
 
65
        the known_hooks registry.
 
66
    :return: The object this specifies.
 
67
    """
 
68
    return registry._LazyObjectGetter(module_name, member_name).get_obj()
 
69
 
 
70
 
 
71
def known_hooks_key_to_parent_and_attribute((module_name, member_name)):
 
72
    """Convert a known_hooks key to a object.
 
73
 
 
74
    :param key: A tuple (module_name, member_name) as found in the keys of
 
75
        the known_hooks registry.
 
76
    :return: The object this specifies.
 
77
    """
 
78
    member_list = member_name.rsplit('.', 1)
 
79
    if len(member_list) == 2:
 
80
        parent_name, attribute = member_list
 
81
    else:
 
82
        parent_name = None
 
83
        attribute = member_name
 
84
    parent = known_hooks_key_to_object((module_name, parent_name))
 
85
    return parent, attribute
 
86
 
 
87
 
 
88
class Hooks(dict):
 
89
    """A dictionary mapping hook name to a list of callables.
 
90
 
 
91
    e.g. ['FOO'] Is the list of items to be called when the
 
92
    FOO hook is triggered.
 
93
    """
 
94
 
 
95
    def __init__(self):
 
96
        dict.__init__(self)
 
97
        self._callable_names = {}
 
98
 
 
99
    def create_hook(self, hook):
 
100
        """Create a hook which can have callbacks registered for it.
 
101
 
 
102
        :param hook: The hook to create. An object meeting the protocol of
 
103
            bzrlib.hooks.HookPoint. It's name is used as the key for future
 
104
            lookups.
 
105
        """
 
106
        if hook.name in self:
 
107
            raise errors.DuplicateKey(hook.name)
 
108
        self[hook.name] = hook
 
109
 
 
110
    def docs(self):
 
111
        """Generate the documentation for this Hooks instance.
 
112
 
 
113
        This introspects all the individual hooks and returns their docs as well.
 
114
        """
 
115
        hook_names = sorted(self.keys())
 
116
        hook_docs = []
 
117
        name = self.__class__.__name__
 
118
        hook_docs.append(name)
 
119
        hook_docs.append("-"*len(name))
 
120
        hook_docs.append("")
 
121
        for hook_name in hook_names:
 
122
            hook = self[hook_name]
 
123
            try:
 
124
                hook_docs.append(hook.docs())
 
125
            except AttributeError:
 
126
                # legacy hook
 
127
                strings = []
 
128
                strings.append(hook_name)
 
129
                strings.append("~" * len(hook_name))
 
130
                strings.append("")
 
131
                strings.append("An old-style hook. For documentation see the __init__ "
 
132
                    "method of '%s'\n" % (name,))
 
133
                hook_docs.extend(strings)
 
134
        return "\n".join(hook_docs)
 
135
 
 
136
    def get_hook_name(self, a_callable):
 
137
        """Get the name for a_callable for UI display.
 
138
 
 
139
        If no name has been registered, the string 'No hook name' is returned.
 
140
        We use a fixed string rather than repr or the callables module because
 
141
        the code names are rarely meaningful for end users and this is not
 
142
        intended for debugging.
 
143
        """
 
144
        return self._callable_names.get(a_callable, "No hook name")
 
145
 
 
146
    def install_named_hook(self, hook_name, a_callable, name):
 
147
        """Install a_callable in to the hook hook_name, and label it name.
 
148
 
 
149
        :param hook_name: A hook name. See the __init__ method of BranchHooks
 
150
            for the complete list of hooks.
 
151
        :param a_callable: The callable to be invoked when the hook triggers.
 
152
            The exact signature will depend on the hook - see the __init__
 
153
            method of BranchHooks for details on each hook.
 
154
        :param name: A name to associate a_callable with, to show users what is
 
155
            running.
 
156
        """
 
157
        try:
 
158
            hook = self[hook_name]
 
159
        except KeyError:
 
160
            raise errors.UnknownHook(self.__class__.__name__, hook_name)
 
161
        try:
 
162
            # list hooks, old-style, not yet deprecated but less useful.
 
163
            hook.append(a_callable)
 
164
        except AttributeError:
 
165
            hook.hook(a_callable, name)
 
166
        if name is not None:
 
167
            self.name_hook(a_callable, name)
 
168
 
 
169
    def name_hook(self, a_callable, name):
 
170
        """Associate name with a_callable to show users what is running."""
 
171
        self._callable_names[a_callable] = name
 
172
 
 
173
 
 
174
class HookPoint(object):
 
175
    """A single hook that clients can register to be called back when it fires.
 
176
 
 
177
    :ivar name: The name of the hook.
 
178
    :ivar introduced: A version tuple specifying what version the hook was
 
179
        introduced in. None indicates an unknown version.
 
180
    :ivar deprecated: A version tuple specifying what version the hook was
 
181
        deprecated or superceded in. None indicates that the hook is not
 
182
        superceded or deprecated. If the hook is superceded then the doc
 
183
        should describe the recommended replacement hook to register for.
 
184
    :ivar doc: The docs for using the hook.
 
185
    """
 
186
 
 
187
    def __init__(self, name, doc, introduced, deprecated):
 
188
        """Create a HookPoint.
 
189
 
 
190
        :param name: The name of the hook, for clients to use when registering.
 
191
        :param doc: The docs for the hook.
 
192
        :param introduced: When the hook was introduced (e.g. (0, 15)).
 
193
        :param deprecated: When the hook was deprecated, None for
 
194
            not-deprecated.
 
195
        """
 
196
        self.name = name
 
197
        self.__doc__ = doc
 
198
        self.introduced = introduced
 
199
        self.deprecated = deprecated
 
200
        self._callbacks = []
 
201
        self._callback_names = {}
 
202
 
 
203
    def docs(self):
 
204
        """Generate the documentation for this HookPoint.
 
205
 
 
206
        :return: A string terminated in \n.
 
207
        """
 
208
        strings = []
 
209
        strings.append(self.name)
 
210
        strings.append('~'*len(self.name))
 
211
        strings.append('')
 
212
        if self.introduced:
 
213
            introduced_string = _format_version_tuple(self.introduced)
 
214
        else:
 
215
            introduced_string = 'unknown'
 
216
        strings.append('Introduced in: %s' % introduced_string)
 
217
        if self.deprecated:
 
218
            deprecated_string = _format_version_tuple(self.deprecated)
 
219
        else:
 
220
            deprecated_string = 'Not deprecated'
 
221
        strings.append('Deprecated in: %s' % deprecated_string)
 
222
        strings.append('')
 
223
        strings.extend(textwrap.wrap(self.__doc__))
 
224
        strings.append('')
 
225
        return '\n'.join(strings)
 
226
 
 
227
    def __eq__(self, other):
 
228
        return (type(other) == type(self) and 
 
229
            other.__dict__ == self.__dict__)
 
230
 
 
231
    def hook(self, callback, callback_label):
 
232
        """Register a callback to be called when this HookPoint fires.
 
233
 
 
234
        :param callback: The callable to use when this HookPoint fires.
 
235
        :param callback_label: A label to show in the UI while this callback is
 
236
            processing.
 
237
        """
 
238
        self._callbacks.append(callback)
 
239
        if callback_label is not None:
 
240
            self._callback_names[callback] = callback_label
 
241
 
 
242
    def __iter__(self):
 
243
        return iter(self._callbacks)
 
244
 
 
245
    def __len__(self):
 
246
        return len(self._callbacks)
 
247
 
 
248
    def __repr__(self):
 
249
        strings = []
 
250
        strings.append("<%s(" % type(self).__name__)
 
251
        strings.append(self.name)
 
252
        strings.append("), callbacks=[")
 
253
        for callback in self._callbacks:
 
254
            strings.append(repr(callback))
 
255
            strings.append("(")
 
256
            strings.append(self._callback_names[callback])
 
257
            strings.append("),")
 
258
        if len(self._callbacks) == 1:
 
259
            strings[-1] = ")"
 
260
        strings.append("]>")
 
261
        return ''.join(strings)
 
262
 
 
263
 
 
264
_help_prefix = \
 
265
"""
 
266
Hooks
 
267
=====
 
268
 
 
269
Introduction
 
270
------------
 
271
 
 
272
A hook of type *xxx* of class *yyy* needs to be registered using::
 
273
 
 
274
  yyy.hooks.install_named_hook("xxx", ...)
 
275
 
 
276
See `Using hooks`_ in the User Guide for examples.
 
277
 
 
278
.. _Using hooks: ../user-guide/index.html#using-hooks
 
279
 
 
280
The class that contains each hook is given before the hooks it supplies. For
 
281
instance, BranchHooks as the class is the hooks class for
 
282
`bzrlib.branch.Branch.hooks`.
 
283
 
 
284
Each description also indicates whether the hook runs on the client (the
 
285
machine where bzr was invoked) or the server (the machine addressed by
 
286
the branch URL).  These may be, but are not necessarily, the same machine.
 
287
 
 
288
Plugins (including hooks) are run on the server if all of these is true:
 
289
 
 
290
  * The connection is via a smart server (accessed with a URL starting with
 
291
    "bzr://", "bzr+ssh://" or "bzr+http://", or accessed via a "http://"
 
292
    URL when a smart server is available via HTTP).
 
293
 
 
294
  * The hook is either server specific or part of general infrastructure rather
 
295
    than client specific code (such as commit).
 
296
 
 
297
"""
 
298
 
 
299
def hooks_help_text(topic):
 
300
    segments = [_help_prefix]
 
301
    for hook_key in sorted(known_hooks.keys()):
 
302
        hooks = known_hooks_key_to_object(hook_key)
 
303
        segments.append(hooks.docs())
 
304
    return '\n'.join(segments)