~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hooks.py

  • Committer: Martin Pool
  • Date: 2009-01-13 03:11:04 UTC
  • mto: This revision was merged to the branch mainline in revision 3937.
  • Revision ID: mbp@sourcefrog.net-20090113031104-03my054s02i9l2pe
Bump version to 1.12 and add news template

Show diffs side-by-side

added added

removed removed

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