/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: Robert Collins
  • Author(s): Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
  • Date: 2009-04-07 05:42:28 UTC
  • mto: This revision was merged to the branch mainline in revision 4261.
  • Revision ID: robertc@robertcollins.net-20090407054228-zslrfatxy9nw231i
Groupcompress from brisbane-core.

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