Using argparse module to parse the cmd line
[tools/mic.git] / mic / helpformat.py
1 #!/usr/bin/env python\r
2 # vim: ai ts=4 sts=4 et sw=4\r
3 #\r
4 # Copyright (c) 2011 Intel, Inc.\r
5 #\r
6 # This program is free software; you can redistribute it and/or modify it\r
7 # under the terms of the GNU General Public License as published by the Free\r
8 # Software Foundation; version 2 of the License\r
9 #\r
10 # This program is distributed in the hope that it will be useful, but\r
11 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\r
12 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\r
13 # for more details.\r
14 #\r
15 # You should have received a copy of the GNU General Public License along\r
16 # with this program; if not, write to the Free Software Foundation, Inc., 59\r
17 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.\r
18 \r
19 """Local additions to commandline parsing."""\r
20 \r
21 import os\r
22 import re\r
23 import functools\r
24 \r
25 from argparse import RawDescriptionHelpFormatter, ArgumentTypeError\r
26 \r
27 class MICHelpFormatter(RawDescriptionHelpFormatter):\r
28     """Changed default argparse help output by request from cmdln lovers."""\r
29 \r
30     def __init__(self, *args, **kwargs):\r
31         super(MICHelpFormatter, self).__init__(*args, **kwargs)\r
32         self._aliases = {}\r
33 \r
34     def add_argument(self, action):\r
35         """Collect aliases."""\r
36 \r
37         if action.choices:\r
38             for item, parser in action.choices.iteritems():\r
39                 self._aliases[str(item)] = parser.get_default('alias')\r
40 \r
41         return super(MICHelpFormatter, self).add_argument(action)\r
42 \r
43     def format_help(self):\r
44         """\r
45         There is no safe and documented way in argparse to reformat\r
46         help output through APIs as almost all of them are private,\r
47         so this method just parses the output and changes it.\r
48         """\r
49         result = []\r
50         subcomm = False\r
51         for line in super(MICHelpFormatter, self).format_help().split('\n'):\r
52             if line.strip().startswith('{'):\r
53                 continue\r
54             if line.startswith('optional arguments:'):\r
55                 line = 'Global Options:'\r
56             if line.startswith('usage:'):\r
57                 line = "Usage: mic [GLOBAL-OPTS] SUBCOMMAND [OPTS]"\r
58             if subcomm:\r
59                 match = re.match("[ ]+([^ ]+)[ ]+(.+)", line)\r
60                 if match:\r
61                     name, help_text = match.group(1), match.group(2)\r
62                     alias = self._aliases.get(name) or ''\r
63                     if alias:\r
64                         alias = "(%s)" % alias\r
65                     line = "  %-22s%s" % ("%s %s" % (name, alias), help_text)\r
66             if line.strip().startswith('subcommands:'):\r
67                 line = 'Subcommands:'\r
68                 subcomm = True\r
69             result.append(line)\r
70         return '\n'.join(result)\r
71 \r
72 def subparser(func):\r
73     """Convenient decorator for subparsers."""\r
74     @functools.wraps(func)\r
75     def wrapper(parser):\r
76         """\r
77         Create subparser\r
78         Set first line of function's docstring as a help\r
79         and the rest of the lines as a description.\r
80         Set attribute 'module' of subparser to 'cmd'+first part of function name\r
81         """\r
82         splitted = func.__doc__.split('\n')\r
83         name = func.__name__.split('_')[0]\r
84         subpar = parser.add_parser(name, help=splitted[0],\r
85                                    description='\n'.join(splitted[1:]),\r
86                                    formatter_class=RawDescriptionHelpFormatter)\r
87         subpar.set_defaults(module="cmd_%s" % name)\r
88         return func(subpar)\r
89     return wrapper\r
90 \r