| 21 | |
| 22 | """This modules defines a command line options parser for PyKota's command line tools.""" |
| 23 | |
| 24 | import optparse |
| 25 | from gettext import gettext as _ |
| 26 | |
| 27 | from pykota import version |
| 28 | |
| 29 | class PyKotaOptionParser(optparse.OptionParser) : |
| 30 | """ |
| 31 | This class to define additional methods, and different help |
| 32 | formatting, from the traditional OptionParser. |
| 33 | """ |
| 34 | def __init__(self, *args, **kwargs) : |
| 35 | """ |
| 36 | Initializes our option parser with additional attributes. |
| 37 | """ |
| 38 | self.examples = [] |
| 39 | optparse.OptionParser.__init__(self, *args, **kwargs) |
| 40 | self.disable_interspersed_args() |
| 41 | self.add_option("-", "--version", |
| 42 | action="store_true", |
| 43 | dest="version", |
| 44 | help=_("show %prog's version number and exit.")) |
| 45 | |
| 46 | def format_help(self, formatter=None) : |
| 47 | """ |
| 48 | Reformats help our way : adding examples and copyright |
| 49 | message at the end. |
| 50 | """ |
| 51 | if formatter is None : |
| 52 | formatter = self.formatter |
| 53 | result = [] |
| 54 | result.append(optparse.OptionParser.format_help(self, formatter) + "\n") |
| 55 | result.append(self.format_examples() + "\n") |
| 56 | result.append(self.format_copyright() + "\n") |
| 57 | return "".join(result) |
| 58 | |
| 59 | def format_examples(self, formatter=None) : |
| 60 | """Formats examples our way.""" |
| 61 | if formatter is None : |
| 62 | formatter = self.formatter |
| 63 | result = [] |
| 64 | if self.examples : |
| 65 | result.append(formatter.format_heading(_("examples"))) |
| 66 | formatter.indent() |
| 67 | for (cmd, explanation) in self.examples : |
| 68 | result.append(formatter.format_description(self.expand_prog_name(cmd))) |
| 69 | result.append(formatter.format_description(self.expand_prog_name(explanation)) + "\n") |
| 70 | formatter.dedent() |
| 71 | return "".join(result) |
| 72 | |
| 73 | def format_copyright(self, formatter=None) : |
| 74 | """Formats copyright message our way.""" |
| 75 | if formatter is None : |
| 76 | formatter = self.formatter |
| 77 | result = [] |
| 78 | result.append(formatter.format_heading(_("licensing terms"))) |
| 79 | formatter.indent() |
| 80 | result.append(formatter.format_description("(c) %s %s\n" \ |
| 81 | % (version.__years__, \ |
| 82 | version.__author__))) |
| 83 | for part in version.__gplblurb__.split("\n\n") : |
| 84 | result.append(formatter.format_description(part) + "\n") |
| 85 | formatter.dedent() |
| 86 | return "".join(result) |
| 87 | |
| 88 | def add_example(self, command, doc) : |
| 89 | """Adds an usage example.""" |
| 90 | self.examples.append(("%prog " + command, doc)) |