optparser.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # -*- coding: utf-8 -*-
  2. # copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
  3. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
  4. #
  5. # This file is part of logilab-common.
  6. #
  7. # logilab-common is free software: you can redistribute it and/or modify it under
  8. # the terms of the GNU Lesser General Public License as published by the Free
  9. # Software Foundation, either version 2.1 of the License, or (at your option) any
  10. # later version.
  11. #
  12. # logilab-common is distributed in the hope that it will be useful, but WITHOUT
  13. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  14. # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  15. # details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public License along
  18. # with logilab-common. If not, see <http://www.gnu.org/licenses/>.
  19. """Extend OptionParser with commands.
  20. Example:
  21. >>> parser = OptionParser()
  22. >>> parser.usage = '%prog COMMAND [options] <arg> ...'
  23. >>> parser.add_command('build', 'mymod.build')
  24. >>> parser.add_command('clean', run_clean, add_opt_clean)
  25. >>> run, options, args = parser.parse_command(sys.argv[1:])
  26. >>> return run(options, args[1:])
  27. With mymod.build that defines two functions run and add_options
  28. """
  29. __docformat__ = "restructuredtext en"
  30. from warnings import warn
  31. warn('lgc.optparser module is deprecated, use lgc.clcommands instead', DeprecationWarning,
  32. stacklevel=2)
  33. import sys
  34. import optparse
  35. class OptionParser(optparse.OptionParser):
  36. def __init__(self, *args, **kwargs):
  37. optparse.OptionParser.__init__(self, *args, **kwargs)
  38. self._commands = {}
  39. self.min_args, self.max_args = 0, 1
  40. def add_command(self, name, mod_or_funcs, help=''):
  41. """name of the command, name of module or tuple of functions
  42. (run, add_options)
  43. """
  44. assert isinstance(mod_or_funcs, str) or isinstance(mod_or_funcs, tuple), \
  45. "mod_or_funcs has to be a module name or a tuple of functions"
  46. self._commands[name] = (mod_or_funcs, help)
  47. def print_main_help(self):
  48. optparse.OptionParser.print_help(self)
  49. print '\ncommands:'
  50. for cmdname, (_, help) in self._commands.items():
  51. print '% 10s - %s' % (cmdname, help)
  52. def parse_command(self, args):
  53. if len(args) == 0:
  54. self.print_main_help()
  55. sys.exit(1)
  56. cmd = args[0]
  57. args = args[1:]
  58. if cmd not in self._commands:
  59. if cmd in ('-h', '--help'):
  60. self.print_main_help()
  61. sys.exit(0)
  62. elif self.version is not None and cmd == "--version":
  63. self.print_version()
  64. sys.exit(0)
  65. self.error('unknown command')
  66. self.prog = '%s %s' % (self.prog, cmd)
  67. mod_or_f, help = self._commands[cmd]
  68. # optparse inserts self.description between usage and options help
  69. self.description = help
  70. if isinstance(mod_or_f, str):
  71. exec 'from %s import run, add_options' % mod_or_f
  72. else:
  73. run, add_options = mod_or_f
  74. add_options(self)
  75. (options, args) = self.parse_args(args)
  76. if not (self.min_args <= len(args) <= self.max_args):
  77. self.error('incorrect number of arguments')
  78. return run, options, args