__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import os, sys, io, re, string, warnings, enum, pathlib, collections as cs
  2. import yaml
  3. PYAMLSort = enum.Enum('PYAMLSort', 'none keys oneline_group')
  4. class PYAMLDumper(yaml.dumper.SafeDumper):
  5. class str_ext(str): __slots__ = 'ext',
  6. pyaml_anchor_decode = None # imported from unidecode module when needed
  7. pyaml_sort_dicts = pyaml_repr_unknown = None
  8. def __init__( self, *args, sort_dicts=None, force_embed=True,
  9. string_val_style=None, anchor_len_max=40, repr_unknown=False, **kws ):
  10. self.pyaml_force_embed = force_embed
  11. self.pyaml_string_val_style = string_val_style
  12. self.pyaml_anchor_len_max = anchor_len_max
  13. self.pyaml_repr_unknown = repr_unknown
  14. if isinstance(sort_dicts, PYAMLSort):
  15. if sort_dicts is sort_dicts.none: kws['sort_keys'] = False
  16. elif sort_dicts is sort_dicts.keys: kws['sort_keys'] = True
  17. else: self.pyaml_sort_dicts, kws['sort_keys'] = sort_dicts, False
  18. elif sort_dicts is not None: kws['sort_keys'] = sort_dicts # for compatibility
  19. return super().__init__(*args, **kws)
  20. @staticmethod
  21. def pyaml_transliterate(s):
  22. if unidecode_missing := not all(ord(c) < 128 for c in s):
  23. if (unidecode := PYAMLDumper.pyaml_anchor_decode) is None:
  24. try: from unidecode import unidecode
  25. except ImportError: unidecode = False
  26. PYAMLDumper.pyaml_anchor_decode = unidecode
  27. if unidecode: unidecode_missing, s = None, unidecode(s)
  28. return re.sub(r'[^-_a-z0-9]+', '_', s.lower()), unidecode_missing
  29. def anchor_node(self, node, hints=list()):
  30. if node in self.anchors:
  31. if self.anchors[node] is None and not self.pyaml_force_embed:
  32. if hints:
  33. nid, uc = self.pyaml_transliterate('_-_'.join(h.value for h in hints))
  34. if len(nid) > (n := self.pyaml_anchor_len_max - 9) + 9:
  35. nid = f'{nid[:n//2]}-_-{nid[-n//2:]}_{self.generate_anchor(node)}'
  36. elif uc is True: nid = f'{nid}_{self.generate_anchor(node)}'
  37. else: nid = self.generate_anchor(node)
  38. self.anchors[node] = nid
  39. else:
  40. self.anchors[node] = None
  41. if isinstance(node, yaml.nodes.SequenceNode):
  42. for item in node.value: self.anchor_node(item)
  43. elif isinstance(node, yaml.nodes.MappingNode):
  44. for key, value in node.value:
  45. self.anchor_node(key)
  46. self.anchor_node(value, hints=hints+[key])
  47. def ignore_aliases(self, data):
  48. if self.pyaml_force_embed: return True
  49. return super().ignore_aliases(data)
  50. def expect_block_sequence(self):
  51. self.increase_indent(flow=False, indentless=False)
  52. self.state = self.expect_first_block_sequence_item
  53. def expect_block_sequence_item(self, first=False):
  54. if not first and isinstance(self.event, yaml.events.SequenceEndEvent):
  55. self.indent = self.indents.pop()
  56. self.state = self.states.pop()
  57. else:
  58. self.write_indent()
  59. self.write_indicator('-', True, indention=True)
  60. self.states.append(self.expect_block_sequence_item)
  61. self.expect_node(sequence=True)
  62. def check_simple_key(self):
  63. res = super().check_simple_key()
  64. if self.analysis: self.analysis.allow_flow_plain = False
  65. return res
  66. def choose_scalar_style(self, _re1=re.compile(r':(\s|\Z)')):
  67. if self.states[-1] == self.expect_block_mapping_simple_value:
  68. # Mapping keys - disable overriding string style, strip comments
  69. if self.pyaml_string_val_style: self.event.style = 'plain'
  70. if isinstance(self.analysis.scalar, self.str_ext):
  71. self.analysis.scalar = str(self.event.value)
  72. # Do default thing for complicated stuff
  73. if self.event.style != 'plain': return super().choose_scalar_style()
  74. # Make sure style isn't overidden for strings like list/mapping items
  75. if (s := self.event.value).startswith('- ') or _re1.search(s): return "'"
  76. # Returned style=None picks write_plain in Emitter.process_scalar
  77. def write_indicator(self, indicator, *args, **kws):
  78. if indicator == '...': return # presumably it's useful somewhere, but don't care
  79. super().write_indicator(indicator, *args, **kws)
  80. def represent_str(self, data):
  81. if not (style := self.pyaml_string_val_style):
  82. if '\n' in data[:-1]:
  83. style = 'literal'
  84. for line in data.splitlines():
  85. if len(line) > self.best_width: break
  86. else: style = '|'
  87. return yaml.representer.ScalarNode('tag:yaml.org,2002:str', data, style=style)
  88. def represent_mapping_sort_oneline(self, kv):
  89. key, value = kv
  90. if not value or isinstance(value, (int, float)): v = 1
  91. elif isinstance(value, str) and '\n' not in value: v = 1
  92. else: v = 2
  93. if isinstance(key, (int, float)): k = 1
  94. elif isinstance(key, str): k = 2
  95. elif key is None: k = 4
  96. else: k, key = 3, f'{type(key)}\0{key}' # best-effort sort for all other types
  97. return v, k, key
  98. def represent_mapping(self, tag, mapping, *args, **kws):
  99. if self.pyaml_sort_dicts is PYAMLSort.oneline_group:
  100. try:
  101. mapping = dict(sorted( mapping.items(),
  102. key=self.represent_mapping_sort_oneline ))
  103. except TypeError: pass # for subtype comparison fails
  104. return super().represent_mapping(tag, mapping, *args, **kws)
  105. def represent_undefined(self, data):
  106. if isinstance(data, tuple) and hasattr(data, '_make') and hasattr(data, '_asdict'):
  107. return self.represent_dict(data._asdict()) # assuming namedtuple
  108. if isinstance(data, cs.abc.Mapping): return self.represent_dict(data) # dict-like
  109. if type(data).__class__.__module__ == 'enum':
  110. node = self.represent_data(data.value)
  111. node.value = self.str_ext(node.value)
  112. node.value.ext = f'# {data.__class__.__name__}.{data.name}'
  113. return node
  114. if hasattr(type(data), '__dataclass_fields__'):
  115. try: import dataclasses as dcs
  116. except ImportError: pass # can still be something else
  117. else: return self.represent_dict(dcs.asdict(data))
  118. try: # this is for numpy arrays, and the likes
  119. if not callable(getattr(data, 'tolist', None)): raise AttributeError
  120. except Exception: pass # can raise other errors with custom types
  121. else: return self.represent_data(data.tolist())
  122. if self.pyaml_repr_unknown: # repr value as a short oneliner
  123. if isinstance(n := self.pyaml_repr_unknown, bool): n = 50
  124. if len(s := repr(data).replace('\n', '⏎')) > n + 10:
  125. if (m := re.search(r' at (0x[0-9a-f]+>)\Z', s)) and n > len(m[0]):
  126. s = s[:n-len(m[0])] + f' ~[{n:,d}/{len(s):,d}]~ ' + m[1]
  127. else: s = s[:n] + f' ...[{n:,d}/{len(s):,d}]'
  128. cls, node = data.__class__, self.represent_data(s)
  129. if (st := f'{cls.__module__}.{cls.__name__}') in s: st = 'value'
  130. node.value = (s := self.str_ext(s)); s.ext = f'# python {st}'; return node
  131. return super().represent_undefined(data) # will raise RepresenterError
  132. def write_ext(self, func, text, *args, **kws):
  133. # Emitter write-funcs extension to append comments to values
  134. if ext := getattr(text, 'ext', None):
  135. # Commented values are enums/class-reprs and such, which shouldn't be split
  136. if args: args = [False, *args[1:]]
  137. else: kws['split'] = False
  138. getattr(super(), f'write_{func}')(text, *args, **kws)
  139. if ext: super().write_plain(ext, split=False)
  140. write_folded = lambda s,v,*a,**kw: s.write_ext('folded', v, *a, **kw)
  141. write_literal = lambda s,v,*a,**kw: s.write_ext('literal', v, *a, **kw)
  142. write_single_quoted = lambda s,v,*a,**kw: s.write_ext('single_quoted', v, *a, **kw)
  143. write_double_quoted = lambda s,v,*a,**kw: s.write_ext('double_quoted', v, *a, **kw)
  144. write_plain = lambda s,v,split=True: s.write_ext('plain', v, split)
  145. # Unsafe was a separate class in <23.x versions, left here for compatibility
  146. UnsafePYAMLDumper = PYAMLDumper
  147. add_representer = PYAMLDumper.add_representer
  148. add_representer( bool,
  149. lambda s,o: s.represent_scalar('tag:yaml.org,2002:bool', ['no', 'yes'][o]) )
  150. add_representer( type(None),
  151. lambda s,o: s.represent_scalar('tag:yaml.org,2002:null', '') )
  152. add_representer(str, PYAMLDumper.represent_str)
  153. add_representer(cs.defaultdict, PYAMLDumper.represent_dict)
  154. add_representer(cs.OrderedDict, PYAMLDumper.represent_dict)
  155. add_representer(set, PYAMLDumper.represent_list)
  156. add_representer(type(pathlib.Path('')), lambda cls,o: cls.represent_data(str(o)))
  157. add_representer(None, PYAMLDumper.represent_undefined)
  158. def dump_add_vspacing( yaml_str,
  159. split_lines=40, split_count=2, oneline_group=False, oneline_split=False ):
  160. '''Add some newlines to separate overly long YAML lists/mappings.
  161. "long" means both >split_lines in length and has >split_count items.
  162. oneline_group - don't split consecutive oneliner list/map items.
  163. oneline_split - split long list/map consisting only of oneliner values.'''
  164. def _add_vspacing(lines):
  165. a = a_seq = ind_re = ind_re_sub = has_sub = None
  166. blocks, item_lines = list(), list()
  167. for n, line in enumerate(lines):
  168. if ind_re is None and (m := re.match(r'( *)([^# ].?)', line)):
  169. ind_re = re.compile(m[1] + r'\S')
  170. lines.append(f'{m[1]}.') # for last add_vspacing
  171. if ind_re_sub:
  172. if ind_re_sub.match(line): has_sub = True; continue
  173. if n - a > split_lines and (block := lines[a:n]):
  174. if a_seq: block.insert(0, lines[a-1].replace('- ', ' ', 1))
  175. blocks.append((a, n, _add_vspacing(block)[a_seq:]))
  176. ind_re_sub = None
  177. if ind_re.match(line): item_lines.append(n)
  178. if m := re.match(r'( *)(- )?\S.*:(\s|\Z)', line):
  179. a, a_seq, ind_re_sub = n+1, bool(m[2]), re.compile(m[1] + ' ')
  180. if ( split_items := len(lines) > split_lines and
  181. len(item_lines) > split_count and (oneline_split or has_sub) ):
  182. for n in item_lines:
  183. try:
  184. if ( oneline_group and ind_re
  185. and ind_re.match(lines[n-1].lstrip('\n'))
  186. and ind_re.match(lines[n+1].lstrip('\n')) ): continue
  187. except IndexError: continue
  188. lines[n] = f'\n{lines[n]}'
  189. for a, b, block in reversed(blocks): lines[a:b] = block
  190. if ind_re: lines.pop()
  191. if split_items: lines.append('')
  192. return lines
  193. yaml_str = '\n'.join(_add_vspacing(yaml_str.splitlines()))
  194. return re.sub(r'\n\n+', '\n\n', yaml_str.strip() + '\n')
  195. def dump( data, dst=None, safe=None, force_embed=True, vspacing=True,
  196. string_val_style=None, sort_dicts=None, multiple_docs=False, width=100,
  197. repr_unknown=False, **pyyaml_kws ):
  198. '''Serialize data as pretty-YAML to specified dst file-like object,
  199. or return as str with dst=str (default) or encoded to bytes with dst=bytes.'''
  200. if safe is not None:
  201. cat = DeprecationWarning if not safe else UserWarning
  202. warnings.warn( 'pyaml module "safe" arg/keyword is ignored as implicit'
  203. ' safe=maybe-true?, as of pyaml >= 23.x', category=cat, stacklevel=2 )
  204. if sort_dicts is not None and not isinstance(sort_dicts, PYAMLSort):
  205. warnings.warn( 'Using pyaml module sort_dicts as boolean is deprecated as of'
  206. ' pyaml >= 23.x - translated to sort_keys PyYAML keyword, use that instead',
  207. DeprecationWarning, stacklevel=2 )
  208. if stream := pyyaml_kws.pop('stream', None):
  209. if dst is not None and stream is not dst:
  210. raise TypeError( 'Using different pyaml dst='
  211. ' and pyyaml stream= options at the same time is not supported' )
  212. dst = stream
  213. elif dst is None: dst = str # old default
  214. buff = io.StringIO()
  215. Dumper = lambda *a,**kw: PYAMLDumper( *a, **kw,
  216. force_embed=force_embed, string_val_style=string_val_style,
  217. sort_dicts=sort_dicts, repr_unknown=repr_unknown )
  218. if not multiple_docs: data = [data]
  219. else: pyyaml_kws.setdefault('explicit_start', True)
  220. yaml.dump_all( data, buff, Dumper=Dumper, width=width,
  221. default_flow_style=False, allow_unicode=True, **pyyaml_kws )
  222. buff = buff.getvalue()
  223. if vspacing not in [None, False]:
  224. if vspacing is True: vspacing = dict()
  225. elif not isinstance(vspacing, dict):
  226. warnings.warn(
  227. 'Unsupported pyaml "vspacing" parameter type:'
  228. f' [{vspacing.__class__.__name__}] {vspacing}\n'
  229. 'As of pyaml >= 23.x it should be either True or keywords-dict'
  230. ' for pyaml_add_vspacing, and any other values are ignored,'
  231. ' enabling default vspacing behavior.', DeprecationWarning, stacklevel=2 )
  232. vspacing = dict()
  233. if sort_dicts is PYAMLSort.oneline_group: vspacing.setdefault('oneline_group', True)
  234. buff = dump_add_vspacing(buff, **vspacing)
  235. if dst is bytes: return buff.encode()
  236. elif dst is str: return buff
  237. else:
  238. try: dst.write(b'') # tests whether dst is str- or bytestream
  239. except TypeError: dst.write(buff)
  240. else: dst.write(buff.encode())
  241. # Simpler pyaml.dump() aliases
  242. def dump_all(data, *dump_args, **dump_kws):
  243. 'Alias to dump(list, multiple_docs=True) for API compatibility with pyyaml'
  244. return dump(data, *dump_args, multiple_docs=True, **dump_kws)
  245. def dumps(data, **dump_kws):
  246. 'Alias to dump() for API compatibility with stdlib conventions'
  247. return dump(data, **dump_kws)
  248. def pprint(*data, **dump_kws):
  249. 'Similar to how print() works, with any number of arguments and stdout-default'
  250. dst = dump_kws.pop('file', dump_kws.pop('dst', sys.stdout))
  251. if len(data) == 1: data, = data
  252. dump(data, dst=dst, **dump_kws)
  253. def debug(*data, **dump_kws):
  254. 'Same as pprint, but also repr-printing any non-yaml types'
  255. pprint(*data, repr_unknown=True, **dump_kws)
  256. _p = lambda *a,_p=print,**kw: _p(*a, **kw, flush=True) # to use here for debug
  257. p = print = pprint