| 1 |
|
| 2 |
__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError'] |
| 3 |
|
| 4 |
class Mark: |
| 5 |
|
| 6 |
def __init__(self, name, index, line, column, buffer, pointer): |
| 7 |
self.name = name |
| 8 |
self.index = index |
| 9 |
self.line = line |
| 10 |
self.column = column |
| 11 |
self.buffer = buffer |
| 12 |
self.pointer = pointer |
| 13 |
|
| 14 |
def get_snippet(self, indent=4, max_length=75): |
| 15 |
if self.buffer is None: |
| 16 |
return None |
| 17 |
head = '' |
| 18 |
start = self.pointer |
| 19 |
while start > 0 and self.buffer[start-1] not in '\0\r\n\x85\u2028\u2029': |
| 20 |
start -= 1 |
| 21 |
if self.pointer-start > max_length/2-1: |
| 22 |
head = ' ... ' |
| 23 |
start += 5 |
| 24 |
break |
| 25 |
tail = '' |
| 26 |
end = self.pointer |
| 27 |
while end < len(self.buffer) and self.buffer[end] not in '\0\r\n\x85\u2028\u2029': |
| 28 |
end += 1 |
| 29 |
if end-self.pointer > max_length/2-1: |
| 30 |
tail = ' ... ' |
| 31 |
end -= 5 |
| 32 |
break |
| 33 |
snippet = self.buffer[start:end] |
| 34 |
return ' '*indent + head + snippet + tail + '\n' \ |
| 35 |
+ ' '*(indent+self.pointer-start+len(head)) + '^' |
| 36 |
|
| 37 |
def __str__(self): |
| 38 |
snippet = self.get_snippet() |
| 39 |
where = " in \"%s\", line %d, column %d" \ |
| 40 |
% (self.name, self.line+1, self.column+1) |
| 41 |
if snippet is not None: |
| 42 |
where += ":\n"+snippet |
| 43 |
return where |
| 44 |
|
| 45 |
class YAMLError(Exception): |
| 46 |
pass |
| 47 |
|
| 48 |
class MarkedYAMLError(YAMLError): |
| 49 |
|
| 50 |
def __init__(self, context=None, context_mark=None, |
| 51 |
problem=None, problem_mark=None, note=None): |
| 52 |
self.context = context |
| 53 |
self.context_mark = context_mark |
| 54 |
self.problem = problem |
| 55 |
self.problem_mark = problem_mark |
| 56 |
self.note = note |
| 57 |
|
| 58 |
def __str__(self): |
| 59 |
lines = [] |
| 60 |
if self.context is not None: |
| 61 |
lines.append(self.context) |
| 62 |
if self.context_mark is not None \ |
| 63 |
and (self.problem is None or self.problem_mark is None |
| 64 |
or self.context_mark.name != self.problem_mark.name |
| 65 |
or self.context_mark.line != self.problem_mark.line |
| 66 |
or self.context_mark.column != self.problem_mark.column): |
| 67 |
lines.append(str(self.context_mark)) |
| 68 |
if self.problem is not None: |
| 69 |
lines.append(self.problem) |
| 70 |
if self.problem_mark is not None: |
| 71 |
lines.append(str(self.problem_mark)) |
| 72 |
if self.note is not None: |
| 73 |
lines.append(self.note) |
| 74 |
return '\n'.join(lines) |
| 75 |
|