~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/doc_generate/autodoc_rstx.py

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright 2006 Canonical Ltd.
 
1
# Copyright (C) 2006-2007 Canonical Ltd
2
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
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
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
"""Generate ReStructuredText source for manual.
18
 
Based on manpage generator autodoc_man.py
19
 
 
20
 
Written by Alexander Belchenko
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Generate ReStructuredText source for the User Reference Manual.
 
18
Loosely based on the manpage generator autodoc_man.py.
 
19
 
 
20
Written by the Bazaar community.
21
21
"""
22
22
 
23
23
import os
24
24
import sys
25
 
import textwrap
26
25
import time
27
26
 
28
27
import bzrlib
29
28
import bzrlib.help
 
29
import bzrlib.help_topics
30
30
import bzrlib.commands
 
31
import bzrlib.osutils
 
32
 
 
33
 
 
34
# Set this to True to generate a file per topic.
 
35
# This probably ought to be an option. The files probably
 
36
# ought to be prefixed with their section name as well so
 
37
# there's zero risk of clashing with a standard sphinx
 
38
# topic (like search.html).
 
39
FILE_PER_TOPIC = False
31
40
 
32
41
 
33
42
def get_filename(options):
45
54
             "timestamp": time.strftime("%Y-%m-%d %H:%M:%S +0000",tt),
46
55
             "version": bzrlib.__version__,
47
56
             }
 
57
    nominated_filename = getattr(options, 'filename', None)
 
58
    if nominated_filename is None:
 
59
        topic_dir = None
 
60
    else:
 
61
        topic_dir = bzrlib.osutils.dirname(nominated_filename)
48
62
    outfile.write(rstx_preamble % params)
49
63
    outfile.write(rstx_head % params)
50
 
    outfile.write(getcommand_list(params))
51
 
    outfile.write(getcommand_help(params))
 
64
    outfile.write(_get_body(params, topic_dir))
52
65
    outfile.write(rstx_foot % params)
53
66
 
54
67
 
55
 
def command_name_list():
56
 
    """Builds a list of command names from bzrlib"""
57
 
    command_names = bzrlib.commands.builtin_command_names()
58
 
    command_names.sort()
59
 
    return command_names
60
 
 
61
 
 
62
 
def getcommand_list (params):
63
 
    """Builds summary help for command names in RSTX format"""
64
 
    bzrcmd = params["bzrcmd"]
65
 
    output = """
66
 
Command overview
67
 
================
68
 
"""
69
 
    for cmd_name in command_name_list():
70
 
        cmd_object = bzrlib.commands.get_cmd_object(cmd_name)
71
 
        if cmd_object.hidden:
72
 
            continue
73
 
        cmd_help = cmd_object.help()
74
 
        if cmd_help:
75
 
            firstline = cmd_help.split('\n', 1)[0]
76
 
            usage = cmd_object._usage()
77
 
            tmp = '**%s**\n\t%s\n\n' % (usage, firstline)
78
 
            output = output + tmp
79
 
        else:
80
 
            raise RuntimeError, "Command '%s' has no help text" % (cmd_name)
81
 
    return output
82
 
 
83
 
 
84
 
def getcommand_help(params):
85
 
    """Shows individual options for a bzr command"""
86
 
    output="""
87
 
Command reference
88
 
=================
89
 
"""
90
 
    for cmd_name in command_name_list():
91
 
        cmd_object = bzrlib.commands.get_cmd_object(cmd_name)
92
 
        if cmd_object.hidden:
93
 
            continue
94
 
        output = output + format_command(params, cmd_object, cmd_name)
95
 
    return output
96
 
 
97
 
 
98
 
def format_command (params, cmd, name):
99
 
    """Provides long help for each public command"""
100
 
    usage = cmd._usage()
101
 
    subsection_header = """
102
 
%s
103
 
%s
104
 
::
105
 
""" % (usage, '-'*len(usage))
106
 
 
107
 
    docsplit = cmd.help().split('\n')
108
 
    doc = '\n'.join([' '*4+line for line in docsplit])
109
 
        
110
 
    option_str = ""
111
 
    options = cmd.options()
112
 
    if options:
113
 
        option_str = "\n    Options:\n"
114
 
        for option_name, option in sorted(options.items()):
115
 
            for name, short_name, argname, help in option.iter_switches():
116
 
                l = '    --' + name
117
 
                if argname is not None:
118
 
                    l += ' ' + argname
119
 
                if short_name:
120
 
                    assert len(short_name) == 1
121
 
                    l += ', -' + short_name
122
 
                l += (30 - len(l)) * ' ' + (help or '')
123
 
                # TODO: Split help over multiple lines with
124
 
                # correct indenting and wrapping.
125
 
                wrapped = textwrap.fill(l, initial_indent='',
126
 
                                        subsequent_indent=30*' ')
127
 
                option_str = option_str + wrapped + '\n'       
128
 
 
129
 
    aliases_str = ""
130
 
    if cmd.aliases:
131
 
        if len(cmd.aliases) > 1:
132
 
            aliases_str += '\n    Aliases: '
133
 
        else:
134
 
            aliases_str += '\n    Alias: '
135
 
        aliases_str += ', '.join(cmd.aliases)
136
 
        aliases_str += '\n'
137
 
 
138
 
    see_also_str = ""
139
 
    see_also = cmd.get_see_also()
140
 
    if see_also:
141
 
        see_also_str += '\n    See also: '
142
 
        see_also_str += ', '.join(see_also)
143
 
        see_also_str += '\n'
144
 
 
145
 
    return subsection_header + option_str + aliases_str + see_also_str + "\n" + doc + "\n"
 
68
def _get_body(params, topic_dir):
 
69
    """Build the manual content."""
 
70
    from bzrlib.help_topics import SECT_CONCEPT, SECT_LIST, SECT_PLUGIN
 
71
    registry = bzrlib.help_topics.topic_registry
 
72
    result = []
 
73
    result.append(_get_section(registry, SECT_CONCEPT, "Concepts",
 
74
        output_dir=topic_dir))
 
75
    result.append(_get_section(registry, SECT_LIST, "Lists",
 
76
        output_dir=topic_dir))
 
77
    result.append(_get_commands_section(registry))
 
78
    #result.append(_get_section(registry, SECT_PLUGIN, "Standard Plug-ins"))
 
79
    return "\n".join(result)
 
80
 
 
81
 
 
82
def _get_section(registry, section, title, hdg_level1="#", hdg_level2="=",
 
83
        output_dir=None):
 
84
    """Build the manual part from topics matching that section.
 
85
    
 
86
    If output_dir is not None, topics are dumped into text files there
 
87
    during processing, as well as being included in the return result.
 
88
    """
 
89
    topics = sorted(registry.get_topics_for_section(section))
 
90
    lines = [title, hdg_level1 * len(title), ""]
 
91
 
 
92
    # docutils treats section heading as implicit link target.
 
93
    # But in some cases topic and heading are different, e.g.:
 
94
    #
 
95
    # `bugs' vs. `Bug Trackers'
 
96
    # `working-tree' vs. `Working Trees'
 
97
    #
 
98
    # So for building proper cross-reference between topic names
 
99
    # and corresponding sections in document, we need provide
 
100
    # simple glue in the form:
 
101
    #
 
102
    # .. _topic: `heading`_
 
103
    links_glue = []
 
104
 
 
105
    for topic in topics:
 
106
        help = registry.get_detail(topic)
 
107
        heading,text = help.split("\n", 1)
 
108
        lines.append(heading)
 
109
        if not text.startswith(hdg_level2):
 
110
            lines.append(hdg_level2 * len(heading))
 
111
        lines.append(text)
 
112
        lines.append('')
 
113
        # check that topic match heading
 
114
        if topic != heading.lower():
 
115
            links_glue.append((topic, heading))
 
116
        # dump the text if requested
 
117
        if output_dir is not None:
 
118
            out_file = bzrlib.osutils.pathjoin(output_dir, topic + ".txt")
 
119
            _dump_text(out_file, help)
 
120
 
 
121
    # provide links glue for topics that don't match headings
 
122
    lines.extend([".. _%s: `%s`_" % i for i in links_glue])
 
123
    lines.append('')
 
124
 
 
125
    return "\n" + "\n".join(lines) + "\n"
 
126
 
 
127
 
 
128
def _dump_text(filename, text):
 
129
    """Dump text to filename."""
 
130
    if not FILE_PER_TOPIC:
 
131
        return
 
132
    f =  open(filename, "w")
 
133
    f.writelines(text)
 
134
    f.close()
 
135
 
 
136
 
 
137
def _get_commands_section(registry, title="Commands", hdg_level1="#",
 
138
                          hdg_level2="="):
 
139
    """Build the commands reference section of the manual."""
 
140
    lines = [title, hdg_level1 * len(title), ""]
 
141
    cmds = sorted(bzrlib.commands.builtin_command_names())
 
142
    for cmd_name in cmds:
 
143
        cmd_object = bzrlib.commands.get_cmd_object(cmd_name)
 
144
        if cmd_object.hidden:
 
145
            continue
 
146
        heading = cmd_name
 
147
        text = cmd_object.get_help_text(plain=False, see_also_as_links=True)
 
148
        lines.append(heading)
 
149
        lines.append(hdg_level2 * len(heading))
 
150
        lines.append(text)
 
151
        lines.append('')
 
152
    return "\n" + "\n".join(lines) + "\n"
146
153
 
147
154
 
148
155
##
149
156
# TEMPLATES
150
157
 
151
 
rstx_preamble = """.. Large parts of this file are autogenerated from the output of
 
158
rstx_preamble = """.. This file is autogenerated from the output of
 
159
..     %(bzrcmd)s help topics
152
160
..     %(bzrcmd)s help commands
153
161
..     %(bzrcmd)s help <cmd>
154
162
..
155
163
.. Generation time: %(timestamp)s
156
164
 
157
 
=============================================
158
 
Man page for Bazaar (%(bzrcmd)s)
159
 
=============================================
160
 
 
161
 
:Date: %(datestamp)s
162
 
 
163
 
`Index <#id1>`_
164
 
 
165
 
-----
166
 
 
167
165
"""
168
166
 
169
167
 
170
168
rstx_head = """\
171
 
Name
172
 
====
173
 
Bazaar (%(bzrcmd)s) - next-generation distributed version control
174
 
 
175
 
Synopsis
176
 
========
177
 
**%(bzrcmd)s** *command* [ *command_options* ]
178
 
 
179
 
**%(bzrcmd)s help**
180
 
 
181
 
**%(bzrcmd)s help** *command*
182
 
 
183
 
 
184
 
Description
185
 
===========
186
 
Bazaar (or **%(bzrcmd)s**) is a project of Canonical to develop
187
 
an open source distributed version control system that is powerful,
188
 
friendly, and scalable. Version control means a system
189
 
that keeps track of previous revisions of software source code
190
 
or similar information and helps people work on it in teams.
 
169
#####################
 
170
Bazaar User Reference
 
171
#####################
 
172
 
 
173
About This Manual
 
174
#################
 
175
 
 
176
This manual is generated from Bazaar's online help. To use
 
177
the online help system, try the following commands.
 
178
 
 
179
    Introduction including a list of commonly used commands::
 
180
 
 
181
        bzr help
 
182
 
 
183
    List of topics and a summary of each::
 
184
 
 
185
        bzr help topics
 
186
 
 
187
    List of commands and a summary of each::
 
188
 
 
189
        bzr help commands
 
190
 
 
191
    More information about a particular topic or command::
 
192
 
 
193
        bzr help topic-or-command-name
 
194
 
 
195
The following web sites provide further information on Bazaar:
 
196
 
 
197
:Home page:                     http://www.bazaar-vcs.org/
 
198
:Official docs:                 http://doc.bazaar-vcs.org/
 
199
:Launchpad:                     https://launchpad.net/bzr/
191
200
"""
192
201
 
193
202
 
194
203
rstx_foot = """
195
 
Environment
196
 
===========
197
 
**BZRPATH**
198
 
                Path where **%(bzrcmd)s** is to look for shell plugin external commands.
199
 
 
200
 
**BZR_EMAIL**
201
 
                E-Mail address of the user. Overrides default user config.
202
 
 
203
 
**EMAIL**
204
 
                E-Mail address of the user. Overrides default user config.
205
 
 
206
 
**BZR_EDITOR**
207
 
                Editor for editing commit messages
208
 
 
209
 
**EDITOR**
210
 
                Editor for editing commit messages
211
 
 
212
 
**BZR_PLUGIN_PATH**
213
 
                Paths where bzr should look for plugins
214
 
 
215
 
**BZR_HOME**
216
 
                Home directory for bzr
217
 
 
218
 
 
219
 
Files
220
 
=====
221
 
 
222
 
**On Linux**:  ``~/.bazaar/bazaar.conf``
223
 
 
224
 
**On Windows**: ``C:\\Documents and Settings\\username\\Application Data\\bazaar\\2.0\\bazaar.conf``
225
 
 
226
 
Contains the user's default configuration. The section ``[DEFAULT]`` is
227
 
used to define general configuration that will be applied everywhere.
228
 
The section ``[ALIASES]`` can be used to create command aliases for
229
 
commonly used options.
230
 
 
231
 
A typical config file might look something like::
232
 
 
233
 
  [DEFAULT]
234
 
  email=John Doe <jdoe@isp.com>
235
 
 
236
 
  [ALIASES]
237
 
  commit = commit --strict
238
 
  log10 = log --short -r -10..-1
239
 
 
240
 
 
241
 
See also
242
 
========
243
 
http://www.bazaar-vcs.org/
244
 
 
245
 
--------------------
246
 
 
247
 
.. Contents::
248
 
    **Index**
249
204
"""