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