comments.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. from __future__ import annotations
  2. """
  3. stuff to deal with comments and formatting on dict/list/ordereddict/set
  4. these are not really related, formatting could be factored out as
  5. a separate base
  6. """
  7. import sys
  8. import copy
  9. from ruamel.yaml.compat import ordereddict
  10. from ruamel.yaml.compat import MutableSliceableSequence, nprintf # NOQA
  11. from ruamel.yaml.scalarstring import ScalarString
  12. from ruamel.yaml.anchor import Anchor
  13. from ruamel.yaml.tag import Tag
  14. from collections.abc import MutableSet, Sized, Set, Mapping
  15. if False: # MYPY
  16. from typing import Any, Dict, Optional, List, Union, Iterator # NOQA
  17. # fmt: off
  18. __all__ = ['CommentedSeq', 'CommentedKeySeq',
  19. 'CommentedMap', 'CommentedOrderedMap',
  20. 'CommentedSet', 'comment_attrib', 'merge_attrib',
  21. 'TaggedScalar',
  22. 'C_POST', 'C_PRE', 'C_SPLIT_ON_FIRST_BLANK', 'C_BLANK_LINE_PRESERVE_SPACE',
  23. ]
  24. # fmt: on
  25. # splitting of comments by the scanner
  26. # an EOLC (End-Of-Line Comment) is preceded by some token
  27. # an FLC (Full Line Comment) is a comment not preceded by a token, i.e. # is
  28. # the first non-blank on line
  29. # a BL is a blank line i.e. empty or spaces/tabs only
  30. # bits 0 and 1 are combined, you can choose only one
  31. C_POST = 0b00
  32. C_PRE = 0b01
  33. C_SPLIT_ON_FIRST_BLANK = 0b10 # as C_POST, but if blank line then C_PRE all lines before
  34. # first blank goes to POST even if no following real FLC
  35. # (first blank -> first of post)
  36. # 0b11 -> reserved for future use
  37. C_BLANK_LINE_PRESERVE_SPACE = 0b100
  38. # C_EOL_PRESERVE_SPACE2 = 0b1000
  39. class IDX:
  40. # temporary auto increment, so rearranging is easier
  41. def __init__(self) -> None:
  42. self._idx = 0
  43. def __call__(self) -> Any:
  44. x = self._idx
  45. self._idx += 1
  46. return x
  47. def __str__(self) -> Any:
  48. return str(self._idx)
  49. cidx = IDX()
  50. # more or less in order of subjective expected likelyhood
  51. # the _POST and _PRE ones are lists themselves
  52. C_VALUE_EOL = C_ELEM_EOL = cidx()
  53. C_KEY_EOL = cidx()
  54. C_KEY_PRE = C_ELEM_PRE = cidx() # not this is not value
  55. C_VALUE_POST = C_ELEM_POST = cidx() # not this is not value
  56. C_VALUE_PRE = cidx()
  57. C_KEY_POST = cidx()
  58. C_TAG_EOL = cidx()
  59. C_TAG_POST = cidx()
  60. C_TAG_PRE = cidx()
  61. C_ANCHOR_EOL = cidx()
  62. C_ANCHOR_POST = cidx()
  63. C_ANCHOR_PRE = cidx()
  64. comment_attrib = '_yaml_comment'
  65. format_attrib = '_yaml_format'
  66. line_col_attrib = '_yaml_line_col'
  67. merge_attrib = '_yaml_merge'
  68. class Comment:
  69. # using sys.getsize tested the Comment objects, __slots__ makes them bigger
  70. # and adding self.end did not matter
  71. __slots__ = 'comment', '_items', '_post', '_pre'
  72. attrib = comment_attrib
  73. def __init__(self, old: bool = True) -> None:
  74. self._pre = None if old else [] # type: ignore
  75. self.comment = None # [post, [pre]]
  76. # map key (mapping/omap/dict) or index (sequence/list) to a list of
  77. # dict: post_key, pre_key, post_value, pre_value
  78. # list: pre item, post item
  79. self._items: Dict[Any, Any] = {}
  80. # self._start = [] # should not put these on first item
  81. self._post: List[Any] = [] # end of document comments
  82. def __str__(self) -> str:
  83. if bool(self._post):
  84. end = ',\n end=' + str(self._post)
  85. else:
  86. end = ""
  87. return f'Comment(comment={self.comment},\n items={self._items}{end})'
  88. def _old__repr__(self) -> str:
  89. if bool(self._post):
  90. end = ',\n end=' + str(self._post)
  91. else:
  92. end = ""
  93. try:
  94. ln = max([len(str(k)) for k in self._items]) + 1
  95. except ValueError:
  96. ln = '' # type: ignore
  97. it = ' '.join([f'{str(k) + ":":{ln}} {v}\n' for k, v in self._items.items()])
  98. if it:
  99. it = '\n ' + it + ' '
  100. return f'Comment(\n start={self.comment},\n items={{{it}}}{end})'
  101. def __repr__(self) -> str:
  102. if self._pre is None:
  103. return self._old__repr__()
  104. if bool(self._post):
  105. end = ',\n end=' + repr(self._post)
  106. else:
  107. end = ""
  108. try:
  109. ln = max([len(str(k)) for k in self._items]) + 1
  110. except ValueError:
  111. ln = '' # type: ignore
  112. it = ' '.join([f'{str(k) + ":":{ln}} {v}\n' for k, v in self._items.items()])
  113. if it:
  114. it = '\n ' + it + ' '
  115. return f'Comment(\n pre={self.pre},\n items={{{it}}}{end})'
  116. @property
  117. def items(self) -> Any:
  118. return self._items
  119. @property
  120. def end(self) -> Any:
  121. return self._post
  122. @end.setter
  123. def end(self, value: Any) -> None:
  124. self._post = value
  125. @property
  126. def pre(self) -> Any:
  127. return self._pre
  128. @pre.setter
  129. def pre(self, value: Any) -> None:
  130. self._pre = value
  131. def get(self, item: Any, pos: Any) -> Any:
  132. x = self._items.get(item)
  133. if x is None or len(x) < pos:
  134. return None
  135. return x[pos] # can be None
  136. def set(self, item: Any, pos: Any, value: Any) -> Any:
  137. x = self._items.get(item)
  138. if x is None:
  139. self._items[item] = x = [None] * (pos + 1)
  140. else:
  141. while len(x) <= pos:
  142. x.append(None)
  143. assert x[pos] is None
  144. x[pos] = value
  145. def __contains__(self, x: Any) -> Any:
  146. # test if a substring is in any of the attached comments
  147. if self.comment:
  148. if self.comment[0] and x in self.comment[0].value:
  149. return True
  150. if self.comment[1]:
  151. for c in self.comment[1]:
  152. if x in c.value:
  153. return True
  154. for value in self.items.values():
  155. if not value:
  156. continue
  157. for c in value:
  158. if c and x in c.value:
  159. return True
  160. if self.end:
  161. for c in self.end:
  162. if x in c.value:
  163. return True
  164. return False
  165. # to distinguish key from None
  166. class NotNone:
  167. pass # NOQA
  168. class Format:
  169. __slots__ = ('_flow_style',)
  170. attrib = format_attrib
  171. def __init__(self) -> None:
  172. self._flow_style: Any = None
  173. def set_flow_style(self) -> None:
  174. self._flow_style = True
  175. def set_block_style(self) -> None:
  176. self._flow_style = False
  177. def flow_style(self, default: Optional[Any] = None) -> Any:
  178. """if default (the flow_style) is None, the flow style tacked on to
  179. the object explicitly will be taken. If that is None as well the
  180. default flow style rules the format down the line, or the type
  181. of the constituent values (simple -> flow, map/list -> block)"""
  182. if self._flow_style is None:
  183. return default
  184. return self._flow_style
  185. def __repr__(self) -> str:
  186. return f'Format({self._flow_style})'
  187. class LineCol:
  188. """
  189. line and column information wrt document, values start at zero (0)
  190. """
  191. attrib = line_col_attrib
  192. def __init__(self) -> None:
  193. self.line = None
  194. self.col = None
  195. self.data: Optional[Dict[Any, Any]] = None
  196. def add_kv_line_col(self, key: Any, data: Any) -> None:
  197. if self.data is None:
  198. self.data = {}
  199. self.data[key] = data
  200. def key(self, k: Any) -> Any:
  201. return self._kv(k, 0, 1)
  202. def value(self, k: Any) -> Any:
  203. return self._kv(k, 2, 3)
  204. def _kv(self, k: Any, x0: Any, x1: Any) -> Any:
  205. if self.data is None:
  206. return None
  207. data = self.data[k]
  208. return data[x0], data[x1]
  209. def item(self, idx: Any) -> Any:
  210. if self.data is None:
  211. return None
  212. return self.data[idx][0], self.data[idx][1]
  213. def add_idx_line_col(self, key: Any, data: Any) -> None:
  214. if self.data is None:
  215. self.data = {}
  216. self.data[key] = data
  217. def __repr__(self) -> str:
  218. return f'LineCol({self.line}, {self.col})'
  219. class CommentedBase:
  220. @property
  221. def ca(self):
  222. # type: () -> Any
  223. if not hasattr(self, Comment.attrib):
  224. setattr(self, Comment.attrib, Comment())
  225. return getattr(self, Comment.attrib)
  226. def yaml_end_comment_extend(self, comment: Any, clear: bool = False) -> None:
  227. if comment is None:
  228. return
  229. if clear or self.ca.end is None:
  230. self.ca.end = []
  231. self.ca.end.extend(comment)
  232. def yaml_key_comment_extend(self, key: Any, comment: Any, clear: bool = False) -> None:
  233. r = self.ca._items.setdefault(key, [None, None, None, None])
  234. if clear or r[1] is None:
  235. if comment[1] is not None:
  236. assert isinstance(comment[1], list)
  237. r[1] = comment[1]
  238. else:
  239. r[1].extend(comment[0])
  240. r[0] = comment[0]
  241. def yaml_value_comment_extend(self, key: Any, comment: Any, clear: bool = False) -> None:
  242. r = self.ca._items.setdefault(key, [None, None, None, None])
  243. if clear or r[3] is None:
  244. if comment[1] is not None:
  245. assert isinstance(comment[1], list)
  246. r[3] = comment[1]
  247. else:
  248. r[3].extend(comment[0])
  249. r[2] = comment[0]
  250. def yaml_set_start_comment(self, comment: Any, indent: Any = 0) -> None:
  251. """overwrites any preceding comment lines on an object
  252. expects comment to be without `#` and possible have multiple lines
  253. """
  254. from .error import CommentMark
  255. from .tokens import CommentToken
  256. pre_comments = self._yaml_clear_pre_comment() # type: ignore
  257. if comment[-1] == '\n':
  258. comment = comment[:-1] # strip final newline if there
  259. start_mark = CommentMark(indent)
  260. for com in comment.split('\n'):
  261. c = com.strip()
  262. if len(c) > 0 and c[0] != '#':
  263. com = '# ' + com
  264. pre_comments.append(CommentToken(com + '\n', start_mark))
  265. def yaml_set_comment_before_after_key(
  266. self,
  267. key: Any,
  268. before: Any = None,
  269. indent: Any = 0,
  270. after: Any = None,
  271. after_indent: Any = None,
  272. ) -> None:
  273. """
  274. expects comment (before/after) to be without `#` and possible have multiple lines
  275. """
  276. from ruamel.yaml.error import CommentMark
  277. from ruamel.yaml.tokens import CommentToken
  278. def comment_token(s: Any, mark: Any) -> Any:
  279. # handle empty lines as having no comment
  280. return CommentToken(('# ' if s else "") + s + '\n', mark)
  281. if after_indent is None:
  282. after_indent = indent + 2
  283. if before and (len(before) > 1) and before[-1] == '\n':
  284. before = before[:-1] # strip final newline if there
  285. if after and after[-1] == '\n':
  286. after = after[:-1] # strip final newline if there
  287. start_mark = CommentMark(indent)
  288. c = self.ca.items.setdefault(key, [None, [], None, None])
  289. if before is not None:
  290. if c[1] is None:
  291. c[1] = []
  292. if before == '\n':
  293. c[1].append(comment_token("", start_mark)) # type: ignore
  294. else:
  295. for com in before.split('\n'):
  296. c[1].append(comment_token(com, start_mark)) # type: ignore
  297. if after:
  298. start_mark = CommentMark(after_indent)
  299. if c[3] is None:
  300. c[3] = []
  301. for com in after.split('\n'):
  302. c[3].append(comment_token(com, start_mark)) # type: ignore
  303. @property
  304. def fa(self) -> Any:
  305. """format attribute
  306. set_flow_style()/set_block_style()"""
  307. if not hasattr(self, Format.attrib):
  308. setattr(self, Format.attrib, Format())
  309. return getattr(self, Format.attrib)
  310. def yaml_add_eol_comment(
  311. self, comment: Any, key: Optional[Any] = NotNone, column: Optional[Any] = None,
  312. ) -> None:
  313. """
  314. there is a problem as eol comments should start with ' #'
  315. (but at the beginning of the line the space doesn't have to be before
  316. the #. The column index is for the # mark
  317. """
  318. from .tokens import CommentToken
  319. from .error import CommentMark
  320. if column is None:
  321. try:
  322. column = self._yaml_get_column(key)
  323. except AttributeError:
  324. column = 0
  325. if comment[0] != '#':
  326. comment = '# ' + comment
  327. if column is None:
  328. if comment[0] == '#':
  329. comment = ' ' + comment
  330. column = 0
  331. start_mark = CommentMark(column)
  332. ct = [CommentToken(comment, start_mark), None]
  333. self._yaml_add_eol_comment(ct, key=key)
  334. @property
  335. def lc(self) -> Any:
  336. if not hasattr(self, LineCol.attrib):
  337. setattr(self, LineCol.attrib, LineCol())
  338. return getattr(self, LineCol.attrib)
  339. def _yaml_set_line_col(self, line: Any, col: Any) -> None:
  340. self.lc.line = line
  341. self.lc.col = col
  342. def _yaml_set_kv_line_col(self, key: Any, data: Any) -> None:
  343. self.lc.add_kv_line_col(key, data)
  344. def _yaml_set_idx_line_col(self, key: Any, data: Any) -> None:
  345. self.lc.add_idx_line_col(key, data)
  346. @property
  347. def anchor(self) -> Any:
  348. if not hasattr(self, Anchor.attrib):
  349. setattr(self, Anchor.attrib, Anchor())
  350. return getattr(self, Anchor.attrib)
  351. def yaml_anchor(self) -> Any:
  352. if not hasattr(self, Anchor.attrib):
  353. return None
  354. return self.anchor
  355. def yaml_set_anchor(self, value: Any, always_dump: bool = False) -> None:
  356. self.anchor.value = value
  357. self.anchor.always_dump = always_dump
  358. @property
  359. def tag(self) -> Any:
  360. if not hasattr(self, Tag.attrib):
  361. setattr(self, Tag.attrib, Tag())
  362. return getattr(self, Tag.attrib)
  363. def yaml_set_ctag(self, value: Tag) -> None:
  364. setattr(self, Tag.attrib, value)
  365. def copy_attributes(self, t: Any, memo: Any = None) -> Any:
  366. """
  367. copies the YAML related attributes, not e.g. .values
  368. returns target
  369. """
  370. # fmt: off
  371. for a in [Comment.attrib, Format.attrib, LineCol.attrib, Anchor.attrib,
  372. Tag.attrib, merge_attrib]:
  373. if hasattr(self, a):
  374. if memo is not None:
  375. setattr(t, a, copy.deepcopy(getattr(self, a, memo)))
  376. else:
  377. setattr(t, a, getattr(self, a))
  378. return t
  379. # fmt: on
  380. def _yaml_add_eol_comment(self, comment: Any, key: Any) -> None:
  381. raise NotImplementedError
  382. def _yaml_get_pre_comment(self) -> Any:
  383. raise NotImplementedError
  384. def _yaml_get_column(self, key: Any) -> Any:
  385. raise NotImplementedError
  386. class CommentedSeq(MutableSliceableSequence, list, CommentedBase): # type: ignore
  387. __slots__ = (Comment.attrib, '_lst')
  388. def __init__(self, *args: Any, **kw: Any) -> None:
  389. list.__init__(self, *args, **kw)
  390. def __getsingleitem__(self, idx: Any) -> Any:
  391. return list.__getitem__(self, idx)
  392. def __setsingleitem__(self, idx: Any, value: Any) -> None:
  393. # try to preserve the scalarstring type if setting an existing key to a new value
  394. if idx < len(self):
  395. if (
  396. isinstance(value, str)
  397. and not isinstance(value, ScalarString)
  398. and isinstance(self[idx], ScalarString)
  399. ):
  400. value = type(self[idx])(value)
  401. list.__setitem__(self, idx, value)
  402. def __delsingleitem__(self, idx: Any = None) -> Any:
  403. list.__delitem__(self, idx)
  404. self.ca.items.pop(idx, None) # might not be there -> default value
  405. for list_index in sorted(self.ca.items):
  406. if list_index < idx:
  407. continue
  408. self.ca.items[list_index - 1] = self.ca.items.pop(list_index)
  409. def __len__(self) -> int:
  410. return list.__len__(self)
  411. def insert(self, idx: Any, val: Any) -> None:
  412. """the comments after the insertion have to move forward"""
  413. list.insert(self, idx, val)
  414. for list_index in sorted(self.ca.items, reverse=True):
  415. if list_index < idx:
  416. break
  417. self.ca.items[list_index + 1] = self.ca.items.pop(list_index)
  418. def extend(self, val: Any) -> None:
  419. list.extend(self, val)
  420. def __eq__(self, other: Any) -> bool:
  421. return list.__eq__(self, other)
  422. def _yaml_add_comment(self, comment: Any, key: Optional[Any] = NotNone) -> None:
  423. if key is not NotNone:
  424. self.yaml_key_comment_extend(key, comment)
  425. else:
  426. self.ca.comment = comment
  427. def _yaml_add_eol_comment(self, comment: Any, key: Any) -> None:
  428. self._yaml_add_comment(comment, key=key)
  429. def _yaml_get_columnX(self, key: Any) -> Any:
  430. return self.ca.items[key][0].start_mark.column
  431. def _yaml_get_column(self, key: Any) -> Any:
  432. column = None
  433. sel_idx = None
  434. pre, post = key - 1, key + 1
  435. if pre in self.ca.items:
  436. sel_idx = pre
  437. elif post in self.ca.items:
  438. sel_idx = post
  439. else:
  440. # self.ca.items is not ordered
  441. for row_idx, _k1 in enumerate(self):
  442. if row_idx >= key:
  443. break
  444. if row_idx not in self.ca.items:
  445. continue
  446. sel_idx = row_idx
  447. if sel_idx is not None:
  448. column = self._yaml_get_columnX(sel_idx)
  449. return column
  450. def _yaml_get_pre_comment(self) -> Any:
  451. pre_comments: List[Any] = []
  452. if self.ca.comment is None:
  453. self.ca.comment = [None, pre_comments]
  454. else:
  455. pre_comments = self.ca.comment[1]
  456. return pre_comments
  457. def _yaml_clear_pre_comment(self) -> Any:
  458. pre_comments: List[Any] = []
  459. if self.ca.comment is None:
  460. self.ca.comment = [None, pre_comments]
  461. else:
  462. self.ca.comment[1] = pre_comments
  463. return pre_comments
  464. def __deepcopy__(self, memo: Any) -> Any:
  465. res = self.__class__()
  466. memo[id(self)] = res
  467. for k in self:
  468. res.append(copy.deepcopy(k, memo))
  469. self.copy_attributes(res, memo=memo)
  470. return res
  471. def __add__(self, other: Any) -> Any:
  472. return list.__add__(self, other)
  473. def sort(self, key: Any = None, reverse: bool = False) -> None:
  474. if key is None:
  475. tmp_lst = sorted(zip(self, range(len(self))), reverse=reverse)
  476. list.__init__(self, [x[0] for x in tmp_lst])
  477. else:
  478. tmp_lst = sorted(
  479. zip(map(key, list.__iter__(self)), range(len(self))), reverse=reverse,
  480. )
  481. list.__init__(self, [list.__getitem__(self, x[1]) for x in tmp_lst])
  482. itm = self.ca.items
  483. self.ca._items = {}
  484. for idx, x in enumerate(tmp_lst):
  485. old_index = x[1]
  486. if old_index in itm:
  487. self.ca.items[idx] = itm[old_index]
  488. def __repr__(self) -> Any:
  489. return list.__repr__(self)
  490. class CommentedKeySeq(tuple, CommentedBase): # type: ignore
  491. """This primarily exists to be able to roundtrip keys that are sequences"""
  492. def _yaml_add_comment(self, comment: Any, key: Optional[Any] = NotNone) -> None:
  493. if key is not NotNone:
  494. self.yaml_key_comment_extend(key, comment)
  495. else:
  496. self.ca.comment = comment
  497. def _yaml_add_eol_comment(self, comment: Any, key: Any) -> None:
  498. self._yaml_add_comment(comment, key=key)
  499. def _yaml_get_columnX(self, key: Any) -> Any:
  500. return self.ca.items[key][0].start_mark.column
  501. def _yaml_get_column(self, key: Any) -> Any:
  502. column = None
  503. sel_idx = None
  504. pre, post = key - 1, key + 1
  505. if pre in self.ca.items:
  506. sel_idx = pre
  507. elif post in self.ca.items:
  508. sel_idx = post
  509. else:
  510. # self.ca.items is not ordered
  511. for row_idx, _k1 in enumerate(self):
  512. if row_idx >= key:
  513. break
  514. if row_idx not in self.ca.items:
  515. continue
  516. sel_idx = row_idx
  517. if sel_idx is not None:
  518. column = self._yaml_get_columnX(sel_idx)
  519. return column
  520. def _yaml_get_pre_comment(self) -> Any:
  521. pre_comments: List[Any] = []
  522. if self.ca.comment is None:
  523. self.ca.comment = [None, pre_comments]
  524. else:
  525. pre_comments = self.ca.comment[1]
  526. return pre_comments
  527. def _yaml_clear_pre_comment(self) -> Any:
  528. pre_comments: List[Any] = []
  529. if self.ca.comment is None:
  530. self.ca.comment = [None, pre_comments]
  531. else:
  532. self.ca.comment[1] = pre_comments
  533. return pre_comments
  534. class CommentedMapView(Sized):
  535. __slots__ = ('_mapping',)
  536. def __init__(self, mapping: Any) -> None:
  537. self._mapping = mapping
  538. def __len__(self) -> int:
  539. count = len(self._mapping)
  540. return count
  541. class CommentedMapKeysView(CommentedMapView, Set): # type: ignore
  542. __slots__ = ()
  543. @classmethod
  544. def _from_iterable(self, it: Any) -> Any:
  545. return set(it)
  546. def __contains__(self, key: Any) -> Any:
  547. return key in self._mapping
  548. def __iter__(self) -> Any:
  549. # yield from self._mapping # not in py27, pypy
  550. # for x in self._mapping._keys():
  551. for x in self._mapping:
  552. yield x
  553. class CommentedMapItemsView(CommentedMapView, Set): # type: ignore
  554. __slots__ = ()
  555. @classmethod
  556. def _from_iterable(self, it: Any) -> Any:
  557. return set(it)
  558. def __contains__(self, item: Any) -> Any:
  559. key, value = item
  560. try:
  561. v = self._mapping[key]
  562. except KeyError:
  563. return False
  564. else:
  565. return v == value
  566. def __iter__(self) -> Any:
  567. for key in self._mapping._keys():
  568. yield (key, self._mapping[key])
  569. class CommentedMapValuesView(CommentedMapView):
  570. __slots__ = ()
  571. def __contains__(self, value: Any) -> Any:
  572. for key in self._mapping:
  573. if value == self._mapping[key]:
  574. return True
  575. return False
  576. def __iter__(self) -> Any:
  577. for key in self._mapping._keys():
  578. yield self._mapping[key]
  579. class CommentedMap(ordereddict, CommentedBase):
  580. __slots__ = (Comment.attrib, '_ok', '_ref')
  581. def __init__(self, *args: Any, **kw: Any) -> None:
  582. self._ok: MutableSet[Any] = set() # own keys
  583. self._ref: List[CommentedMap] = []
  584. ordereddict.__init__(self, *args, **kw)
  585. def _yaml_add_comment(
  586. self, comment: Any, key: Optional[Any] = NotNone, value: Optional[Any] = NotNone,
  587. ) -> None:
  588. """values is set to key to indicate a value attachment of comment"""
  589. if key is not NotNone:
  590. self.yaml_key_comment_extend(key, comment)
  591. return
  592. if value is not NotNone:
  593. self.yaml_value_comment_extend(value, comment)
  594. else:
  595. self.ca.comment = comment
  596. def _yaml_add_eol_comment(self, comment: Any, key: Any) -> None:
  597. """add on the value line, with value specified by the key"""
  598. self._yaml_add_comment(comment, value=key)
  599. def _yaml_get_columnX(self, key: Any) -> Any:
  600. return self.ca.items[key][2].start_mark.column
  601. def _yaml_get_column(self, key: Any) -> Any:
  602. column = None
  603. sel_idx = None
  604. pre, post, last = None, None, None
  605. for x in self:
  606. if pre is not None and x != key:
  607. post = x
  608. break
  609. if x == key:
  610. pre = last
  611. last = x
  612. if pre in self.ca.items:
  613. sel_idx = pre
  614. elif post in self.ca.items:
  615. sel_idx = post
  616. else:
  617. # self.ca.items is not ordered
  618. for k1 in self:
  619. if k1 >= key:
  620. break
  621. if k1 not in self.ca.items:
  622. continue
  623. sel_idx = k1
  624. if sel_idx is not None:
  625. column = self._yaml_get_columnX(sel_idx)
  626. return column
  627. def _yaml_get_pre_comment(self) -> Any:
  628. pre_comments: List[Any] = []
  629. if self.ca.comment is None:
  630. self.ca.comment = [None, pre_comments]
  631. else:
  632. pre_comments = self.ca.comment[1]
  633. return pre_comments
  634. def _yaml_clear_pre_comment(self) -> Any:
  635. pre_comments: List[Any] = []
  636. if self.ca.comment is None:
  637. self.ca.comment = [None, pre_comments]
  638. else:
  639. self.ca.comment[1] = pre_comments
  640. return pre_comments
  641. def update(self, *vals: Any, **kw: Any) -> None:
  642. try:
  643. ordereddict.update(self, *vals, **kw)
  644. except TypeError:
  645. # probably a dict that is used
  646. for x in vals[0]:
  647. self[x] = vals[0][x]
  648. if vals:
  649. try:
  650. self._ok.update(vals[0].keys()) # type: ignore
  651. except AttributeError:
  652. # assume one argument that is a list/tuple of two element lists/tuples
  653. for x in vals[0]:
  654. self._ok.add(x[0])
  655. if kw:
  656. self._ok.update(*kw.keys()) # type: ignore
  657. def insert(self, pos: Any, key: Any, value: Any, comment: Optional[Any] = None) -> None:
  658. """insert key value into given position, as defined by source YAML
  659. attach comment if provided
  660. """
  661. if key in self._ok:
  662. del self[key]
  663. keys = [k for k in self.keys() if k in self._ok]
  664. try:
  665. merge_value = getattr(self, merge_attrib)
  666. merge_pos = merge_value.merge_pos
  667. except (AttributeError, IndexError):
  668. merge_pos = -1
  669. if merge_pos >= 0:
  670. if merge_pos >= pos:
  671. # getattr(self, merge_attrib)[0] = (merge_pos + 1, ma0[1])
  672. merge_value.merge_pos += 1
  673. idx_min = pos
  674. idx_max = len(self._ok)
  675. else:
  676. idx_min = pos - 1
  677. idx_max = len(self._ok)
  678. else:
  679. idx_min = pos
  680. idx_max = len(self._ok)
  681. self[key] = value # at the end
  682. # print(f'{idx_min=} {idx_max=}')
  683. for idx in range(idx_min, idx_max):
  684. self.move_to_end(keys[idx])
  685. self._ok.add(key)
  686. # for referer in self._ref:
  687. # for keytmp in keys:
  688. # referer.update_key_value(keytmp)
  689. if comment is not None:
  690. self.yaml_add_eol_comment(comment, key=key)
  691. def mlget(self, key: Any, default: Any = None, list_ok: Any = False) -> Any:
  692. """multi-level get that expects dicts within dicts"""
  693. if not isinstance(key, list):
  694. return self.get(key, default)
  695. # assume that the key is a list of recursively accessible dicts
  696. def get_one_level(key_list: Any, level: Any, d: Any) -> Any:
  697. if not list_ok:
  698. assert isinstance(d, dict)
  699. if level >= len(key_list):
  700. if level > len(key_list):
  701. raise IndexError
  702. return d[key_list[level - 1]]
  703. return get_one_level(key_list, level + 1, d[key_list[level - 1]])
  704. try:
  705. return get_one_level(key, 1, self)
  706. except KeyError:
  707. return default
  708. except (TypeError, IndexError):
  709. if not list_ok:
  710. raise
  711. return default
  712. def __getitem__(self, key: Any) -> Any:
  713. try:
  714. return ordereddict.__getitem__(self, key)
  715. except KeyError:
  716. for merged in getattr(self, merge_attrib, []):
  717. # if isinstance(merged, tuple):
  718. # if key in merged[1]:
  719. # return merged[1][key]
  720. # else:
  721. if True:
  722. if key in merged:
  723. return merged[key]
  724. raise
  725. def __setitem__(self, key: Any, value: Any) -> None:
  726. # try to preserve the scalarstring type if setting an existing key to a new value
  727. if key in self:
  728. if (
  729. isinstance(value, str)
  730. and not isinstance(value, ScalarString)
  731. and isinstance(self[key], ScalarString)
  732. ):
  733. value = type(self[key])(value)
  734. ordereddict.__setitem__(self, key, value)
  735. self._ok.add(key)
  736. def _unmerged_contains(self, key: Any) -> Any:
  737. if key in self._ok:
  738. return True
  739. return None
  740. def __contains__(self, key: Any) -> bool:
  741. return bool(ordereddict.__contains__(self, key))
  742. def get(self, key: Any, default: Any = None) -> Any:
  743. try:
  744. return self.__getitem__(key)
  745. except: # NOQA
  746. return default
  747. def __repr__(self) -> Any:
  748. res = '{'
  749. sep = ''
  750. for k, v in self.items():
  751. res += f'{sep}{k!r}: {v!r}'
  752. if not sep:
  753. sep = ', '
  754. res += '}'
  755. return res
  756. def non_merged_items(self) -> Any:
  757. for x in ordereddict.__iter__(self):
  758. if x in self._ok:
  759. yield x, ordereddict.__getitem__(self, x)
  760. def __delitem__(self, key: Any) -> None:
  761. # for merged in getattr(self, merge_attrib, []):
  762. # if key in merged[1]:
  763. # value = merged[1][key]
  764. # break
  765. # else:
  766. # # not found in merged in stuff
  767. # ordereddict.__delitem__(self, key)
  768. # for referer in self._ref:
  769. # referer.update=_key_value(key)
  770. # return
  771. #
  772. # ordereddict.__setitem__(self, key, value) # merge might have different value
  773. # self._ok.discard(key)
  774. try:
  775. merge_value = getattr(self, merge_attrib)
  776. merge_pos = merge_value.merge_pos
  777. except AttributeError:
  778. merge_pos = -1
  779. if merge_pos >= 0:
  780. try:
  781. pos = list(ordereddict.keys(self)).index(key)
  782. # the merge is not in the dict, so don't use >=
  783. if merge_pos > pos:
  784. merge_value.merge_pos -= 1
  785. except ValueError:
  786. pass # let the removal of the key throw a "normal" error
  787. self._ok.discard(key)
  788. ordereddict.__delitem__(self, key)
  789. for referer in self._ref:
  790. referer.update_key_value(key)
  791. def __iter__(self) -> Any:
  792. for x in ordereddict.__iter__(self):
  793. yield x
  794. def pop(self, key: Any, default: Any = NotNone) -> Any:
  795. try:
  796. result = self[key]
  797. except KeyError:
  798. if default is NotNone:
  799. raise
  800. return default
  801. del self[key]
  802. return result
  803. def _keys(self) -> Any:
  804. for x in ordereddict.__iter__(self):
  805. yield x
  806. def __len__(self) -> int:
  807. return int(ordereddict.__len__(self))
  808. def __eq__(self, other: Any) -> bool:
  809. return bool(dict(self) == other)
  810. def keys(self) -> Any:
  811. return CommentedMapKeysView(self)
  812. def values(self) -> Any:
  813. return CommentedMapValuesView(self)
  814. def _items(self) -> Any:
  815. for x in ordereddict.__iter__(self):
  816. yield x, ordereddict.__getitem__(self, x)
  817. def items(self) -> Any:
  818. return CommentedMapItemsView(self)
  819. @property
  820. def merge(self) -> Any:
  821. if not hasattr(self, merge_attrib):
  822. setattr(self, merge_attrib, [])
  823. return getattr(self, merge_attrib)
  824. def copy(self) -> Any:
  825. x = type(self)() # update doesn't work
  826. for k, v in self._items():
  827. x[k] = v
  828. self.copy_attributes(x)
  829. return x
  830. def add_referent(self, cm: Any) -> None:
  831. if cm not in self._ref:
  832. self._ref.append(cm)
  833. def add_yaml_merge(self, value: Any) -> None:
  834. assert not hasattr(self, merge_attrib)
  835. setattr(self, merge_attrib, value)
  836. for v in value:
  837. # if isinstance(v, tuple):
  838. # assert len(v) == 2
  839. # # print('vvv', v, type(v[1]))
  840. # v[1].add_referent(self)
  841. # for k1, v1 in v[1].items():
  842. # if ordereddict.__contains__(self, k1):
  843. # continue
  844. # ordereddict.__setitem__(self, k1, v1)
  845. # else:
  846. if True:
  847. v.add_referent(self)
  848. for k1, v1 in v.items():
  849. if ordereddict.__contains__(self, k1):
  850. continue
  851. ordereddict.__setitem__(self, k1, v1)
  852. def update_key_value(self, key: Any) -> None:
  853. if key in self._ok:
  854. return
  855. for v in self.merge:
  856. if key in v[1]:
  857. ordereddict.__setitem__(self, key, v[1][key])
  858. return
  859. ordereddict.__delitem__(self, key)
  860. def __deepcopy__(self, memo: Any) -> Any:
  861. res = self.__class__()
  862. memo[id(self)] = res
  863. for k in self:
  864. res[k] = copy.deepcopy(self[k], memo)
  865. self.copy_attributes(res, memo=memo)
  866. return res
  867. # based on brownie mappings
  868. @classmethod # type: ignore
  869. def raise_immutable(cls: Any, *args: Any, **kwargs: Any) -> None:
  870. raise TypeError(f'{cls.__name__} objects are immutable')
  871. class CommentedKeyMap(CommentedBase, Mapping): # type: ignore
  872. __slots__ = Comment.attrib, '_od'
  873. """This primarily exists to be able to roundtrip keys that are mappings"""
  874. def __init__(self, *args: Any, **kw: Any) -> None:
  875. if hasattr(self, '_od'):
  876. raise_immutable(self)
  877. try:
  878. self._od = ordereddict(*args, **kw)
  879. except TypeError:
  880. raise
  881. __delitem__ = __setitem__ = clear = pop = popitem = setdefault = update = raise_immutable
  882. # need to implement __getitem__, __iter__ and __len__
  883. def __getitem__(self, index: Any) -> Any:
  884. return self._od[index]
  885. def __iter__(self) -> Iterator[Any]:
  886. for x in self._od.__iter__():
  887. yield x
  888. def __len__(self) -> int:
  889. return len(self._od)
  890. def __hash__(self) -> Any:
  891. return hash(tuple(self.items()))
  892. def __repr__(self) -> Any:
  893. if not hasattr(self, merge_attrib):
  894. return self._od.__repr__()
  895. return 'ordereddict(' + repr(list(self._od.items())) + ')'
  896. @classmethod
  897. def fromkeys(keys: Any, v: Any = None) -> Any:
  898. return CommentedKeyMap(dict.fromkeys(keys, v))
  899. def _yaml_add_comment(self, comment: Any, key: Optional[Any] = NotNone) -> None:
  900. if key is not NotNone:
  901. self.yaml_key_comment_extend(key, comment)
  902. else:
  903. self.ca.comment = comment
  904. def _yaml_add_eol_comment(self, comment: Any, key: Any) -> None:
  905. self._yaml_add_comment(comment, key=key)
  906. def _yaml_get_columnX(self, key: Any) -> Any:
  907. return self.ca.items[key][0].start_mark.column
  908. def _yaml_get_column(self, key: Any) -> Any:
  909. column = None
  910. sel_idx = None
  911. pre, post = key - 1, key + 1
  912. if pre in self.ca.items:
  913. sel_idx = pre
  914. elif post in self.ca.items:
  915. sel_idx = post
  916. else:
  917. # self.ca.items is not ordered
  918. for row_idx, _k1 in enumerate(self):
  919. if row_idx >= key:
  920. break
  921. if row_idx not in self.ca.items:
  922. continue
  923. sel_idx = row_idx
  924. if sel_idx is not None:
  925. column = self._yaml_get_columnX(sel_idx)
  926. return column
  927. def _yaml_get_pre_comment(self) -> Any:
  928. pre_comments: List[Any] = []
  929. if self.ca.comment is None:
  930. self.ca.comment = [None, pre_comments]
  931. else:
  932. self.ca.comment[1] = pre_comments
  933. return pre_comments
  934. class CommentedOrderedMap(CommentedMap):
  935. __slots__ = (Comment.attrib,)
  936. class CommentedSet(MutableSet, CommentedBase): # type: ignore # NOQA
  937. __slots__ = Comment.attrib, 'odict'
  938. def __init__(self, values: Any = None) -> None:
  939. self.odict = ordereddict()
  940. MutableSet.__init__(self)
  941. if values is not None:
  942. self |= values
  943. def _yaml_add_comment(
  944. self, comment: Any, key: Optional[Any] = NotNone, value: Optional[Any] = NotNone,
  945. ) -> None:
  946. """values is set to key to indicate a value attachment of comment"""
  947. if key is not NotNone:
  948. self.yaml_key_comment_extend(key, comment)
  949. return
  950. if value is not NotNone:
  951. self.yaml_value_comment_extend(value, comment)
  952. else:
  953. self.ca.comment = comment
  954. def _yaml_add_eol_comment(self, comment: Any, key: Any) -> None:
  955. """add on the value line, with value specified by the key"""
  956. self._yaml_add_comment(comment, value=key)
  957. def add(self, value: Any) -> None:
  958. """Add an element."""
  959. self.odict[value] = None
  960. def discard(self, value: Any) -> None:
  961. """Remove an element. Do not raise an exception if absent."""
  962. del self.odict[value]
  963. def __contains__(self, x: Any) -> Any:
  964. return x in self.odict
  965. def __iter__(self) -> Any:
  966. for x in self.odict:
  967. yield x
  968. def __len__(self) -> int:
  969. return len(self.odict)
  970. def __repr__(self) -> str:
  971. return f'set({self.odict.keys()!r})'
  972. class TaggedScalar(CommentedBase):
  973. # the value and style attributes are set during roundtrip construction
  974. def __init__(self, value: Any = None, style: Any = None, tag: Any = None) -> None:
  975. self.value = value
  976. self.style = style
  977. if tag is not None:
  978. if isinstance(tag, str):
  979. tag = Tag(suffix=tag)
  980. self.yaml_set_ctag(tag)
  981. def __str__(self) -> Any:
  982. return self.value
  983. def count(self, s: str, start: Optional[int] = None, end: Optional[int] = None) -> Any:
  984. return self.value.count(s, start, end)
  985. def __getitem__(self, pos: int) -> Any:
  986. return self.value[pos]
  987. def __repr__(self) -> str:
  988. return f'TaggedScalar(value={self.value!r}, style={self.style!r}, tag={self.tag!r})'
  989. def dump_comments(d: Any, name: str = "", sep: str = '.', out: Any = sys.stdout) -> None:
  990. """
  991. recursively dump comments, all but the toplevel preceded by the path
  992. in dotted form x.0.a
  993. """
  994. if isinstance(d, dict) and hasattr(d, 'ca'):
  995. if name:
  996. out.write(f'{name} {type(d)}\n')
  997. out.write(f'{d.ca!r}\n')
  998. for k in d:
  999. dump_comments(d[k], name=(name + sep + str(k)) if name else k, sep=sep, out=out)
  1000. elif isinstance(d, list) and hasattr(d, 'ca'):
  1001. if name:
  1002. out.write(f'{name} {type(d)}\n')
  1003. out.write(f'{d.ca!r}\n')
  1004. for idx, k in enumerate(d):
  1005. dump_comments(
  1006. k, name=(name + sep + str(idx)) if name else str(idx), sep=sep, out=out,
  1007. )