~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/help.py

Some code cleanup passes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2004, 2005, 2006 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
# TODO: Some way to get a list of external commands (defined by shell
 
18
# scripts) so that they can be included in the help listing as well.
 
19
# It should be enough to just list the plugin directory and look for
 
20
# executable files with reasonable names.
 
21
 
 
22
# TODO: `help commands --all` should show hidden commands
 
23
 
 
24
import sys
 
25
import textwrap
 
26
 
 
27
from bzrlib import (
 
28
    commands as _mod_commands,
 
29
    errors,
 
30
    help_topics,
 
31
    osutils,
 
32
    plugin,
 
33
    symbol_versioning,
 
34
    )
 
35
 
 
36
 
 
37
def help(topic=None, outfile=None):
 
38
    """Write the help for the specific topic to outfile"""
 
39
    if outfile is None:
 
40
        outfile = sys.stdout
 
41
 
 
42
    indices = HelpIndices()
 
43
 
 
44
    alias = _mod_commands.get_alias(topic)
 
45
    try:
 
46
        topics = indices.search(topic)
 
47
        shadowed_terms = []
 
48
        for index, topic in topics[1:]:
 
49
            shadowed_terms.append('%s%s' % (index.prefix,
 
50
                topic.get_help_topic()))
 
51
        source = topics[0][1]
 
52
        outfile.write(source.get_help_text(shadowed_terms))
 
53
    except errors.NoHelpTopic:
 
54
        if alias is None:
 
55
            raise
 
56
 
 
57
    if alias is not None:
 
58
        outfile.write("'bzr %s' is an alias for 'bzr %s'.\n" % (topic,
 
59
            " ".join(alias)))
 
60
 
 
61
 
 
62
def help_commands(outfile=None):
 
63
    """List all commands"""
 
64
    if outfile is None:
 
65
        outfile = sys.stdout
 
66
    outfile.write(_help_commands_to_text('commands'))
 
67
 
 
68
 
 
69
def _help_commands_to_text(topic):
 
70
    """Generate the help text for the list of commands"""
 
71
    out = []
 
72
    if topic == 'hidden-commands':
 
73
        hidden = True
 
74
    else:
 
75
        hidden = False
 
76
    names = list(_mod_commands.all_command_names())
 
77
    commands = ((n, _mod_commands.get_cmd_object(n)) for n in names)
 
78
    shown_commands = [(n, o) for n, o in commands if o.hidden == hidden]
 
79
    max_name = max(len(n) for n, o in shown_commands)
 
80
    indent = ' ' * (max_name + 1)
 
81
    width = osutils.terminal_width() - 1
 
82
 
 
83
    for cmd_name, cmd_object in sorted(shown_commands):
 
84
        plugin_name = cmd_object.plugin_name()
 
85
        if plugin_name is None:
 
86
            plugin_name = ''
 
87
        else:
 
88
            plugin_name = ' [%s]' % plugin_name
 
89
 
 
90
        cmd_help = cmd_object.help()
 
91
        if cmd_help:
 
92
            firstline = cmd_help.split('\n', 1)[0]
 
93
        else:
 
94
            firstline = ''
 
95
        helpstring = '%-*s %s%s' % (max_name, cmd_name, firstline, plugin_name)
 
96
        lines = textwrap.wrap(
 
97
            helpstring, subsequent_indent=indent,
 
98
            width=width,
 
99
            break_long_words=False)
 
100
        for line in lines:
 
101
            out.append(line + '\n')
 
102
    return ''.join(out)
 
103
 
 
104
 
 
105
help_topics.topic_registry.register("commands",
 
106
                                    _help_commands_to_text,
 
107
                                    "Basic help for all commands",
 
108
                                    help_topics.SECT_HIDDEN)
 
109
help_topics.topic_registry.register("hidden-commands",
 
110
                                    _help_commands_to_text,
 
111
                                    "All hidden commands",
 
112
                                    help_topics.SECT_HIDDEN)
 
113
 
 
114
 
 
115
class HelpIndices(object):
 
116
    """Maintainer of help topics across multiple indices.
 
117
 
 
118
    It is currently separate to the HelpTopicRegistry because of its ordered
 
119
    nature, but possibly we should instead structure it as a search within the
 
120
    registry and add ordering and searching facilities to the registry. The
 
121
    registry would probably need to be restructured to support that cleanly
 
122
    which is why this has been implemented in parallel even though it does as a
 
123
    result permit searching for help in indices which are not discoverable via
 
124
    'help topics'.
 
125
 
 
126
    Each index has a unique prefix string, such as "commands", and contains
 
127
    help topics which can be listed or searched.
 
128
    """
 
129
 
 
130
    def __init__(self):
 
131
        self.search_path = [
 
132
            help_topics.HelpTopicIndex(),
 
133
            _mod_commands.HelpCommandIndex(),
 
134
            plugin.PluginsHelpIndex(),
 
135
            ]
 
136
 
 
137
    def _check_prefix_uniqueness(self):
 
138
        """Ensure that the index collection is able to differentiate safely."""
 
139
        prefixes = {}
 
140
        for index in self.search_path:
 
141
            prefixes.setdefault(index.prefix, []).append(index)
 
142
        for prefix, indices in prefixes.items():
 
143
            if len(indices) > 1:
 
144
                raise errors.DuplicateHelpPrefix(prefix)
 
145
 
 
146
    def search(self, topic):
 
147
        """Search for topic across the help search path.
 
148
 
 
149
        :param topic: A string naming the help topic to search for.
 
150
        :raises: NoHelpTopic if none of the indexs in search_path have topic.
 
151
        :return: A list of HelpTopics which matched 'topic'.
 
152
        """
 
153
        self._check_prefix_uniqueness()
 
154
        result = []
 
155
        for index in self.search_path:
 
156
            result.extend([(index, _topic) for _topic in index.get_topics(topic)])
 
157
        if not result:
 
158
            raise errors.NoHelpTopic(topic)
 
159
        else:
 
160
            return result