/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: Martin Pool
  • Date: 2009-03-12 05:32:56 UTC
  • mfrom: (4124 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4140.
  • Revision ID: mbp@sourcefrog.net-20090312053256-071khr6k4wwuuyja
merge news

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.symbol_versioning import deprecated_method, one_five
 
21
lazy_import(globals(), """
 
22
import textwrap
 
23
 
 
24
from bzrlib import (
 
25
        _format_version_tuple,
 
26
        errors,
 
27
        )
 
28
""")
 
29
 
 
30
 
 
31
class Hooks(dict):
 
32
    """A dictionary mapping hook name to a list of callables.
 
33
 
 
34
    e.g. ['FOO'] Is the list of items to be called when the
 
35
    FOO hook is triggered.
 
36
    """
 
37
 
 
38
    def __init__(self):
 
39
        dict.__init__(self)
 
40
        self._callable_names = {}
 
41
 
 
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
 
46
            bzrlib.hooks.HookPoint. It's name is used as the key for future
 
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 = []
 
60
        name = self.__class__.__name__
 
61
        hook_docs.append(name)
 
62
        hook_docs.append("="*len(name))
 
63
        hook_docs.append("")
 
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__ "
 
75
                    "method of '%s'\n" % (name,))
 
76
                hook_docs.extend(strings)
 
77
        return "\n".join(hook_docs)
 
78
 
 
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.
 
83
        We use a fixed string rather than repr or the callables module because
 
84
        the code names are rarely meaningful for end users and this is not
 
85
        intended for debugging.
 
86
        """
 
87
        return self._callable_names.get(a_callable, "No hook name")
 
88
 
 
89
    @deprecated_method(one_five)
 
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.
 
96
            The exact signature will depend on the hook - see the __init__
 
97
            method of BranchHooks for details on each hook.
 
98
        """
 
99
        self.install_named_hook(hook_name, a_callable, None)
 
100
 
 
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.
 
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.
 
107
            The exact signature will depend on the hook - see the __init__
 
108
            method of BranchHooks for details on each hook.
 
109
        :param name: A name to associate a_callable with, to show users what is
 
110
            running.
 
111
        """
 
112
        try:
 
113
            hook = self[hook_name]
 
114
        except KeyError:
 
115
            raise errors.UnknownHook(self.__class__.__name__, hook_name)
 
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)
 
121
        if name is not None:
 
122
            self.name_hook(a_callable, name)
 
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
 
127
 
 
128
 
 
129
class HookPoint(object):
 
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):
 
143
        """Create a HookPoint.
 
144
 
 
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):
 
159
        """Generate the documentation for this HookPoint.
 
160
 
 
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):
 
183
        """Register a callback to be called when this HookPoint fires.
 
184
 
 
185
        :param callback: The callable to use when this HookPoint fires.
 
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 = []
 
197
        strings.append("<%s(" % type(self).__name__)
 
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)