]> Tony Duckles's Git Repositories (git.nynim.org) - svn2svn.git/blob - svn2svn/run/parse.py
svn2svn v1.5.0
[svn2svn.git] / svn2svn / run / parse.py
1 """ optparser helper functions """
2
3 import optparse
4 import textwrap
5
6 class HelpFormatter(optparse.IndentedHelpFormatter):
7 """
8 Modified version of certain optparse.IndentedHelpFormatter methods:
9 * Respect line-breaks in parser.desription and option.help_text
10 * Vertically-align long_opts
11 Inspired by: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6df6e6b541a15bc2/09f28e26af0699b1?pli=1
12 """
13 def format_description(self, description):
14 if not description: return ""
15 desc_width = self.width - self.current_indent
16 indent = " "*self.current_indent
17 bits = description.split('\n')
18 formatted_bits = [
19 textwrap.fill(bit,
20 desc_width,
21 initial_indent=indent,
22 subsequent_indent=indent)
23 for bit in bits]
24 result = "\n".join(formatted_bits) + "\n"
25 return result
26
27 def format_option_strings(self, option):
28 """Return a comma-separated list of option strings & metavariables."""
29 if option.takes_value():
30 metavar = option.metavar or option.dest.upper()
31 short_opts = [("%s" % (sopt)) if option._long_opts else \
32 (self._short_opt_fmt % (sopt, metavar))
33 for sopt in option._short_opts]
34 long_opts = [self._long_opt_fmt % (lopt, metavar)
35 for lopt in option._long_opts]
36 else:
37 short_opts = option._short_opts
38 long_opts = option._long_opts
39
40 return (" " if not short_opts else "")+(", ".join(short_opts + long_opts))
41
42 def format_option(self, option):
43 result = []
44 opts = self.option_strings[option]
45 opt_width = self.help_position - self.current_indent - 2
46 if len(opts) > opt_width:
47 opts = "%*s%s\n" % (self.current_indent, "", opts)
48 indent_first = self.help_position
49 else: # start help on same line as opts
50 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
51 indent_first = 0
52 result.append(opts)
53 if option.help:
54 help_text = self.expand_default(option)
55 help_lines = []
56 for para in help_text.split("\n"):
57 help_lines.extend(textwrap.wrap(para, self.help_width))
58 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
59 result.extend(["%*s%s\n" % (self.help_position, "", line)
60 for line in help_lines[1:]])
61 elif opts[-1] != "\n":
62 result.append("\n")
63 return "".join(result)
64
65 def format_usage(self, usage):
66 return usage