parsing.py 3.6 KB

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