/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: John Arbash Meinel
  • Date: 2009-03-24 16:35:22 UTC
  • mto: This revision was merged to the branch mainline in revision 4198.
  • Revision ID: john@arbash-meinel.com-20090324163522-p0p9s5ahzsnem1oc
A few notes, some updates from ian.

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