34 lines
946 B
Python
34 lines
946 B
Python
#!/usr/bin/env python3
|
|
"""Re-format YAML passed on stdin or read from any arguments."""
|
|
|
|
import yaml
|
|
import sys
|
|
|
|
|
|
# https://stackoverflow.com/a/72265455
|
|
def str_presenter(dumper, data):
|
|
if len(data.splitlines()) > 1 or "\n" in data:
|
|
text_list = [line.rstrip() for line in data.splitlines()]
|
|
fixed_data = "\n".join(text_list)
|
|
return dumper.represent_scalar("tag:yaml.org,2002:str", fixed_data, style="|")
|
|
return dumper.represent_scalar("tag:yaml.org,2002:str", data)
|
|
|
|
|
|
yaml.add_representer(str, str_presenter)
|
|
|
|
|
|
def ymmw(files):
|
|
if not files:
|
|
files=[sys.stdin]
|
|
|
|
for f in files:
|
|
try:
|
|
print(f)
|
|
print(yaml.dump(yaml.load(open(f) if not f == sys.stdin else f, Loader=yaml.FullLoader)), end='')
|
|
except OSError as ex:
|
|
sys.exit(f"""ERROR: Couldn't read input from stdin, or couldn't write output to stdout. Exiting.
|
|
|
|
{ex}""")
|
|
|
|
if __name__ == '__main__':
|
|
ymmw(sys.argv[1:])
|