undo.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python
  2. """Annotation undo functionality.
  3. Author: Pontus Stenetorp <pontus stenetorp se>
  4. Version: 2011-11-30
  5. """
  6. from annotation import TextAnnotations
  7. from annotator import create_span, delete_span
  8. from common import ProtocolError
  9. from jsonwrap import loads as json_loads
  10. class CorruptUndoTokenError(ProtocolError):
  11. def __str__(self):
  12. return 'Undo token corrupted, unable to process'
  13. def json(self, json_dic):
  14. json_dic['exception'] = 'corruptUndoTokenError'
  15. class InvalidUndoTokenError(ProtocolError):
  16. def __init__(self, attrib):
  17. self.attrib = attrib
  18. def __str__(self):
  19. return 'Undo token missing %s' % self.attrib
  20. def json(self, json_dic):
  21. json_dic['exception'] = 'invalidUndoTokenError'
  22. class NonUndoableActionError(ProtocolError):
  23. def __str__(self):
  24. return 'Unable to undo the given action'
  25. def json(self, json_dic):
  26. json_dic['exception'] = 'nonUndoableActionError'
  27. def undo(collection, document, token):
  28. try:
  29. token = json_loads(token)
  30. except ValueError:
  31. raise CorruptUndoTokenError
  32. try:
  33. action = token['action']
  34. except KeyError:
  35. raise InvalidTokenError('action')
  36. if action == 'add_tb':
  37. # Undo an addition
  38. return delete_span(collection, document, token['id'])
  39. if action == 'mod_tb':
  40. # Undo a modification
  41. # TODO: We do not handle attributes and comments
  42. return create_span(
  43. collection,
  44. document,
  45. token['start'],
  46. token['end'],
  47. token['type'],
  48. id=token['id'],
  49. attributes=token['attributes'],
  50. comment=token['comment'] if 'comment' in token else None)
  51. else:
  52. raise NonUndoableActionError
  53. assert False, 'should have returned prior to this point'
  54. if __name__ == '__main__':
  55. # XXX: Path to...
  56. pass