error.py 2.5 KB

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