~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hooks.py

  • Committer: John Arbash Meinel
  • Date: 2010-01-13 16:23:07 UTC
  • mto: (4634.119.7 2.0)
  • mto: This revision was merged to the branch mainline in revision 4959.
  • Revision ID: john@arbash-meinel.com-20100113162307-0bs82td16gzih827
Update the MANIFEST.in file.

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