~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/help.py

  • Committer: Wouter van Heyst
  • Date: 2006-06-07 16:05:27 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: larstiq@larstiq.dyndns.org-20060607160527-2b3649154d0e2e84
more code cleanup

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005, 2006 Canonical Ltd
2
 
#
 
1
# Copyright (C) 2004, 2005, 2006 by Canonical Ltd
 
2
 
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
#
 
12
 
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
20
# executable files with reasonable names.
21
21
 
22
22
# TODO: `help commands --all` should show hidden commands
 
23
import textwrap
 
24
 
 
25
global_help = \
 
26
"""Bazaar-NG -- a free distributed version-control tool
 
27
http://bazaar-vcs.org/
 
28
 
 
29
Basic commands:
 
30
 
 
31
  bzr init           makes this directory a versioned branch
 
32
  bzr branch         make a copy of another branch
 
33
 
 
34
  bzr add            make files or directories versioned
 
35
  bzr ignore         ignore a file or pattern
 
36
  bzr mv             move or rename a versioned file
 
37
 
 
38
  bzr status         summarize changes in working copy
 
39
  bzr diff           show detailed diffs
 
40
 
 
41
  bzr merge          pull in changes from another branch
 
42
  bzr commit         save some or all changes
 
43
 
 
44
  bzr log            show history of changes
 
45
  bzr check          validate storage
 
46
 
 
47
  bzr help init      more help on e.g. init command
 
48
  bzr help commands  list all commands
 
49
"""
 
50
 
23
51
 
24
52
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
 
    topics = indices.search(topic)
44
 
    shadowed_terms = []
45
 
    for index, topic in topics[1:]:
46
 
        shadowed_terms.append('%s%s' % (index.prefix, topic.get_help_topic()))
47
 
    outfile.write(topics[0][1].get_help_text(shadowed_terms))
 
53
 
 
54
 
 
55
def help(topic=None, outfile = None):
 
56
    if outfile == None:
 
57
        outfile = sys.stdout
 
58
    if topic == None:
 
59
        outfile.write(global_help)
 
60
    elif topic == 'commands':
 
61
        help_commands(outfile = outfile)
 
62
    else:
 
63
        help_on_command(topic, outfile = outfile)
 
64
 
 
65
 
 
66
def command_usage(cmd_object):
 
67
    """Return single-line grammar for command.
 
68
 
 
69
    Only describes arguments, not options.
 
70
    """
 
71
    s = 'bzr ' + cmd_object.name() + ' '
 
72
    for aname in cmd_object.takes_args:
 
73
        aname = aname.upper()
 
74
        if aname[-1] in ['$', '+']:
 
75
            aname = aname[:-1] + '...'
 
76
        elif aname[-1] == '?':
 
77
            aname = '[' + aname[:-1] + ']'
 
78
        elif aname[-1] == '*':
 
79
            aname = '[' + aname[:-1] + '...]'
 
80
        s += aname + ' '
 
81
            
 
82
    assert s[-1] == ' '
 
83
    s = s[:-1]
 
84
    
 
85
    return s
 
86
 
 
87
 
 
88
def help_on_command(cmdname, outfile=None):
 
89
    from bzrlib.commands import get_cmd_object
 
90
 
 
91
    cmdname = str(cmdname)
 
92
 
 
93
    if outfile == None:
 
94
        outfile = sys.stdout
 
95
 
 
96
    cmd_object = get_cmd_object(cmdname)
 
97
 
 
98
    doc = cmd_object.help()
 
99
    if doc == None:
 
100
        raise NotImplementedError("sorry, no detailed help yet for %r" % cmdname)
 
101
 
 
102
    print >>outfile, 'usage:', command_usage(cmd_object) 
 
103
 
 
104
    if cmd_object.aliases:
 
105
        print >>outfile, 'aliases:',
 
106
        print >>outfile, ', '.join(cmd_object.aliases)
 
107
 
 
108
    print >>outfile
 
109
 
 
110
    outfile.write(doc)
 
111
    if doc[-1] != '\n':
 
112
        outfile.write('\n')
 
113
    help_on_command_options(cmd_object, outfile)
 
114
 
 
115
 
 
116
def help_on_command_options(cmd, outfile=None):
 
117
    from bzrlib.option import Option
 
118
    options = cmd.options()
 
119
    if not options:
 
120
        return
 
121
    if outfile == None:
 
122
        outfile = sys.stdout
 
123
    outfile.write('\noptions:\n')
 
124
    for option_name, option in sorted(options.items()):
 
125
        l = '    --' + option_name
 
126
        if option.type is not None:
 
127
            l += ' ' + option.argname.upper()
 
128
        short_name = option.short_name()
 
129
        if short_name:
 
130
            assert len(short_name) == 1
 
131
            l += ', -' + short_name
 
132
        l += (30 - len(l)) * ' ' + option.help
 
133
        # TODO: split help over multiple lines with correct indenting and 
 
134
        # wrapping
 
135
        wrapped = textwrap.fill(l, initial_indent='', subsequent_indent=30*' ')
 
136
        outfile.write(wrapped + '\n')
48
137
 
49
138
 
50
139
def help_commands(outfile=None):
51
140
    """List all commands"""
52
 
    if outfile is None:
 
141
    from bzrlib.commands import (builtin_command_names,
 
142
                                 plugin_command_names,
 
143
                                 get_cmd_object)
 
144
 
 
145
    if outfile == None:
53
146
        outfile = sys.stdout
54
 
    outfile.write(_help_commands_to_text('commands'))
55
 
 
56
 
 
57
 
@symbol_versioning.deprecated_function(symbol_versioning.zero_sixteen)
58
 
def command_usage(cmd):
59
 
    return cmd._usage()
60
 
 
61
 
 
62
 
def _help_commands_to_text(topic):
63
 
    """Generate the help text for the list of commands"""
64
 
    out = []
65
 
    if topic == 'hidden-commands':
66
 
        hidden = True
67
 
    else:
68
 
        hidden = False
69
 
    names = set(_mod_commands.builtin_command_names()) # to eliminate duplicates
70
 
    names.update(_mod_commands.plugin_command_names())
71
 
    commands = ((n, _mod_commands.get_cmd_object(n)) for n in names)
72
 
    shown_commands = [(n, o) for n, o in commands if o.hidden == hidden]
73
 
    max_name = max(len(n) for n, o in shown_commands)
74
 
    indent = ' ' * (max_name + 1)
75
 
    width = osutils.terminal_width() - 1
76
 
 
77
 
    for cmd_name, cmd_object in sorted(shown_commands):
78
 
        plugin_name = cmd_object.plugin_name()
79
 
        if plugin_name is None:
80
 
            plugin_name = ''
81
 
        else:
82
 
            plugin_name = ' [%s]' % plugin_name
83
 
 
 
147
 
 
148
    names = set()                       # to eliminate duplicates
 
149
    names.update(builtin_command_names())
 
150
    names.update(plugin_command_names())
 
151
    names = list(names)
 
152
    names.sort()
 
153
 
 
154
    for cmd_name in names:
 
155
        cmd_object = get_cmd_object(cmd_name)
 
156
        if cmd_object.hidden:
 
157
            continue
 
158
        print >>outfile, command_usage(cmd_object)
84
159
        cmd_help = cmd_object.help()
85
160
        if cmd_help:
86
161
            firstline = cmd_help.split('\n', 1)[0]
87
 
        else:
88
 
            firstline = ''
89
 
        helpstring = '%-*s %s%s' % (max_name, cmd_name, firstline, plugin_name)
90
 
        lines = textwrap.wrap(helpstring, subsequent_indent=indent,
91
 
                              width=width)
92
 
        for line in lines:
93
 
            out.append(line + '\n')
94
 
    return ''.join(out)
95
 
 
96
 
 
97
 
help_topics.topic_registry.register("commands",
98
 
                                    _help_commands_to_text,
99
 
                                    "Basic help for all commands")
100
 
help_topics.topic_registry.register("hidden-commands",
101
 
                                    _help_commands_to_text,
102
 
                                    "All hidden commands")
103
 
 
104
 
 
105
 
class HelpIndices(object):
106
 
    """Maintainer of help topics across multiple indices.
107
 
    
108
 
    It is currently separate to the HelpTopicRegistry because of its ordered
109
 
    nature, but possibly we should instead structure it as a search within the
110
 
    registry and add ordering and searching facilities to the registry. The
111
 
    registry would probably need to be restructured to support that cleanly
112
 
    which is why this has been implemented in parallel even though it does as a
113
 
    result permit searching for help in indices which are not discoverable via
114
 
    'help topics'.
115
 
 
116
 
    Each index has a unique prefix string, such as "commands", and contains
117
 
    help topics which can be listed or searched.
118
 
    """
119
 
 
120
 
    def __init__(self):
121
 
        self.search_path = [
122
 
            help_topics.HelpTopicIndex(),
123
 
            _mod_commands.HelpCommandIndex(),
124
 
            plugin.PluginsHelpIndex(),
125
 
            ]
126
 
 
127
 
    def _check_prefix_uniqueness(self):
128
 
        """Ensure that the index collection is able to differentiate safely."""
129
 
        prefixes = {}
130
 
        for index in self.search_path:
131
 
            prefixes.setdefault(index.prefix, []).append(index)
132
 
        for prefix, indices in prefixes.items():
133
 
            if len(indices) > 1:
134
 
                raise errors.DuplicateHelpPrefix(prefix)
135
 
 
136
 
    def search(self, topic):
137
 
        """Search for topic across the help search path.
 
162
            print >>outfile, '        ' + firstline
138
163
        
139
 
        :param topic: A string naming the help topic to search for.
140
 
        :raises: NoHelpTopic if none of the indexs in search_path have topic.
141
 
        :return: A list of HelpTopics which matched 'topic'.
142
 
        """
143
 
        self._check_prefix_uniqueness()
144
 
        result = []
145
 
        for index in self.search_path:
146
 
            result.extend([(index, _topic) for _topic in index.get_topics(topic)])
147
 
        if not result:
148
 
            raise errors.NoHelpTopic(topic)
149
 
        else:
150
 
            return result