~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/doc_generate/autodoc_man.py

(vila) Rename assertWarns in test_config to avoid clashing with unittest2
 assertWarns. (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
2
 
 
3
 
# Copyright (C) 2005 by Hans Ulrich Niedermann
4
 
# Portions Copyright (C) 2005 by Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
5
2
 
6
3
# This program is free software; you can redistribute it and/or modify
7
4
# it under the terms of the GNU General Public License as published by
8
5
# the Free Software Foundation; either version 2 of the License, or
9
6
# (at your option) any later version.
10
 
 
 
7
#
11
8
# This program is distributed in the hope that it will be useful,
12
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
11
# GNU General Public License for more details.
15
 
 
 
12
#
16
13
# You should have received a copy of the GNU General Public License
17
14
# along with this program; if not, write to the Free Software
18
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
 
 
20
 
#<<< code taken from bzr (C) Canonical
21
 
 
22
 
import os, sys
23
 
 
24
 
import bzrlib, bzrlib.help
25
 
 
26
 
#>>> code taken from bzr (C) Canonical
27
 
 
28
 
#<<< code by HUN
29
 
 
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""man.py - create man page from built-in bzr help and static text
 
18
 
 
19
TODO:
 
20
  * use usage information instead of simple "bzr foo" in COMMAND OVERVIEW
 
21
  * add command aliases
 
22
"""
 
23
 
 
24
from __future__ import absolute_import
 
25
 
 
26
PLUGINS_TO_DOCUMENT = ["launchpad"]
 
27
 
 
28
import textwrap
30
29
import time
31
 
import re
 
30
 
 
31
import bzrlib
 
32
import bzrlib.help
 
33
import bzrlib.help_topics
 
34
import bzrlib.commands
 
35
 
 
36
from bzrlib.plugin import load_plugins
 
37
load_plugins()
 
38
 
 
39
 
 
40
def get_filename(options):
 
41
    """Provides name of manpage"""
 
42
    return "%s.1" % (options.bzr_name)
 
43
 
 
44
 
 
45
def infogen(options, outfile):
 
46
    """Assembles a man page"""
 
47
    t = time.time()
 
48
    tt = time.gmtime(t)
 
49
    params = \
 
50
           { "bzrcmd": options.bzr_name,
 
51
             "datestamp": time.strftime("%Y-%m-%d",tt),
 
52
             "timestamp": time.strftime("%Y-%m-%d %H:%M:%S +0000",tt),
 
53
             "version": bzrlib.__version__,
 
54
             }
 
55
    outfile.write(man_preamble % params)
 
56
    outfile.write(man_escape(man_head % params))
 
57
    outfile.write(man_escape(getcommand_list(params)))
 
58
    outfile.write(man_escape(getcommand_help(params)))
 
59
    outfile.write("".join(environment_variables()))
 
60
    outfile.write(man_escape(man_foot % params))
32
61
 
33
62
 
34
63
def man_escape(string):
 
64
    """Escapes strings for man page compatibility"""
35
65
    result = string.replace("\\","\\\\")
36
 
    result = result.replace("`","\\`")
37
 
    result = result.replace("'","\\'")
 
66
    result = result.replace("`","\\'")
 
67
    result = result.replace("'","\\*(Aq")
38
68
    result = result.replace("-","\\-")
39
69
    return result
40
70
 
41
71
 
42
 
class Parser:
43
 
 
44
 
    def parse_line(self, line):
45
 
        pass
46
 
 
47
 
 
48
 
class CommandListParser(Parser):
49
 
 
50
 
    """Parser for output of "bzr help commands".
51
 
 
52
 
    The parsed content can then be used to
53
 
    - write a "COMMAND OVERVIEW" section into a man page
54
 
    - provide a list of all commands
55
 
    """
56
 
 
57
 
    def __init__(self,params):
58
 
        self.params = params
59
 
        self.command_usage = []
60
 
        self.all_commands = []
61
 
        self.usage_exp = re.compile("([a-z0-9-]+).*")
62
 
        self.descr_exp = re.compile("    ([A-Z].*)\s*")
63
 
        self.state = 0
64
 
        self.command = None
65
 
        self.usage = None
66
 
        self.descr = None
67
 
 
68
 
    def parse_line(self, line):
69
 
        m = self.usage_exp.match(line)
70
 
        if line == '':
71
 
                return
72
 
        if m:
73
 
            if self.state == 0:
74
 
                if self.usage:
75
 
                    self.command_usage.append((self.command,self.usage,self.descr))
76
 
                    self.all_commands.append(self.command)
77
 
                self.usage = " ".join(line.split(" ")[1:])
78
 
                self.command = m.groups()[0]
79
 
            else:
80
 
                raise RuntimeError, "matching usage line in state %d" % state
81
 
            self.state = 1
82
 
            return
83
 
        m = self.descr_exp.match(line)
84
 
        if m:
85
 
            if self.state == 1:
86
 
                self.descr = m.groups()[0]
87
 
            else:
88
 
                raise RuntimeError, "matching descr line in state %d" % state
89
 
            self.state = 0
90
 
            return
91
 
        raise RuntimeError, "Cannot parse this line ('%s')." % line
92
 
 
93
 
    def end_parse(self):
94
 
        if self.state == 0:
95
 
            if self.usage:
96
 
                self.command_usage.append((self.command,self.usage,self.descr))
97
 
                self.all_commands.append(self.command)
98
 
        else:
99
 
            raise RuntimeError, "ending parse in state %d" % state
100
 
 
101
 
    def write_to_manpage(self, outfile):
102
 
        bzrcmd = self.params["bzrcmd"]
103
 
        outfile.write('.SH "COMMAND OVERVIEW"\n')
104
 
        for (command,usage,descr) in self.command_usage:
105
 
            outfile.write('.TP\n.B "%s %s"\n%s\n' % (bzrcmd, usage, descr))
106
 
 
107
 
 
108
 
class HelpReader:
109
 
 
110
 
    def __init__(self, parser):
111
 
        self.parser = parser
112
 
 
113
 
    def write(self, data):
114
 
        if data[-1] == '\n':
115
 
            data = data[:-1]
116
 
        for line in data.split('\n'):
117
 
            self.parser.parse_line(line)
118
 
 
119
 
 
120
 
def write_command_details(params, command, usage, descr, outfile):
121
 
    x = ('.SS "%s %s"\n.B "%s"\n.PP\n.B "Usage:"\n%s %s\n\n' %
122
 
         (params["bzrcmd"],
123
 
          command,
124
 
          descr,
125
 
          params["bzrcmd"],
126
 
          usage))
127
 
    outfile.write(man_escape(x))
 
72
def command_name_list():
 
73
    """Builds a list of command names from bzrlib"""
 
74
    command_names = bzrlib.commands.builtin_command_names()
 
75
    for cmdname in bzrlib.commands.plugin_command_names():
 
76
        cmd_object = bzrlib.commands.get_cmd_object(cmdname)
 
77
        if (PLUGINS_TO_DOCUMENT is None or
 
78
            cmd_object.plugin_name() in PLUGINS_TO_DOCUMENT):
 
79
            command_names.append(cmdname)
 
80
    command_names.sort()
 
81
    return command_names
 
82
 
 
83
 
 
84
def getcommand_list (params):
 
85
    """Builds summary help for command names in manpage format"""
 
86
    bzrcmd = params["bzrcmd"]
 
87
    output = '.SH "COMMAND OVERVIEW"\n'
 
88
    for cmd_name in command_name_list():
 
89
        cmd_object = bzrlib.commands.get_cmd_object(cmd_name)
 
90
        if cmd_object.hidden:
 
91
            continue
 
92
        cmd_help = cmd_object.help()
 
93
        if cmd_help:
 
94
            firstline = cmd_help.split('\n', 1)[0]
 
95
            usage = cmd_object._usage()
 
96
            tmp = '.TP\n.B "%s"\n%s\n' % (usage, firstline)
 
97
            output = output + tmp
 
98
        else:
 
99
            raise RuntimeError, "Command '%s' has no help text" % (cmd_name)
 
100
    return output
 
101
 
 
102
 
 
103
def getcommand_help(params):
 
104
    """Shows individual options for a bzr command"""
 
105
    output='.SH "COMMAND REFERENCE"\n'
 
106
    formatted = {}
 
107
    for cmd_name in command_name_list():
 
108
        cmd_object = bzrlib.commands.get_cmd_object(cmd_name)
 
109
        if cmd_object.hidden:
 
110
            continue
 
111
        formatted[cmd_name] = format_command(params, cmd_object)
 
112
        for alias in cmd_object.aliases:
 
113
            formatted[alias] = format_alias(params, alias, cmd_name)
 
114
    for cmd_name in sorted(formatted):
 
115
        output += formatted[cmd_name]
 
116
    return output
 
117
 
 
118
 
 
119
def format_command(params, cmd):
 
120
    """Provides long help for each public command"""
 
121
    subsection_header = '.SS "%s"\n' % (cmd._usage())
 
122
    doc = "%s\n" % (cmd.__doc__)
 
123
    doc = bzrlib.help_topics.help_as_plain_text(cmd.help())
 
124
 
 
125
    # A dot at the beginning of a line is interpreted as a macro.
 
126
    # Simply join lines that begin with a dot with the previous
 
127
    # line to work around this.
 
128
    doc = doc.replace("\n.", ".")
 
129
 
 
130
    option_str = ""
 
131
    options = cmd.options()
 
132
    if options:
 
133
        option_str = "\nOptions:\n"
 
134
        for option_name, option in sorted(options.items()):
 
135
            for name, short_name, argname, help in option.iter_switches():
 
136
                if option.is_hidden(name):
 
137
                    continue
 
138
                l = '    --' + name
 
139
                if argname is not None:
 
140
                    l += ' ' + argname
 
141
                if short_name:
 
142
                    l += ', -' + short_name
 
143
                l += (30 - len(l)) * ' ' + (help or '')
 
144
                wrapped = textwrap.fill(l, initial_indent='',
 
145
                    subsequent_indent=30*' ',
 
146
                    break_long_words=False,
 
147
                    )
 
148
                option_str += wrapped + '\n'
 
149
 
 
150
    aliases_str = ""
 
151
    if cmd.aliases:
 
152
        if len(cmd.aliases) > 1:
 
153
            aliases_str += '\nAliases: '
 
154
        else:
 
155
            aliases_str += '\nAlias: '
 
156
        aliases_str += ', '.join(cmd.aliases)
 
157
        aliases_str += '\n'
 
158
 
 
159
    see_also_str = ""
 
160
    see_also = cmd.get_see_also()
 
161
    if see_also:
 
162
        see_also_str += '\nSee also: '
 
163
        see_also_str += ', '.join(see_also)
 
164
        see_also_str += '\n'
 
165
 
 
166
    return subsection_header + option_str + aliases_str + see_also_str + "\n" + doc + "\n"
 
167
 
 
168
 
 
169
def format_alias(params, alias, cmd_name):
 
170
    help = '.SS "bzr %s"\n' % alias
 
171
    help += 'Alias for "%s", see "bzr %s".\n' % (cmd_name, cmd_name)
 
172
    return help
 
173
 
 
174
 
 
175
def environment_variables():
 
176
    yield ".SH \"ENVIRONMENT\"\n"
 
177
 
 
178
    from bzrlib.help_topics import known_env_variables
 
179
    for k, desc in known_env_variables:
 
180
        yield ".TP\n"
 
181
        yield ".I \"%s\"\n" % k
 
182
        yield man_escape(desc) + "\n"
128
183
 
129
184
 
130
185
man_preamble = """\
131
 
.\\\" Man page for %(bzrcmd)s (bazaar-ng)
 
186
.\\\"Man page for Bazaar (%(bzrcmd)s)
132
187
.\\\"
133
188
.\\\" Large parts of this file are autogenerated from the output of
134
189
.\\\"     \"%(bzrcmd)s help commands\"
135
190
.\\\"     \"%(bzrcmd)s help <cmd>\"
136
191
.\\\"
137
 
.\\\" Generation time: %(timestamp)s
138
 
.\\\"
 
192
 
 
193
.ie \\n(.g .ds Aq \\(aq
 
194
.el .ds Aq '
139
195
"""
140
196
 
141
 
# The DESCRIPTION text was taken from http://www.bazaar-ng.org/
142
 
# and is thus (C) Canonical
 
197
 
143
198
man_head = """\
144
 
.TH bzr 1 "%(datestamp)s" "%(version)s" "bazaar-ng"
 
199
.TH bzr 1 "%(datestamp)s" "%(version)s" "Bazaar"
145
200
.SH "NAME"
146
 
%(bzrcmd)s - bazaar-ng next-generation distributed version control
 
201
%(bzrcmd)s - Bazaar next-generation distributed version control
147
202
.SH "SYNOPSIS"
148
203
.B "%(bzrcmd)s"
149
204
.I "command"
158
213
.B "help"
159
214
.I "command"
160
215
.SH "DESCRIPTION"
161
 
bazaar-ng (or
162
 
.B "%(bzrcmd)s"
163
 
) is a project of Canonical to develop an open source distributed version control system that is powerful, friendly, and scalable. Version control means a system that keeps track of previous revisions of software source code or similar information and helps people work on it in teams.
164
 
.SS "Warning"
165
 
bazaar-ng is at an early stage of development, and the design is still changing from week to week. This man page here may be inconsistent with itself, with other documentation or with the code, and sometimes refer to features that are planned but not yet written. Comments are still very welcome; please send them to bazaar-ng@lists.canonical.com.
 
216
 
 
217
Bazaar (or %(bzrcmd)s) is a distributed version control system that is powerful, 
 
218
friendly, and scalable.  Bazaar is a project of Canonical Ltd and part of 
 
219
the GNU Project to develop a free operating system.
 
220
 
 
221
Bazaar keeps track of changes to software source code (or similar information);
 
222
lets you explore who changed it, when, and why; merges concurrent changes; and
 
223
helps people work together in a team.
166
224
"""
167
225
 
168
226
man_foot = """\
169
 
.SH "ENVIRONMENT"
170
 
.TP
171
 
.I "BZRPATH"
172
 
Path where
173
 
.B "%(bzrcmd)s"
174
 
is to look for external command.
175
 
.TP
176
 
.I "BZREMAIL"
177
 
E-Mail address of the user. Overrides
178
 
.I "~/.bzr.conf/email" and
179
 
.IR "EMAIL" .
180
 
Example content:
181
 
.I "John Doe <john@example.com>"
182
 
.TP
183
 
.I "EMAIL"
184
 
E-Mail address of the user. Overridden by the content of the file
185
 
.I "~/.bzr.conf/email"
186
 
and of the environment variable
187
 
.IR "BZREMAIL" .
188
227
.SH "FILES"
189
228
.TP
190
 
.I "~/.bzr.conf/"
191
 
Directory where all the user\'s settings are stored.
192
 
.TP
193
 
.I "~/.bzr.conf/email"
194
 
Stores name and email address of the user. Overrides content of
195
 
.I "EMAIL"
196
 
environment variable. Example content:
197
 
.I "John Doe <john@example.com>"
 
229
.I "~/.bazaar/bazaar.conf"
 
230
Contains the user's default configuration. The section
 
231
.B [DEFAULT]
 
232
is used to define general configuration that will be applied everywhere.
 
233
The section
 
234
.B [ALIASES]
 
235
can be used to create command aliases for
 
236
commonly used options.
 
237
 
 
238
A typical config file might look something like:
 
239
 
 
240
.br
 
241
[DEFAULT]
 
242
.br
 
243
email=John Doe <jdoe@isp.com>
 
244
.br
 
245
[ALIASES]
 
246
.br
 
247
commit = commit --strict
 
248
.br
 
249
log10 = log --short -r -10..-1
198
250
.SH "SEE ALSO"
199
 
.UR http://www.bazaar-ng.org/
200
 
.BR http://www.bazaar-ng.org/,
201
 
.UR http://www.bazaar-ng.org/doc/
202
 
.BR http://www.bazaar-ng.org/doc/
 
251
.UR http://bazaar.canonical.com/
 
252
.BR http://bazaar.canonical.com/
203
253
"""
204
254
 
205
 
def main(args=[]):
206
 
    """ main function
207
 
    :param  args:   command-line arguments (sys.argv[1:])
208
 
    :type   args:   list
209
 
    """
210
 
    t = time.time()
211
 
    tt = time.gmtime(t)
212
 
    params = \
213
 
           { "bzrcmd": "bzr",
214
 
             "datestamp": time.strftime("%Y-%m-%d",tt),
215
 
             "timestamp": time.strftime("%Y-%m-%d %H:%M:%S +0000",tt),
216
 
             "version": bzrlib.__version__,
217
 
             }
218
 
 
219
 
    clp = CommandListParser(params)
220
 
    bzrlib.help.help("commands", outfile=HelpReader(clp))
221
 
    clp.end_parse()
222
 
 
223
 
    filename = "bzr.1"
224
 
    if len(args) == 1:
225
 
        filename = args[0]
226
 
    if filename == "-":
227
 
        outfile = sys.stdout
228
 
    else:
229
 
        outfile = open(filename,"w")
230
 
 
231
 
    outfile.write(man_preamble % params)
232
 
    outfile.write(man_escape(man_head % params))
233
 
    clp.write_to_manpage(outfile)
234
 
 
235
 
    # FIXME:
236
 
    #   This doesn't do more than the summary so far.
237
 
    #outfile.write('.SH "DETAILED COMMAND DESCRIPTION"\n')
238
 
    #for (command,usage,descr) in clp.command_usage:
239
 
    #    write_command_details(params, command, usage, descr, outfile = outfile)
240
 
 
241
 
    outfile.write(man_escape(man_foot % params))
242
 
 
243
 
 
244
 
if __name__ == '__main__':
245
 
    main(sys.argv[1:])
246
 
 
247
 
 
248
 
#>>> code by HUN