~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzr_man.py

 * bzr add now lists how many files were ignored per glob.  add --verbose
   lists the specific files.  (Aaron Bentley)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright 2005 Canonical Ltd.
 
1
#!/usr/bin/python
 
2
 
 
3
# Copyright (C) 2005 by Hans Ulrich Niedermann
 
4
# Portions Copyright (C) 2005 by Canonical Ltd
2
5
 
3
6
# This program is free software; you can redistribute it and/or modify
4
7
# it under the terms of the GNU General Public License as published by
14
17
# along with this program; if not, write to the Free Software
15
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
19
 
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
 
import os
25
 
import sys
26
 
import textwrap
 
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
 
27
30
import time
28
 
 
29
 
import bzrlib
30
 
import bzrlib.help
31
 
import bzrlib.commands
32
 
 
33
 
 
34
 
def get_filename(options):
35
 
    """Provides name of manpage"""
36
 
    return "%s.1" % (options.bzr_name)
37
 
 
38
 
 
39
 
def infogen(options, outfile):
40
 
    """Assembles a man page"""
41
 
    t = time.time()
42
 
    tt = time.gmtime(t)
43
 
    params = \
44
 
           { "bzrcmd": options.bzr_name,
45
 
             "datestamp": time.strftime("%Y-%m-%d",tt),
46
 
             "timestamp": time.strftime("%Y-%m-%d %H:%M:%S +0000",tt),
47
 
             "version": bzrlib.__version__,
48
 
             }
49
 
    outfile.write(man_preamble % params)
50
 
    outfile.write(man_escape(man_head % params))
51
 
    outfile.write(man_escape(getcommand_list(params)))
52
 
    outfile.write(man_escape(getcommand_help(params)))
53
 
    outfile.write(man_escape(man_foot % params))
 
31
import re
54
32
 
55
33
 
56
34
def man_escape(string):
57
 
    """Escapes strings for man page compatibility"""
58
35
    result = string.replace("\\","\\\\")
59
36
    result = result.replace("`","\\`")
60
37
    result = result.replace("'","\\'")
62
39
    return result
63
40
 
64
41
 
65
 
def command_name_list():
66
 
    """Builds a list of command names from bzrlib"""
67
 
    command_names = bzrlib.commands.builtin_command_names()
68
 
    command_names.sort()
69
 
    return command_names
70
 
 
71
 
 
72
 
def getcommand_list (params):
73
 
    """Builds summary help for command names in manpage format"""
74
 
    bzrcmd = params["bzrcmd"]
75
 
    output = '.SH "COMMAND OVERVIEW"\n'
76
 
    for cmd_name in command_name_list():
77
 
        cmd_object = bzrlib.commands.get_cmd_object(cmd_name)
78
 
        if cmd_object.hidden:
79
 
            continue
80
 
        cmd_help = cmd_object.help()
81
 
        if cmd_help:
82
 
            firstline = cmd_help.split('\n', 1)[0]
83
 
            usage = bzrlib.help.command_usage(cmd_object)
84
 
            tmp = '.TP\n.B "%s"\n%s\n' % (usage, firstline)
85
 
            output = output + tmp
 
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)
86
98
        else:
87
 
            raise RuntimeError, "Command '%s' has no help text" % (cmd_name)
88
 
    return output
89
 
 
90
 
 
91
 
def getcommand_help(params):
92
 
    """Shows individual options for a bzr command"""
93
 
    output='.SH "COMMAND REFERENCE"\n'
94
 
    for cmd_name in command_name_list():
95
 
        cmd_object = bzrlib.commands.get_cmd_object(cmd_name)
96
 
        if cmd_object.hidden:
97
 
            continue
98
 
        output = output + format_command(params, cmd_object)
99
 
    return output
100
 
 
101
 
 
102
 
def format_command (params, cmd):
103
 
    """Provides long help for each public command"""
104
 
    subsection_header = '.SS "%s"\n' % (bzrlib.help.command_usage(cmd))
105
 
    doc = "%s\n" % (cmd.__doc__)
106
 
    docsplit = cmd.__doc__.split('\n')
107
 
    doc = '\n'.join([docsplit[0]] + [line[4:] for line in docsplit[1:]])
108
 
    option_str = ""
109
 
    options = cmd.options()
110
 
    if options:
111
 
        option_str = "\nOptions:\n"
112
 
        for option_name, option in sorted(options.items()):
113
 
            l = '    --' + option_name
114
 
            if option.type is not None:
115
 
                l += ' ' + option.argname.upper()
116
 
            short_name = option.short_name()
117
 
            if short_name:
118
 
                assert len(short_name) == 1
119
 
                l += ', -' + short_name
120
 
            l += (30 - len(l)) * ' ' + option.help
121
 
            # TODO: Split help over multiple lines with
122
 
            # correct indenting and wrapping.
123
 
            wrapped = textwrap.fill(l, initial_indent='',
124
 
                                    subsequent_indent=30*' ')
125
 
            option_str = option_str + wrapped + '\n'       
126
 
    return subsection_header + option_str + "\n" + doc + "\n"
 
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))
127
128
 
128
129
 
129
130
man_preamble = """\
130
 
Man page for %(bzrcmd)s (bazaar-ng)
 
131
.\\\" Man page for %(bzrcmd)s (bazaar-ng)
131
132
.\\\"
132
133
.\\\" Large parts of this file are autogenerated from the output of
133
134
.\\\"     \"%(bzrcmd)s help commands\"
137
138
.\\\"
138
139
"""
139
140
 
140
 
 
 
141
# The DESCRIPTION text was taken from http://www.bazaar-ng.org/
 
142
# and is thus (C) Canonical
141
143
man_head = """\
142
144
.TH bzr 1 "%(datestamp)s" "%(version)s" "bazaar-ng"
143
145
.SH "NAME"
172
174
is to look for external command.
173
175
.TP
174
176
.I "BZREMAIL"
175
 
E-Mail address of the user. Overrides default user config.
 
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>"
176
182
.TP
177
183
.I "EMAIL"
178
 
E-Mail address of the user. Overriddes default user config.
 
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" .
179
188
.SH "FILES"
180
189
.TP
181
 
.I "~/.bazaar/bazaar.conf/"
182
 
Contains the default user config. Only one section, [DEFAULT] is allowed. A 
183
 
typical default config file may be similiar to:
184
 
.br
185
 
.br
186
 
.B [DEFAULT]
187
 
.br
188
 
.B email=John Doe <jdoe@isp.com>
 
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>"
189
198
.SH "SEE ALSO"
190
 
.UR http://bazaar.canonical.com/
191
 
.BR http://bazaar.canonical.com/,
192
199
.UR http://www.bazaar-ng.org/
193
 
.BR 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/
194
203
"""
195
204
 
 
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