decorators.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import traceback
  2. from rope.base import exceptions
  3. class Logger(object):
  4. message = None
  5. only_short = False
  6. def __call__(self, message, short=None):
  7. if short is None or not self.only_short:
  8. self._show(message)
  9. if short is not None:
  10. self._show(short)
  11. def _show(self, message):
  12. if self.message is None:
  13. print message
  14. else:
  15. self.message(message)
  16. logger = Logger()
  17. def lisphook(func):
  18. def newfunc(*args, **kwds):
  19. try:
  20. func(*args, **kwds)
  21. except Exception, e:
  22. trace = str(traceback.format_exc())
  23. short = 'Ignored an exception in ropemode hook: %s' % \
  24. _exception_message(e)
  25. logger(trace, short)
  26. newfunc.lisp = None
  27. newfunc.__name__ = func.__name__
  28. newfunc.__doc__ = func.__doc__
  29. return newfunc
  30. def lispfunction(func):
  31. func.lisp = None
  32. return func
  33. input_exceptions = (exceptions.RefactoringError,
  34. exceptions.ModuleSyntaxError,
  35. exceptions.BadIdentifierError)
  36. def _exception_handler(func):
  37. def newfunc(*args, **kwds):
  38. try:
  39. return func(*args, **kwds)
  40. except exceptions.RopeError, e:
  41. short = None
  42. if isinstance(e, input_exceptions):
  43. short = _exception_message(e)
  44. logger(str(traceback.format_exc()), short)
  45. newfunc.__name__ = func.__name__
  46. newfunc.__doc__ = func.__doc__
  47. return newfunc
  48. def _exception_message(e):
  49. return '%s: %s' % (e.__class__.__name__, str(e))
  50. def rope_hook(hook):
  51. def decorator(func):
  52. func = lisphook(func)
  53. func.name = func.__name__
  54. func.kind = 'hook'
  55. func.hook = hook
  56. return func
  57. return decorator
  58. def local_command(key=None, prefix=False, shortcut=None, name=None):
  59. def decorator(func, name=name):
  60. func = _exception_handler(func)
  61. func.kind = 'local'
  62. func.prefix = prefix
  63. func.local_key = key
  64. func.shortcut_key = shortcut
  65. if name is None:
  66. name = func.__name__
  67. func.name = name
  68. return func
  69. return decorator
  70. def global_command(key=None, prefix=False):
  71. def decorator(func):
  72. func = _exception_handler(func)
  73. func.kind = 'global'
  74. func.prefix = prefix
  75. func.global_key = key
  76. func.name = func.__name__
  77. return func
  78. return decorator