docopt_command.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import sys
  2. from inspect import getdoc
  3. from docopt import docopt, DocoptExit
  4. def docopt_full_help(docstring, *args, **kwargs):
  5. try:
  6. return docopt(docstring, *args, **kwargs)
  7. except DocoptExit:
  8. raise SystemExit(docstring)
  9. class DocoptCommand(object):
  10. def sys_dispatch(self):
  11. self.dispatch(sys.argv[1:], None)
  12. def dispatch(self, argv, global_options):
  13. self.perform_command(*self.parse(argv, global_options))
  14. def perform_command(self, options, command, handler, command_options):
  15. handler(command_options)
  16. def parse(self, argv, global_options):
  17. options = docopt_full_help(getdoc(self), argv, options_first=True)
  18. command = options['COMMAND']
  19. if not hasattr(self, command):
  20. raise NoSuchCommand(command, self)
  21. handler = getattr(self, command)
  22. docstring = getdoc(handler)
  23. if docstring is None:
  24. raise NoSuchCommand(command, self)
  25. command_options = docopt_full_help(docstring, options['ARGS'], options_first=True)
  26. return (options, command, handler, command_options)
  27. class NoSuchCommand(Exception):
  28. def __init__(self, command, supercommand):
  29. super(NoSuchCommand, self).__init__("No such command: %s" % command)
  30. self.command = command
  31. self.supercommand = supercommand