cli.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import os, sys, re, stat, errno, json, tempfile, contextlib
  2. import yaml, pyaml
  3. @contextlib.contextmanager
  4. def safe_replacement(path, *open_args, mode=None, xattrs=None, **open_kws):
  5. 'Context to atomically create/replace file-path in-place unless errors are raised'
  6. path = str(path)
  7. if mode is None:
  8. try: mode = stat.S_IMODE(os.lstat(path).st_mode)
  9. except FileNotFoundError: pass
  10. if xattrs is None and getattr(os, 'getxattr', None): # MacOS
  11. try: xattrs = dict((k, os.getxattr(path, k)) for k in os.listxattr(path))
  12. except FileNotFoundError: pass
  13. except OSError as err:
  14. if err.errno != errno.ENOTSUP: raise
  15. open_kws.update( delete=False,
  16. dir=os.path.dirname(path), prefix=os.path.basename(path) + '.' )
  17. if not open_args: open_kws.setdefault('mode', 'w')
  18. with tempfile.NamedTemporaryFile(*open_args, **open_kws) as tmp:
  19. try:
  20. if mode is not None: os.fchmod(tmp.fileno(), mode)
  21. if xattrs:
  22. for k, v in xattrs.items(): os.setxattr(path, k, v)
  23. yield tmp
  24. if not tmp.closed: tmp.flush()
  25. try: os.fdatasync(tmp)
  26. except AttributeError: pass # MacOS
  27. os.rename(tmp.name, path)
  28. finally:
  29. try: os.unlink(tmp.name)
  30. except FileNotFoundError: pass
  31. def file_line_iter(src, sep='\0\n', bs=128 * 2**10):
  32. 'Generator for src-file chunks, split by any of the separator chars'
  33. buff0 = buff = ''
  34. while True:
  35. eof = len(buff := src.read(bs)) < bs
  36. while buff:
  37. for n in sorted(buff.find(c) for c in sep):
  38. if n >= 0: break
  39. else: buff0 += buff; break
  40. chunk, buff = buff[:n], buff[n+1:]
  41. buff0, chunk = '', buff0 + chunk
  42. yield chunk
  43. if eof: break
  44. if buff0: yield buff0
  45. def main(argv=None, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr):
  46. import argparse, textwrap
  47. dd = lambda text: re.sub( r' \t+', ' ',
  48. textwrap.dedent(text).strip('\n') + '\n' ).replace('\t', ' ')
  49. parser = argparse.ArgumentParser(
  50. formatter_class=argparse.RawTextHelpFormatter,
  51. description='Process and dump prettified YAML to stdout.')
  52. parser.add_argument('path', nargs='*', metavar='path', default=list(), help=dd('''
  53. Path(s) to YAML to read (default/empty: use stdin).
  54. With multiple paths, will output YAML documents from each one in the same order.'''))
  55. parser.add_argument('-r', '--replace', action='store_true',
  56. help='Replace specified YAML file(s) with prettified version in-place.')
  57. parser.add_argument('-o', '--out-file', metavar='file-path',
  58. help='Write output to specified file instead of standard output.')
  59. parser.add_argument('-w', '--width', type=int, metavar='chars', help=dd('''
  60. Max line width hint to pass to pyyaml for the dump.
  61. Only used to format scalars and collections (e.g. lists).'''))
  62. parser.add_argument('-v', '--vspacing', metavar='N[/M][g]', help=dd('''
  63. Custom thresholds for when to add vertical spacing (empty lines),
  64. to visually separate items in overly long YAML lists/mappings.
  65. "long" means both >split-lines in line-length and has >split-count items.
  66. Value has N[/M][g] format, with default being something like 40/2.
  67. N = min number of same-indent lines in a section to split.
  68. M = min count of values in a list/mapping to split.
  69. "g" can be added to clump single-line values at the top of such lists/maps.
  70. "s" to split all-onliner blocks of values.
  71. Values examples: 20g, 5/1g, 60/4, gs, 10.'''))
  72. parser.add_argument('-l', '--lines', action='store_true', help=dd('''
  73. Read input as a list of \\0 (ascii null char) or newline-separated
  74. json/yaml "lines", common with loggers or other incremental data dumps.
  75. Each input entry will be exported as a separate YAML document (after "---").
  76. Empty or whitespace-only input entries are skipped without errors.'''))
  77. parser.add_argument('-q', '--quiet', action='store_true',
  78. help='Disable sanity-check on the output and suppress stderr warnings.')
  79. opts = parser.parse_args(sys.argv[1:] if argv is None else argv)
  80. pyaml_kwargs = dict()
  81. if opts.width: pyaml_kwargs['width'] = opts.width
  82. if vspacing := opts.vspacing:
  83. if not (m := re.search(r'^(\d+(?:/\d+)?)?([gs]+)?$', vspacing)):
  84. parser.error(f'Unrecognized -v/--vspacing spec: {vspacing!r}')
  85. vspacing, (vsplit, flags) = dict(), m.groups()
  86. if flags:
  87. if 's' in flags: vspacing['oneline_split'] = True
  88. if 'g' in flags: pyaml_kwargs['sort_dicts'] = pyaml.PYAMLSort.oneline_group
  89. if vsplit:
  90. lines, _, count = vsplit.strip().strip('/').partition('/')
  91. if lines: vspacing['split_lines'] = int(lines.strip())
  92. if count: vspacing['split_count'] = int(count.strip())
  93. if vspacing: pyaml_kwargs['vspacing'] = vspacing
  94. if not all(paths := opts.path or ['']) and opts.replace:
  95. parser.error('-r/--replace option can only be used with a file path, not stdin')
  96. if opts.out_file and opts.replace:
  97. parser.error('-r/--replace and -o/--out-file options cannot be used at the same time')
  98. with contextlib.ExitStack() as srcs:
  99. data = list([p, srcs.enter_context(open(p)) if p else stdin] for p in (paths or ['']))
  100. for d in data: d[1] = list( yaml.safe_load_all(d[1]) if not opts.lines else
  101. (yaml.safe_load(chunk) for chunk in file_line_iter(d[1]) if chunk.strip()) )
  102. for d in data: d.append(
  103. pyaml.dump(d[1][0], **pyaml_kwargs) # avoid leading "---" if possible
  104. if len(data) == len(d[1]) == 1 else pyaml.dump_all(d[1], **pyaml_kwargs) )
  105. if not opts.quiet:
  106. try:
  107. for p, d, ys in data:
  108. data_chk = list(yaml.safe_load_all(ys))
  109. try: data_hash = json.dumps(d, sort_keys=True)
  110. except: pass # too complex for checking with json
  111. else:
  112. if json.dumps(data_chk, sort_keys=True) != data_hash:
  113. raise AssertionError('Data from before/after pyaml does not match')
  114. except Exception as err:
  115. p_err = lambda *a,**kw: print(*a, **kw, file=stderr, flush=True)
  116. p_err( 'WARNING: Failed to parse produced YAML output for'
  117. f' <{p or "stdin"}> back to same data, it is likely too complicated for pyaml' )
  118. err = f'[{err.__class__.__name__}] {err}'
  119. p_err(' raised error: ' + ' // '.join(map(str.strip, err.split('\n'))))
  120. with contextlib.ExitStack() as dsts:
  121. if opts.replace:
  122. for d in data: d[0] = dsts.enter_context(safe_replacement(d[0]))
  123. elif p := opts.out_file:
  124. dst = dsts.enter_context( safe_replacement(p) if not
  125. any(p.startswith(pre) for pre in ['/dev/', '/proc/']) else open(p, 'w') )
  126. for d in data: d[0] = dst
  127. else:
  128. for d in data: d[0] = stdout
  129. for dst, d, ys in data: dst.write(ys)