~bzr-pqm/bzr/bzr.dev

3331.3.6 by Martin Pool
merge trunk
1
# Copyright (C) 2007, 2008 Canonical Ltd
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
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
3256.2.30 by Daniel Watkins
Updated deprecation warnings and tests.
20
from bzrlib.symbol_versioning import deprecated_method, one_five
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
21
lazy_import(globals(), """
4098.2.1 by Robert Collins
Allow self documenting hooks.
22
import textwrap
23
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
24
from bzrlib import (
4098.2.1 by Robert Collins
Allow self documenting hooks.
25
        _format_version_tuple,
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
26
        errors,
27
        )
28
""")
29
30
31
class Hooks(dict):
32
    """A dictionary mapping hook name to a list of callables.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
33
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
34
    e.g. ['FOO'] Is the list of items to be called when the
35
    FOO hook is triggered.
36
    """
37
2553.1.1 by Robert Collins
Give Hooks names.
38
    def __init__(self):
39
        dict.__init__(self)
40
        self._callable_names = {}
41
4098.2.1 by Robert Collins
Allow self documenting hooks.
42
    def create_hook(self, hook):
43
        """Create a hook which can have callbacks registered for it.
44
45
        :param hook: The hook to create. An object meeting the protocol of
4098.2.2 by Robert Collins
Review feedback.
46
            bzrlib.hooks.HookPoint. It's name is used as the key for future
4098.2.1 by Robert Collins
Allow self documenting hooks.
47
            lookups.
48
        """
49
        if hook.name in self:
50
            raise errors.DuplicateKey(hook.name)
51
        self[hook.name] = hook
52
53
    def docs(self):
54
        """Generate the documentation for this Hooks instance.
55
56
        This introspects all the individual hooks and returns their docs as well.
57
        """
58
        hook_names = sorted(self.keys())
59
        hook_docs = []
4108.3.1 by Robert Collins
Include the Hooks class in the Hooks docs.
60
        name = self.__class__.__name__
61
        hook_docs.append(name)
62
        hook_docs.append("="*len(name))
63
        hook_docs.append("")
4098.2.1 by Robert Collins
Allow self documenting hooks.
64
        for hook_name in hook_names:
65
            hook = self[hook_name]
66
            try:
67
                hook_docs.append(hook.docs())
68
            except AttributeError:
69
                # legacy hook
70
                strings = []
71
                strings.append(hook_name)
72
                strings.append("-" * len(hook_name))
73
                strings.append("")
74
                strings.append("An old-style hook. For documentation see the __init__ "
4108.3.1 by Robert Collins
Include the Hooks class in the Hooks docs.
75
                    "method of '%s'\n" % (name,))
4098.2.1 by Robert Collins
Allow self documenting hooks.
76
                hook_docs.extend(strings)
77
        return "\n".join(hook_docs)
78
2553.1.1 by Robert Collins
Give Hooks names.
79
    def get_hook_name(self, a_callable):
80
        """Get the name for a_callable for UI display.
81
82
        If no name has been registered, the string 'No hook name' is returned.
2553.1.3 by Robert Collins
Increase docs in response to review feedback.
83
        We use a fixed string rather than repr or the callables module because
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
84
        the code names are rarely meaningful for end users and this is not
2553.1.3 by Robert Collins
Increase docs in response to review feedback.
85
        intended for debugging.
2553.1.1 by Robert Collins
Give Hooks names.
86
        """
87
        return self._callable_names.get(a_callable, "No hook name")
88
3256.2.30 by Daniel Watkins
Updated deprecation warnings and tests.
89
    @deprecated_method(one_five)
3256.2.8 by Daniel Watkins
Alphabetised hooks.py.
90
    def install_hook(self, hook_name, a_callable):
91
        """Install a_callable in to the hook hook_name.
92
93
        :param hook_name: A hook name. See the __init__ method of BranchHooks
94
            for the complete list of hooks.
95
        :param a_callable: The callable to be invoked when the hook triggers.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
96
            The exact signature will depend on the hook - see the __init__
3256.2.8 by Daniel Watkins
Alphabetised hooks.py.
97
            method of BranchHooks for details on each hook.
98
        """
3256.2.11 by Daniel Watkins
Modified install_hook to call install_named_hook, as suggested by Aaron.
99
        self.install_named_hook(hook_name, a_callable, None)
3256.2.8 by Daniel Watkins
Alphabetised hooks.py.
100
3256.2.5 by Daniel Watkins
Added install_named_hook.
101
    def install_named_hook(self, hook_name, a_callable, name):
102
        """Install a_callable in to the hook hook_name, and label it name.
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
103
104
        :param hook_name: A hook name. See the __init__ method of BranchHooks
105
            for the complete list of hooks.
106
        :param a_callable: The callable to be invoked when the hook triggers.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
107
            The exact signature will depend on the hook - see the __init__
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
108
            method of BranchHooks for details on each hook.
3256.2.3 by Daniel Watkins
Added docs.
109
        :param name: A name to associate a_callable with, to show users what is
110
            running.
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
111
        """
112
        try:
4098.2.1 by Robert Collins
Allow self documenting hooks.
113
            hook = self[hook_name]
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
114
        except KeyError:
115
            raise errors.UnknownHook(self.__class__.__name__, hook_name)
4098.2.1 by Robert Collins
Allow self documenting hooks.
116
        try:
117
            # list hooks, old-style, not yet deprecated but less useful.
118
            hook.append(a_callable)
119
        except AttributeError:
120
            hook.hook(a_callable, name)
3256.2.10 by Daniel Watkins
Tightened exception scope, as suggested by Aaron.
121
        if name is not None:
122
            self.name_hook(a_callable, name)
2553.1.1 by Robert Collins
Give Hooks names.
123
124
    def name_hook(self, a_callable, name):
125
        """Associate name with a_callable to show users what is running."""
126
        self._callable_names[a_callable] = name
4098.2.1 by Robert Collins
Allow self documenting hooks.
127
128
4098.2.2 by Robert Collins
Review feedback.
129
class HookPoint(object):
4098.2.1 by Robert Collins
Allow self documenting hooks.
130
    """A single hook that clients can register to be called back when it fires.
131
132
    :ivar name: The name of the hook.
133
    :ivar introduced: A version tuple specifying what version the hook was
134
        introduced in. None indicates an unknown version.
135
    :ivar deprecated: A version tuple specifying what version the hook was
136
        deprecated or superceded in. None indicates that the hook is not
137
        superceded or deprecated. If the hook is superceded then the doc
138
        should describe the recommended replacement hook to register for.
139
    :ivar doc: The docs for using the hook.
140
    """
141
142
    def __init__(self, name, doc, introduced, deprecated):
4098.2.2 by Robert Collins
Review feedback.
143
        """Create a HookPoint.
4098.2.3 by Robert Collins
White space difference-of-opinion.
144
4098.2.1 by Robert Collins
Allow self documenting hooks.
145
        :param name: The name of the hook, for clients to use when registering.
146
        :param doc: The docs for the hook.
147
        :param introduced: When the hook was introduced (e.g. (0, 15)).
148
        :param deprecated: When the hook was deprecated, None for
149
            not-deprecated.
150
        """
151
        self.name = name
152
        self.__doc__ = doc
153
        self.introduced = introduced
154
        self.deprecated = deprecated
155
        self._callbacks = []
156
        self._callback_names = {}
157
158
    def docs(self):
4098.2.2 by Robert Collins
Review feedback.
159
        """Generate the documentation for this HookPoint.
4098.2.3 by Robert Collins
White space difference-of-opinion.
160
4098.2.1 by Robert Collins
Allow self documenting hooks.
161
        :return: A string terminated in \n.
162
        """
163
        strings = []
164
        strings.append(self.name)
165
        strings.append('-'*len(self.name))
166
        strings.append('')
167
        if self.introduced:
168
            introduced_string = _format_version_tuple(self.introduced)
169
        else:
170
            introduced_string = 'unknown'
171
        strings.append('Introduced in: %s' % introduced_string)
172
        if self.deprecated:
173
            deprecated_string = _format_version_tuple(self.deprecated)
174
        else:
175
            deprecated_string = 'Not deprecated'
176
        strings.append('Deprecated in: %s' % deprecated_string)
177
        strings.append('')
178
        strings.extend(textwrap.wrap(self.__doc__))
179
        strings.append('')
180
        return '\n'.join(strings)
181
182
    def hook(self, callback, callback_label):
4098.2.2 by Robert Collins
Review feedback.
183
        """Register a callback to be called when this HookPoint fires.
4098.2.1 by Robert Collins
Allow self documenting hooks.
184
4098.2.2 by Robert Collins
Review feedback.
185
        :param callback: The callable to use when this HookPoint fires.
4098.2.1 by Robert Collins
Allow self documenting hooks.
186
        :param callback_label: A label to show in the UI while this callback is
187
            processing.
188
        """
189
        self._callbacks.append(callback)
190
        self._callback_names[callback] = callback_label
191
192
    def __iter__(self):
193
        return iter(self._callbacks)
194
195
    def __repr__(self):
196
        strings = []
4098.2.2 by Robert Collins
Review feedback.
197
        strings.append("<%s(" % type(self).__name__)
4098.2.1 by Robert Collins
Allow self documenting hooks.
198
        strings.append(self.name)
199
        strings.append("), callbacks=[")
200
        for callback in self._callbacks:
201
            strings.append(repr(callback))
202
            strings.append("(")
203
            strings.append(self._callback_names[callback])
204
            strings.append("),")
205
        if len(self._callbacks) == 1:
206
            strings[-1] = ")"
207
        strings.append("]>")
208
        return ''.join(strings)