~bzr-pqm/bzr/bzr.dev

4763.2.4 by John Arbash Meinel
merge bzr.2.1 in preparation for NEWS entry.
1
# Copyright (C) 2007-2010 Canonical Ltd
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
16
17
18
"""Support for plugin hooking logic."""
3948.3.3 by Martin Pool
merge trunk
19
from bzrlib import registry
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
4098.2.1 by Robert Collins
Allow self documenting hooks.
22
import textwrap
23
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
24
from bzrlib import (
4098.2.1 by Robert Collins
Allow self documenting hooks.
25
        _format_version_tuple,
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
26
        errors,
27
        )
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
28
from bzrlib.help_topics import help_as_plain_text
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
29
""")
30
31
4119.3.1 by Robert Collins
Create a single registry of all Hooks classes, removing the test suite knowledge of such hooks and allowing plugins to sensibly and safely define new hooks.
32
known_hooks = registry.Registry()
4230.1.1 by James Westby
Add msgeditor hooks to known_hooks.
33
# known_hooks registry contains
4230.1.2 by James Westby
Update the comments based on those in the test.
34
# tuple of (module, member name) which is the hook point
4230.1.1 by James Westby
Add msgeditor hooks to known_hooks.
35
# module where the specific hooks are defined
4230.1.2 by James Westby
Update the comments based on those in the test.
36
# callable to get the empty specific Hooks for that attribute
4119.3.1 by Robert Collins
Create a single registry of all Hooks classes, removing the test suite knowledge of such hooks and allowing plugins to sensibly and safely define new hooks.
37
known_hooks.register_lazy(('bzrlib.branch', 'Branch.hooks'), 'bzrlib.branch',
38
    'BranchHooks')
4160.1.1 by Robert Collins
Add a BzrDir.pre_open hook for use by the smart server gaol.
39
known_hooks.register_lazy(('bzrlib.bzrdir', 'BzrDir.hooks'), 'bzrlib.bzrdir',
40
    'BzrDirHooks')
4119.3.1 by Robert Collins
Create a single registry of all Hooks classes, removing the test suite knowledge of such hooks and allowing plugins to sensibly and safely define new hooks.
41
known_hooks.register_lazy(('bzrlib.commands', 'Command.hooks'),
42
    'bzrlib.commands', 'CommandHooks')
4307.3.2 by Jelmer Vernooij
Add tests for the repository info hook.
43
known_hooks.register_lazy(('bzrlib.info', 'hooks'),
44
    'bzrlib.info', 'InfoHooks')
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
45
known_hooks.register_lazy(('bzrlib.lock', 'Lock.hooks'), 'bzrlib.lock',
46
    'LockHooks')
4869.3.4 by Andrew Bennetts
Add Merger.hooks to the global known_hooks.
47
known_hooks.register_lazy(('bzrlib.merge', 'Merger.hooks'), 'bzrlib.merge',
48
    'MergeHooks')
4230.1.1 by James Westby
Add msgeditor hooks to known_hooks.
49
known_hooks.register_lazy(('bzrlib.msgeditor', 'hooks'), 'bzrlib.msgeditor',
50
    'MessageEditorHooks')
4119.3.1 by Robert Collins
Create a single registry of all Hooks classes, removing the test suite knowledge of such hooks and allowing plugins to sensibly and safely define new hooks.
51
known_hooks.register_lazy(('bzrlib.mutabletree', 'MutableTree.hooks'),
52
    'bzrlib.mutabletree', 'MutableTreeHooks')
53
known_hooks.register_lazy(('bzrlib.smart.client', '_SmartClient.hooks'),
54
    'bzrlib.smart.client', 'SmartClientHooks')
55
known_hooks.register_lazy(('bzrlib.smart.server', 'SmartTCPServer.hooks'),
56
    'bzrlib.smart.server', 'SmartServerHooks')
5393.3.1 by Parth Malwankar
initial post_status hook is now working
57
known_hooks.register_lazy(('bzrlib.status', 'hooks'),
58
    'bzrlib.status', 'StatusHooks')
4216.4.2 by Jelmer Vernooij
Register RioVersionInfoBuilderHooks in the hooks registry.
59
known_hooks.register_lazy(
60
    ('bzrlib.version_info_formats.format_rio', 'RioVersionInfoBuilder.hooks'),
61
    'bzrlib.version_info_formats.format_rio', 'RioVersionInfoBuilderHooks')
4098.5.15 by Aaron Bentley
Implement hook for bzr send.
62
known_hooks.register_lazy(
5086.3.1 by Jelmer Vernooij
``bzrlib.merge_directive._BaseMergeDirective`` has been renamed to
63
    ('bzrlib.merge_directive', 'BaseMergeDirective.hooks'),
4098.5.16 by Aaron Bentley
Move hook to MergeDirective, implement MergeDirective.compose_merge_request.
64
    'bzrlib.merge_directive', 'MergeDirectiveHooks')
4119.3.1 by Robert Collins
Create a single registry of all Hooks classes, removing the test suite knowledge of such hooks and allowing plugins to sensibly and safely define new hooks.
65
66
67
def known_hooks_key_to_object((module_name, member_name)):
68
    """Convert a known_hooks key to a object.
69
70
    :param key: A tuple (module_name, member_name) as found in the keys of
71
        the known_hooks registry.
72
    :return: The object this specifies.
73
    """
74
    return registry._LazyObjectGetter(module_name, member_name).get_obj()
75
76
77
def known_hooks_key_to_parent_and_attribute((module_name, member_name)):
78
    """Convert a known_hooks key to a object.
79
80
    :param key: A tuple (module_name, member_name) as found in the keys of
81
        the known_hooks registry.
82
    :return: The object this specifies.
83
    """
84
    member_list = member_name.rsplit('.', 1)
85
    if len(member_list) == 2:
86
        parent_name, attribute = member_list
87
    else:
88
        parent_name = None
89
        attribute = member_name
90
    parent = known_hooks_key_to_object((module_name, parent_name))
91
    return parent, attribute
92
93
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
94
class Hooks(dict):
95
    """A dictionary mapping hook name to a list of callables.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
96
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
97
    e.g. ['FOO'] Is the list of items to be called when the
98
    FOO hook is triggered.
99
    """
100
2553.1.1 by Robert Collins
Give Hooks names.
101
    def __init__(self):
102
        dict.__init__(self)
103
        self._callable_names = {}
104
4098.2.1 by Robert Collins
Allow self documenting hooks.
105
    def create_hook(self, hook):
106
        """Create a hook which can have callbacks registered for it.
107
108
        :param hook: The hook to create. An object meeting the protocol of
4098.2.2 by Robert Collins
Review feedback.
109
            bzrlib.hooks.HookPoint. It's name is used as the key for future
4098.2.1 by Robert Collins
Allow self documenting hooks.
110
            lookups.
111
        """
112
        if hook.name in self:
113
            raise errors.DuplicateKey(hook.name)
114
        self[hook.name] = hook
115
116
    def docs(self):
117
        """Generate the documentation for this Hooks instance.
118
119
        This introspects all the individual hooks and returns their docs as well.
120
        """
121
        hook_names = sorted(self.keys())
122
        hook_docs = []
4108.3.1 by Robert Collins
Include the Hooks class in the Hooks docs.
123
        name = self.__class__.__name__
124
        hook_docs.append(name)
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
125
        hook_docs.append("-"*len(name))
4108.3.1 by Robert Collins
Include the Hooks class in the Hooks docs.
126
        hook_docs.append("")
4098.2.1 by Robert Collins
Allow self documenting hooks.
127
        for hook_name in hook_names:
128
            hook = self[hook_name]
129
            try:
130
                hook_docs.append(hook.docs())
131
            except AttributeError:
132
                # legacy hook
133
                strings = []
134
                strings.append(hook_name)
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
135
                strings.append("~" * len(hook_name))
4098.2.1 by Robert Collins
Allow self documenting hooks.
136
                strings.append("")
137
                strings.append("An old-style hook. For documentation see the __init__ "
4108.3.1 by Robert Collins
Include the Hooks class in the Hooks docs.
138
                    "method of '%s'\n" % (name,))
4098.2.1 by Robert Collins
Allow self documenting hooks.
139
                hook_docs.extend(strings)
140
        return "\n".join(hook_docs)
141
2553.1.1 by Robert Collins
Give Hooks names.
142
    def get_hook_name(self, a_callable):
143
        """Get the name for a_callable for UI display.
144
145
        If no name has been registered, the string 'No hook name' is returned.
2553.1.3 by Robert Collins
Increase docs in response to review feedback.
146
        We use a fixed string rather than repr or the callables module because
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
147
        the code names are rarely meaningful for end users and this is not
2553.1.3 by Robert Collins
Increase docs in response to review feedback.
148
        intended for debugging.
2553.1.1 by Robert Collins
Give Hooks names.
149
        """
150
        return self._callable_names.get(a_callable, "No hook name")
151
3256.2.5 by Daniel Watkins
Added install_named_hook.
152
    def install_named_hook(self, hook_name, a_callable, name):
153
        """Install a_callable in to the hook hook_name, and label it name.
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
154
155
        :param hook_name: A hook name. See the __init__ method of BranchHooks
156
            for the complete list of hooks.
157
        :param a_callable: The callable to be invoked when the hook triggers.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
158
            The exact signature will depend on the hook - see the __init__
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
159
            method of BranchHooks for details on each hook.
3256.2.3 by Daniel Watkins
Added docs.
160
        :param name: A name to associate a_callable with, to show users what is
161
            running.
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
162
        """
163
        try:
4098.2.1 by Robert Collins
Allow self documenting hooks.
164
            hook = self[hook_name]
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
165
        except KeyError:
166
            raise errors.UnknownHook(self.__class__.__name__, hook_name)
4098.2.1 by Robert Collins
Allow self documenting hooks.
167
        try:
168
            # list hooks, old-style, not yet deprecated but less useful.
169
            hook.append(a_callable)
170
        except AttributeError:
171
            hook.hook(a_callable, name)
3256.2.10 by Daniel Watkins
Tightened exception scope, as suggested by Aaron.
172
        if name is not None:
173
            self.name_hook(a_callable, name)
2553.1.1 by Robert Collins
Give Hooks names.
174
175
    def name_hook(self, a_callable, name):
176
        """Associate name with a_callable to show users what is running."""
177
        self._callable_names[a_callable] = name
4098.2.1 by Robert Collins
Allow self documenting hooks.
178
179
4098.2.2 by Robert Collins
Review feedback.
180
class HookPoint(object):
4098.2.1 by Robert Collins
Allow self documenting hooks.
181
    """A single hook that clients can register to be called back when it fires.
182
183
    :ivar name: The name of the hook.
5393.3.1 by Parth Malwankar
initial post_status hook is now working
184
    :ivar doc: The docs for using the hook.
4098.2.1 by Robert Collins
Allow self documenting hooks.
185
    :ivar introduced: A version tuple specifying what version the hook was
186
        introduced in. None indicates an unknown version.
187
    :ivar deprecated: A version tuple specifying what version the hook was
4098.5.15 by Aaron Bentley
Implement hook for bzr send.
188
        deprecated or superseded in. None indicates that the hook is not
189
        superseded or deprecated. If the hook is superseded then the doc
4098.2.1 by Robert Collins
Allow self documenting hooks.
190
        should describe the recommended replacement hook to register for.
191
    """
192
193
    def __init__(self, name, doc, introduced, deprecated):
4098.2.2 by Robert Collins
Review feedback.
194
        """Create a HookPoint.
4098.2.3 by Robert Collins
White space difference-of-opinion.
195
4098.2.1 by Robert Collins
Allow self documenting hooks.
196
        :param name: The name of the hook, for clients to use when registering.
197
        :param doc: The docs for the hook.
198
        :param introduced: When the hook was introduced (e.g. (0, 15)).
199
        :param deprecated: When the hook was deprecated, None for
200
            not-deprecated.
201
        """
202
        self.name = name
203
        self.__doc__ = doc
204
        self.introduced = introduced
205
        self.deprecated = deprecated
206
        self._callbacks = []
207
        self._callback_names = {}
208
209
    def docs(self):
4098.2.2 by Robert Collins
Review feedback.
210
        """Generate the documentation for this HookPoint.
4098.2.3 by Robert Collins
White space difference-of-opinion.
211
4098.2.1 by Robert Collins
Allow self documenting hooks.
212
        :return: A string terminated in \n.
213
        """
214
        strings = []
215
        strings.append(self.name)
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
216
        strings.append('~'*len(self.name))
4098.2.1 by Robert Collins
Allow self documenting hooks.
217
        strings.append('')
218
        if self.introduced:
219
            introduced_string = _format_version_tuple(self.introduced)
220
        else:
221
            introduced_string = 'unknown'
222
        strings.append('Introduced in: %s' % introduced_string)
223
        if self.deprecated:
224
            deprecated_string = _format_version_tuple(self.deprecated)
4634.21.1 by Ian Clatworthy
Tweak hook help to only report deprecation information if actually deprecated
225
            strings.append('Deprecated in: %s' % deprecated_string)
4098.2.1 by Robert Collins
Allow self documenting hooks.
226
        strings.append('')
4070.11.2 by Martin Pool
Ask textwrap not to break long words or on hyphens
227
        strings.extend(textwrap.wrap(self.__doc__,
4070.11.5 by Martin Pool
textwrap break_on_hyphens option is not available in python2.5
228
            break_long_words=False))
4098.2.1 by Robert Collins
Allow self documenting hooks.
229
        strings.append('')
230
        return '\n'.join(strings)
231
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
232
    def __eq__(self, other):
233
        return (type(other) == type(self) and 
234
            other.__dict__ == self.__dict__)
235
4098.2.1 by Robert Collins
Allow self documenting hooks.
236
    def hook(self, callback, callback_label):
4098.2.2 by Robert Collins
Review feedback.
237
        """Register a callback to be called when this HookPoint fires.
4098.2.1 by Robert Collins
Allow self documenting hooks.
238
4098.2.2 by Robert Collins
Review feedback.
239
        :param callback: The callable to use when this HookPoint fires.
4098.2.1 by Robert Collins
Allow self documenting hooks.
240
        :param callback_label: A label to show in the UI while this callback is
241
            processing.
242
        """
243
        self._callbacks.append(callback)
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
244
        if callback_label is not None:
245
            self._callback_names[callback] = callback_label
4098.2.1 by Robert Collins
Allow self documenting hooks.
246
247
    def __iter__(self):
248
        return iter(self._callbacks)
249
4119.3.3 by Robert Collins
Provide a __len__ on HookPoint so that 'if somehookpoint' will behave as it did when they were lists.
250
    def __len__(self):
251
        return len(self._callbacks)
252
4098.2.1 by Robert Collins
Allow self documenting hooks.
253
    def __repr__(self):
254
        strings = []
4098.2.2 by Robert Collins
Review feedback.
255
        strings.append("<%s(" % type(self).__name__)
4098.2.1 by Robert Collins
Allow self documenting hooks.
256
        strings.append(self.name)
257
        strings.append("), callbacks=[")
258
        for callback in self._callbacks:
259
            strings.append(repr(callback))
260
            strings.append("(")
261
            strings.append(self._callback_names[callback])
262
            strings.append("),")
263
        if len(self._callbacks) == 1:
264
            strings[-1] = ")"
265
        strings.append("]>")
266
        return ''.join(strings)
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
267
268
269
_help_prefix = \
270
"""
271
Hooks
272
=====
273
274
Introduction
275
------------
276
277
A hook of type *xxx* of class *yyy* needs to be registered using::
278
279
  yyy.hooks.install_named_hook("xxx", ...)
280
5255.1.1 by Ian Clatworthy
Fix PDF generation of User Reference
281
See :doc:`Using hooks<../user-guide/hooks>` in the User Guide for examples.
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
282
283
The class that contains each hook is given before the hooks it supplies. For
284
instance, BranchHooks as the class is the hooks class for
285
`bzrlib.branch.Branch.hooks`.
286
287
Each description also indicates whether the hook runs on the client (the
288
machine where bzr was invoked) or the server (the machine addressed by
289
the branch URL).  These may be, but are not necessarily, the same machine.
290
291
Plugins (including hooks) are run on the server if all of these is true:
292
293
  * The connection is via a smart server (accessed with a URL starting with
294
    "bzr://", "bzr+ssh://" or "bzr+http://", or accessed via a "http://"
295
    URL when a smart server is available via HTTP).
296
297
  * The hook is either server specific or part of general infrastructure rather
298
    than client specific code (such as commit).
299
300
"""
301
302
def hooks_help_text(topic):
303
    segments = [_help_prefix]
304
    for hook_key in sorted(known_hooks.keys()):
305
        hooks = known_hooks_key_to_object(hook_key)
306
        segments.append(hooks.docs())
307
    return '\n'.join(segments)