You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1178 lines
37 KiB

  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, Optional, 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. ma0 = getattr(self, merge_attrib, [[-1]])[0]
  666. merge_pos = ma0[0]
  667. except 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. idx_min = pos
  673. idx_max = len(self._ok)
  674. else:
  675. idx_min = pos - 1
  676. idx_max = len(self._ok)
  677. else:
  678. idx_min = pos
  679. idx_max = len(self._ok)
  680. self[key] = value # at the end
  681. # print(f'{idx_min=} {idx_max=}')
  682. for idx in range(idx_min, idx_max):
  683. self.move_to_end(keys[idx])
  684. self._ok.add(key)
  685. # for referer in self._ref:
  686. # for keytmp in keys:
  687. # referer.update_key_value(keytmp)
  688. if comment is not None:
  689. self.yaml_add_eol_comment(comment, key=key)
  690. def mlget(self, key: Any, default: Any = None, list_ok: Any = False) -> Any:
  691. """multi-level get that expects dicts within dicts"""
  692. if not isinstance(key, list):
  693. return self.get(key, default)
  694. # assume that the key is a list of recursively accessible dicts
  695. def get_one_level(key_list: Any, level: Any, d: Any) -> Any:
  696. if not list_ok:
  697. assert isinstance(d, dict)
  698. if level >= len(key_list):
  699. if level > len(key_list):
  700. raise IndexError
  701. return d[key_list[level - 1]]
  702. return get_one_level(key_list, level + 1, d[key_list[level - 1]])
  703. try:
  704. return get_one_level(key, 1, self)
  705. except KeyError:
  706. return default
  707. except (TypeError, IndexError):
  708. if not list_ok:
  709. raise
  710. return default
  711. def __getitem__(self, key: Any) -> Any:
  712. try:
  713. return ordereddict.__getitem__(self, key)
  714. except KeyError:
  715. for merged in getattr(self, merge_attrib, []):
  716. if key in merged[1]:
  717. return merged[1][key]
  718. raise
  719. def __setitem__(self, key: Any, value: Any) -> None:
  720. # try to preserve the scalarstring type if setting an existing key to a new value
  721. if key in self:
  722. if (
  723. isinstance(value, str)
  724. and not isinstance(value, ScalarString)
  725. and isinstance(self[key], ScalarString)
  726. ):
  727. value = type(self[key])(value)
  728. ordereddict.__setitem__(self, key, value)
  729. self._ok.add(key)
  730. def _unmerged_contains(self, key: Any) -> Any:
  731. if key in self._ok:
  732. return True
  733. return None
  734. def __contains__(self, key: Any) -> bool:
  735. return bool(ordereddict.__contains__(self, key))
  736. def get(self, key: Any, default: Any = None) -> Any:
  737. try:
  738. return self.__getitem__(key)
  739. except: # NOQA
  740. return default
  741. def __repr__(self) -> Any:
  742. res = '{'
  743. sep = ''
  744. for k, v in self.items():
  745. res += f'{sep}{k!r}: {v!r}'
  746. if not sep:
  747. sep = ', '
  748. res += '}'
  749. return res
  750. def non_merged_items(self) -> Any:
  751. for x in ordereddict.__iter__(self):
  752. if x in self._ok:
  753. yield x, ordereddict.__getitem__(self, x)
  754. def __delitem__(self, key: Any) -> None:
  755. # for merged in getattr(self, merge_attrib, []):
  756. # if key in merged[1]:
  757. # value = merged[1][key]
  758. # break
  759. # else:
  760. # # not found in merged in stuff
  761. # ordereddict.__delitem__(self, key)
  762. # for referer in self._ref:
  763. # referer.update=_key_value(key)
  764. # return
  765. #
  766. # ordereddict.__setitem__(self, key, value) # merge might have different value
  767. # self._ok.discard(key)
  768. self._ok.discard(key)
  769. ordereddict.__delitem__(self, key)
  770. for referer in self._ref:
  771. referer.update_key_value(key)
  772. def __iter__(self) -> Any:
  773. for x in ordereddict.__iter__(self):
  774. yield x
  775. def pop(self, key: Any, default: Any = NotNone) -> Any:
  776. try:
  777. result = self[key]
  778. except KeyError:
  779. if default is NotNone:
  780. raise
  781. return default
  782. del self[key]
  783. return result
  784. def _keys(self) -> Any:
  785. for x in ordereddict.__iter__(self):
  786. yield x
  787. def __len__(self) -> int:
  788. return int(ordereddict.__len__(self))
  789. def __eq__(self, other: Any) -> bool:
  790. return bool(dict(self) == other)
  791. def keys(self) -> Any:
  792. return CommentedMapKeysView(self)
  793. def values(self) -> Any:
  794. return CommentedMapValuesView(self)
  795. def _items(self) -> Any:
  796. for x in ordereddict.__iter__(self):
  797. yield x, ordereddict.__getitem__(self, x)
  798. def items(self) -> Any:
  799. return CommentedMapItemsView(self)
  800. @property
  801. def merge(self) -> Any:
  802. if not hasattr(self, merge_attrib):
  803. setattr(self, merge_attrib, [])
  804. return getattr(self, merge_attrib)
  805. def copy(self) -> Any:
  806. x = type(self)() # update doesn't work
  807. for k, v in self._items():
  808. x[k] = v
  809. self.copy_attributes(x)
  810. return x
  811. def add_referent(self, cm: Any) -> None:
  812. if cm not in self._ref:
  813. self._ref.append(cm)
  814. def add_yaml_merge(self, value: Any) -> None:
  815. for v in value:
  816. v[1].add_referent(self)
  817. for k1, v1 in v[1].items():
  818. if ordereddict.__contains__(self, k1):
  819. continue
  820. ordereddict.__setitem__(self, k1, v1)
  821. self.merge.extend(value)
  822. def update_key_value(self, key: Any) -> None:
  823. if key in self._ok:
  824. return
  825. for v in self.merge:
  826. if key in v[1]:
  827. ordereddict.__setitem__(self, key, v[1][key])
  828. return
  829. ordereddict.__delitem__(self, key)
  830. def __deepcopy__(self, memo: Any) -> Any:
  831. res = self.__class__()
  832. memo[id(self)] = res
  833. for k in self:
  834. res[k] = copy.deepcopy(self[k], memo)
  835. self.copy_attributes(res, memo=memo)
  836. return res
  837. # based on brownie mappings
  838. @classmethod # type: ignore
  839. def raise_immutable(cls: Any, *args: Any, **kwargs: Any) -> None:
  840. raise TypeError(f'{cls.__name__} objects are immutable')
  841. class CommentedKeyMap(CommentedBase, Mapping): # type: ignore
  842. __slots__ = Comment.attrib, '_od'
  843. """This primarily exists to be able to roundtrip keys that are mappings"""
  844. def __init__(self, *args: Any, **kw: Any) -> None:
  845. if hasattr(self, '_od'):
  846. raise_immutable(self)
  847. try:
  848. self._od = ordereddict(*args, **kw)
  849. except TypeError:
  850. raise
  851. __delitem__ = __setitem__ = clear = pop = popitem = setdefault = update = raise_immutable
  852. # need to implement __getitem__, __iter__ and __len__
  853. def __getitem__(self, index: Any) -> Any:
  854. return self._od[index]
  855. def __iter__(self) -> Iterator[Any]:
  856. for x in self._od.__iter__():
  857. yield x
  858. def __len__(self) -> int:
  859. return len(self._od)
  860. def __hash__(self) -> Any:
  861. return hash(tuple(self.items()))
  862. def __repr__(self) -> Any:
  863. if not hasattr(self, merge_attrib):
  864. return self._od.__repr__()
  865. return 'ordereddict(' + repr(list(self._od.items())) + ')'
  866. @classmethod
  867. def fromkeys(keys: Any, v: Any = None) -> Any:
  868. return CommentedKeyMap(dict.fromkeys(keys, v))
  869. def _yaml_add_comment(self, comment: Any, key: Optional[Any] = NotNone) -> None:
  870. if key is not NotNone:
  871. self.yaml_key_comment_extend(key, comment)
  872. else:
  873. self.ca.comment = comment
  874. def _yaml_add_eol_comment(self, comment: Any, key: Any) -> None:
  875. self._yaml_add_comment(comment, key=key)
  876. def _yaml_get_columnX(self, key: Any) -> Any:
  877. return self.ca.items[key][0].start_mark.column
  878. def _yaml_get_column(self, key: Any) -> Any:
  879. column = None
  880. sel_idx = None
  881. pre, post = key - 1, key + 1
  882. if pre in self.ca.items:
  883. sel_idx = pre
  884. elif post in self.ca.items:
  885. sel_idx = post
  886. else:
  887. # self.ca.items is not ordered
  888. for row_idx, _k1 in enumerate(self):
  889. if row_idx >= key:
  890. break
  891. if row_idx not in self.ca.items:
  892. continue
  893. sel_idx = row_idx
  894. if sel_idx is not None:
  895. column = self._yaml_get_columnX(sel_idx)
  896. return column
  897. def _yaml_get_pre_comment(self) -> Any:
  898. pre_comments: List[Any] = []
  899. if self.ca.comment is None:
  900. self.ca.comment = [None, pre_comments]
  901. else:
  902. self.ca.comment[1] = pre_comments
  903. return pre_comments
  904. class CommentedOrderedMap(CommentedMap):
  905. __slots__ = (Comment.attrib,)
  906. class CommentedSet(MutableSet, CommentedBase): # type: ignore # NOQA
  907. __slots__ = Comment.attrib, 'odict'
  908. def __init__(self, values: Any = None) -> None:
  909. self.odict = ordereddict()
  910. MutableSet.__init__(self)
  911. if values is not None:
  912. self |= values
  913. def _yaml_add_comment(
  914. self, comment: Any, key: Optional[Any] = NotNone, value: Optional[Any] = NotNone,
  915. ) -> None:
  916. """values is set to key to indicate a value attachment of comment"""
  917. if key is not NotNone:
  918. self.yaml_key_comment_extend(key, comment)
  919. return
  920. if value is not NotNone:
  921. self.yaml_value_comment_extend(value, comment)
  922. else:
  923. self.ca.comment = comment
  924. def _yaml_add_eol_comment(self, comment: Any, key: Any) -> None:
  925. """add on the value line, with value specified by the key"""
  926. self._yaml_add_comment(comment, value=key)
  927. def add(self, value: Any) -> None:
  928. """Add an element."""
  929. self.odict[value] = None
  930. def discard(self, value: Any) -> None:
  931. """Remove an element. Do not raise an exception if absent."""
  932. del self.odict[value]
  933. def __contains__(self, x: Any) -> Any:
  934. return x in self.odict
  935. def __iter__(self) -> Any:
  936. for x in self.odict:
  937. yield x
  938. def __len__(self) -> int:
  939. return len(self.odict)
  940. def __repr__(self) -> str:
  941. return f'set({self.odict.keys()!r})'
  942. class TaggedScalar(CommentedBase):
  943. # the value and style attributes are set during roundtrip construction
  944. def __init__(self, value: Any = None, style: Any = None, tag: Any = None) -> None:
  945. self.value = value
  946. self.style = style
  947. if tag is not None:
  948. if isinstance(tag, str):
  949. tag = Tag(suffix=tag)
  950. self.yaml_set_ctag(tag)
  951. def __str__(self) -> Any:
  952. return self.value
  953. def count(self, s: str, start: Optional[int] = None, end: Optional[int] = None) -> Any:
  954. return self.value.count(s, start, end)
  955. def __getitem__(self, pos: int) -> Any:
  956. return self.value[pos]
  957. def __repr__(self) -> str:
  958. return f'TaggedScalar(value={self.value!r}, style={self.style!r}, tag={self.tag!r})'
  959. def dump_comments(d: Any, name: str = "", sep: str = '.', out: Any = sys.stdout) -> None:
  960. """
  961. recursively dump comments, all but the toplevel preceded by the path
  962. in dotted form x.0.a
  963. """
  964. if isinstance(d, dict) and hasattr(d, 'ca'):
  965. if name:
  966. out.write(f'{name} {type(d)}\n')
  967. out.write(f'{d.ca!r}\n')
  968. for k in d:
  969. dump_comments(d[k], name=(name + sep + str(k)) if name else k, sep=sep, out=out)
  970. elif isinstance(d, list) and hasattr(d, 'ca'):
  971. if name:
  972. out.write(f'{name} {type(d)}\n')
  973. out.write(f'{d.ca!r}\n')
  974. for idx, k in enumerate(d):
  975. dump_comments(
  976. k, name=(name + sep + str(idx)) if name else str(idx), sep=sep, out=out,
  977. )