1
# Copyright (C) 2007, 2008 Canonical Ltd
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.
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.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
"""Support for plugin hooking logic."""
19
from bzrlib.lazy_import import lazy_import
20
from bzrlib import registry
21
from bzrlib.symbol_versioning import deprecated_method, one_five
22
lazy_import(globals(), """
26
_format_version_tuple,
29
from bzrlib.help_topics import help_as_plain_text
33
known_hooks = registry.Registry()
34
known_hooks.register_lazy(('bzrlib.branch', 'Branch.hooks'), 'bzrlib.branch',
36
known_hooks.register_lazy(('bzrlib.commands', 'Command.hooks'),
37
'bzrlib.commands', 'CommandHooks')
38
known_hooks.register_lazy(('bzrlib.lock', 'Lock.hooks'), 'bzrlib.lock',
40
known_hooks.register_lazy(('bzrlib.mutabletree', 'MutableTree.hooks'),
41
'bzrlib.mutabletree', 'MutableTreeHooks')
42
known_hooks.register_lazy(('bzrlib.smart.client', '_SmartClient.hooks'),
43
'bzrlib.smart.client', 'SmartClientHooks')
44
known_hooks.register_lazy(('bzrlib.smart.server', 'SmartTCPServer.hooks'),
45
'bzrlib.smart.server', 'SmartServerHooks')
48
def known_hooks_key_to_object((module_name, member_name)):
49
"""Convert a known_hooks key to a object.
51
:param key: A tuple (module_name, member_name) as found in the keys of
52
the known_hooks registry.
53
:return: The object this specifies.
55
return registry._LazyObjectGetter(module_name, member_name).get_obj()
58
def known_hooks_key_to_parent_and_attribute((module_name, member_name)):
59
"""Convert a known_hooks key to a object.
61
:param key: A tuple (module_name, member_name) as found in the keys of
62
the known_hooks registry.
63
:return: The object this specifies.
65
member_list = member_name.rsplit('.', 1)
66
if len(member_list) == 2:
67
parent_name, attribute = member_list
70
attribute = member_name
71
parent = known_hooks_key_to_object((module_name, parent_name))
72
return parent, attribute
76
"""A dictionary mapping hook name to a list of callables.
78
e.g. ['FOO'] Is the list of items to be called when the
79
FOO hook is triggered.
84
self._callable_names = {}
86
def create_hook(self, hook):
87
"""Create a hook which can have callbacks registered for it.
89
:param hook: The hook to create. An object meeting the protocol of
90
bzrlib.hooks.HookPoint. It's name is used as the key for future
94
raise errors.DuplicateKey(hook.name)
95
self[hook.name] = hook
98
"""Generate the documentation for this Hooks instance.
100
This introspects all the individual hooks and returns their docs as well.
102
hook_names = sorted(self.keys())
104
name = self.__class__.__name__
105
hook_docs.append(name)
106
hook_docs.append("-"*len(name))
108
for hook_name in hook_names:
109
hook = self[hook_name]
111
hook_docs.append(hook.docs())
112
except AttributeError:
115
strings.append(hook_name)
116
strings.append("~" * len(hook_name))
118
strings.append("An old-style hook. For documentation see the __init__ "
119
"method of '%s'\n" % (name,))
120
hook_docs.extend(strings)
121
return "\n".join(hook_docs)
123
def get_hook_name(self, a_callable):
124
"""Get the name for a_callable for UI display.
126
If no name has been registered, the string 'No hook name' is returned.
127
We use a fixed string rather than repr or the callables module because
128
the code names are rarely meaningful for end users and this is not
129
intended for debugging.
131
return self._callable_names.get(a_callable, "No hook name")
133
@deprecated_method(one_five)
134
def install_hook(self, hook_name, a_callable):
135
"""Install a_callable in to the hook hook_name.
137
:param hook_name: A hook name. See the __init__ method of BranchHooks
138
for the complete list of hooks.
139
:param a_callable: The callable to be invoked when the hook triggers.
140
The exact signature will depend on the hook - see the __init__
141
method of BranchHooks for details on each hook.
143
self.install_named_hook(hook_name, a_callable, None)
145
def install_named_hook(self, hook_name, a_callable, name):
146
"""Install a_callable in to the hook hook_name, and label it name.
148
:param hook_name: A hook name. See the __init__ method of BranchHooks
149
for the complete list of hooks.
150
:param a_callable: The callable to be invoked when the hook triggers.
151
The exact signature will depend on the hook - see the __init__
152
method of BranchHooks for details on each hook.
153
:param name: A name to associate a_callable with, to show users what is
157
hook = self[hook_name]
159
raise errors.UnknownHook(self.__class__.__name__, hook_name)
161
# list hooks, old-style, not yet deprecated but less useful.
162
hook.append(a_callable)
163
except AttributeError:
164
hook.hook(a_callable, name)
166
self.name_hook(a_callable, name)
168
def name_hook(self, a_callable, name):
169
"""Associate name with a_callable to show users what is running."""
170
self._callable_names[a_callable] = name
173
class HookPoint(object):
174
"""A single hook that clients can register to be called back when it fires.
176
:ivar name: The name of the hook.
177
:ivar introduced: A version tuple specifying what version the hook was
178
introduced in. None indicates an unknown version.
179
:ivar deprecated: A version tuple specifying what version the hook was
180
deprecated or superceded in. None indicates that the hook is not
181
superceded or deprecated. If the hook is superceded then the doc
182
should describe the recommended replacement hook to register for.
183
:ivar doc: The docs for using the hook.
186
def __init__(self, name, doc, introduced, deprecated):
187
"""Create a HookPoint.
189
:param name: The name of the hook, for clients to use when registering.
190
:param doc: The docs for the hook.
191
:param introduced: When the hook was introduced (e.g. (0, 15)).
192
:param deprecated: When the hook was deprecated, None for
197
self.introduced = introduced
198
self.deprecated = deprecated
200
self._callback_names = {}
203
"""Generate the documentation for this HookPoint.
205
:return: A string terminated in \n.
208
strings.append(self.name)
209
strings.append('~'*len(self.name))
212
introduced_string = _format_version_tuple(self.introduced)
214
introduced_string = 'unknown'
215
strings.append('Introduced in: %s' % introduced_string)
217
deprecated_string = _format_version_tuple(self.deprecated)
219
deprecated_string = 'Not deprecated'
220
strings.append('Deprecated in: %s' % deprecated_string)
222
strings.extend(textwrap.wrap(self.__doc__))
224
return '\n'.join(strings)
226
def __eq__(self, other):
227
return (type(other) == type(self) and
228
other.__dict__ == self.__dict__)
230
def hook(self, callback, callback_label):
231
"""Register a callback to be called when this HookPoint fires.
233
:param callback: The callable to use when this HookPoint fires.
234
:param callback_label: A label to show in the UI while this callback is
237
self._callbacks.append(callback)
238
if callback_label is not None:
239
self._callback_names[callback] = callback_label
242
return iter(self._callbacks)
245
return len(self._callbacks)
249
strings.append("<%s(" % type(self).__name__)
250
strings.append(self.name)
251
strings.append("), callbacks=[")
252
for callback in self._callbacks:
253
strings.append(repr(callback))
255
strings.append(self._callback_names[callback])
257
if len(self._callbacks) == 1:
260
return ''.join(strings)
271
A hook of type *xxx* of class *yyy* needs to be registered using::
273
yyy.hooks.install_named_hook("xxx", ...)
275
See `Using hooks`_ in the User Guide for examples.
277
.. _Using hooks: ../user-guide/index.html#using-hooks
279
The class that contains each hook is given before the hooks it supplies. For
280
instance, BranchHooks as the class is the hooks class for
281
`bzrlib.branch.Branch.hooks`.
283
Each description also indicates whether the hook runs on the client (the
284
machine where bzr was invoked) or the server (the machine addressed by
285
the branch URL). These may be, but are not necessarily, the same machine.
287
Plugins (including hooks) are run on the server if all of these is true:
289
* The connection is via a smart server (accessed with a URL starting with
290
"bzr://", "bzr+ssh://" or "bzr+http://", or accessed via a "http://"
291
URL when a smart server is available via HTTP).
293
* The hook is either server specific or part of general infrastructure rather
294
than client specific code (such as commit).
298
def hooks_help_text(topic):
299
segments = [_help_prefix]
300
for hook_key in sorted(known_hooks.keys()):
301
hooks = known_hooks_key_to_object(hook_key)
302
segments.append(hooks.docs())
303
return '\n'.join(segments)