13
13
# You should have received a copy of the GNU General Public License
14
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
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
18
"""Support for plugin hooking logic."""
19
from bzrlib import registry
19
20
from bzrlib.lazy_import import lazy_import
21
from bzrlib.symbol_versioning import deprecated_method
20
22
lazy_import(globals(), """
21
25
from bzrlib import (
26
_format_version_tuple,
29
from bzrlib.help_topics import help_as_plain_text
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',
40
known_hooks.register_lazy(('bzrlib.bzrdir', 'BzrDir.hooks'), 'bzrlib.bzrdir',
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',
48
known_hooks.register_lazy(('bzrlib.merge', 'Merger.hooks'), 'bzrlib.merge',
50
known_hooks.register_lazy(('bzrlib.msgeditor', 'hooks'), 'bzrlib.msgeditor',
52
known_hooks.register_lazy(('bzrlib.mutabletree', 'MutableTree.hooks'),
53
'bzrlib.mutabletree', 'MutableTreeHooks')
54
known_hooks.register_lazy(('bzrlib.smart.client', '_SmartClient.hooks'),
55
'bzrlib.smart.client', 'SmartClientHooks')
56
known_hooks.register_lazy(('bzrlib.smart.server', 'SmartTCPServer.hooks'),
57
'bzrlib.smart.server', 'SmartServerHooks')
58
known_hooks.register_lazy(
59
('bzrlib.version_info_formats.format_rio', 'RioVersionInfoBuilder.hooks'),
60
'bzrlib.version_info_formats.format_rio', 'RioVersionInfoBuilderHooks')
61
known_hooks.register_lazy(
62
('bzrlib.merge_directive', '_BaseMergeDirective.hooks'),
63
'bzrlib.merge_directive', 'MergeDirectiveHooks')
66
def known_hooks_key_to_object((module_name, member_name)):
67
"""Convert a known_hooks key to a object.
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.
73
return registry._LazyObjectGetter(module_name, member_name).get_obj()
76
def known_hooks_key_to_parent_and_attribute((module_name, member_name)):
77
"""Convert a known_hooks key to a object.
79
:param key: A tuple (module_name, member_name) as found in the keys of
80
the known_hooks registry.
81
:return: The object this specifies.
83
member_list = member_name.rsplit('.', 1)
84
if len(member_list) == 2:
85
parent_name, attribute = member_list
88
attribute = member_name
89
parent = known_hooks_key_to_object((module_name, parent_name))
90
return parent, attribute
28
94
"""A dictionary mapping hook name to a list of callables.
30
96
e.g. ['FOO'] Is the list of items to be called when the
31
97
FOO hook is triggered.
34
def install_hook(self, hook_name, a_callable):
35
"""Install a_callable in to the hook hook_name.
102
self._callable_names = {}
104
def create_hook(self, hook):
105
"""Create a hook which can have callbacks registered for it.
107
:param hook: The hook to create. An object meeting the protocol of
108
bzrlib.hooks.HookPoint. It's name is used as the key for future
111
if hook.name in self:
112
raise errors.DuplicateKey(hook.name)
113
self[hook.name] = hook
116
"""Generate the documentation for this Hooks instance.
118
This introspects all the individual hooks and returns their docs as well.
120
hook_names = sorted(self.keys())
122
name = self.__class__.__name__
123
hook_docs.append(name)
124
hook_docs.append("-"*len(name))
126
for hook_name in hook_names:
127
hook = self[hook_name]
129
hook_docs.append(hook.docs())
130
except AttributeError:
133
strings.append(hook_name)
134
strings.append("~" * len(hook_name))
136
strings.append("An old-style hook. For documentation see the __init__ "
137
"method of '%s'\n" % (name,))
138
hook_docs.extend(strings)
139
return "\n".join(hook_docs)
141
def get_hook_name(self, a_callable):
142
"""Get the name for a_callable for UI display.
144
If no name has been registered, the string 'No hook name' is returned.
145
We use a fixed string rather than repr or the callables module because
146
the code names are rarely meaningful for end users and this is not
147
intended for debugging.
149
return self._callable_names.get(a_callable, "No hook name")
151
def install_named_hook(self, hook_name, a_callable, name):
152
"""Install a_callable in to the hook hook_name, and label it name.
37
154
:param hook_name: A hook name. See the __init__ method of BranchHooks
38
155
for the complete list of hooks.
39
156
:param a_callable: The callable to be invoked when the hook triggers.
40
The exact signature will depend on the hook - see the __init__
157
The exact signature will depend on the hook - see the __init__
41
158
method of BranchHooks for details on each hook.
159
:param name: A name to associate a_callable with, to show users what is
44
self[hook_name].append(a_callable)
163
hook = self[hook_name]
46
165
raise errors.UnknownHook(self.__class__.__name__, hook_name)
167
# list hooks, old-style, not yet deprecated but less useful.
168
hook.append(a_callable)
169
except AttributeError:
170
hook.hook(a_callable, name)
172
self.name_hook(a_callable, name)
174
def name_hook(self, a_callable, name):
175
"""Associate name with a_callable to show users what is running."""
176
self._callable_names[a_callable] = name
179
class HookPoint(object):
180
"""A single hook that clients can register to be called back when it fires.
182
:ivar name: The name of the hook.
183
:ivar introduced: A version tuple specifying what version the hook was
184
introduced in. None indicates an unknown version.
185
:ivar deprecated: A version tuple specifying what version the hook was
186
deprecated or superseded in. None indicates that the hook is not
187
superseded or deprecated. If the hook is superseded then the doc
188
should describe the recommended replacement hook to register for.
189
:ivar doc: The docs for using the hook.
192
def __init__(self, name, doc, introduced, deprecated):
193
"""Create a HookPoint.
195
:param name: The name of the hook, for clients to use when registering.
196
:param doc: The docs for the hook.
197
:param introduced: When the hook was introduced (e.g. (0, 15)).
198
:param deprecated: When the hook was deprecated, None for
203
self.introduced = introduced
204
self.deprecated = deprecated
206
self._callback_names = {}
209
"""Generate the documentation for this HookPoint.
211
:return: A string terminated in \n.
214
strings.append(self.name)
215
strings.append('~'*len(self.name))
218
introduced_string = _format_version_tuple(self.introduced)
220
introduced_string = 'unknown'
221
strings.append('Introduced in: %s' % introduced_string)
223
deprecated_string = _format_version_tuple(self.deprecated)
224
strings.append('Deprecated in: %s' % deprecated_string)
226
strings.extend(textwrap.wrap(self.__doc__,
227
break_long_words=False))
229
return '\n'.join(strings)
231
def __eq__(self, other):
232
return (type(other) == type(self) and
233
other.__dict__ == self.__dict__)
235
def hook(self, callback, callback_label):
236
"""Register a callback to be called when this HookPoint fires.
238
:param callback: The callable to use when this HookPoint fires.
239
:param callback_label: A label to show in the UI while this callback is
242
self._callbacks.append(callback)
243
if callback_label is not None:
244
self._callback_names[callback] = callback_label
247
return iter(self._callbacks)
250
return len(self._callbacks)
254
strings.append("<%s(" % type(self).__name__)
255
strings.append(self.name)
256
strings.append("), callbacks=[")
257
for callback in self._callbacks:
258
strings.append(repr(callback))
260
strings.append(self._callback_names[callback])
262
if len(self._callbacks) == 1:
265
return ''.join(strings)
276
A hook of type *xxx* of class *yyy* needs to be registered using::
278
yyy.hooks.install_named_hook("xxx", ...)
280
See `Using hooks`_ in the User Guide for examples.
282
.. _Using hooks: ../user-guide/hooks.html
284
The class that contains each hook is given before the hooks it supplies. For
285
instance, BranchHooks as the class is the hooks class for
286
`bzrlib.branch.Branch.hooks`.
288
Each description also indicates whether the hook runs on the client (the
289
machine where bzr was invoked) or the server (the machine addressed by
290
the branch URL). These may be, but are not necessarily, the same machine.
292
Plugins (including hooks) are run on the server if all of these is true:
294
* The connection is via a smart server (accessed with a URL starting with
295
"bzr://", "bzr+ssh://" or "bzr+http://", or accessed via a "http://"
296
URL when a smart server is available via HTTP).
298
* The hook is either server specific or part of general infrastructure rather
299
than client specific code (such as commit).
303
def hooks_help_text(topic):
304
segments = [_help_prefix]
305
for hook_key in sorted(known_hooks.keys()):
306
hooks = known_hooks_key_to_object(hook_key)
307
segments.append(hooks.docs())
308
return '\n'.join(segments)