/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: James Westby
  • Date: 2009-04-06 22:31:35 UTC
  • mto: This revision was merged to the branch mainline in revision 4263.
  • Revision ID: james.westby@canonical.com-20090406223135-f7os74eyxlbpxtal
Update the comments based on those in the test.

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