-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat_yaml.py
47 lines (39 loc) · 1.23 KB
/
format_yaml.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""Command-line tool to validate and pretty-print YAML"""
import argparse
import sys
from ruamel.yaml import YAML
def parse_args():
description = (
"A simple command line interface to validate and pretty-print YAML objects."
)
parser = argparse.ArgumentParser(description=description)
parser.add_argument(
"infile",
nargs="?",
type=argparse.FileType(encoding="utf-8"),
help="a JSON file to be validated or pretty-printed",
default=sys.stdin,
)
parser.add_argument(
"outfile",
nargs="?",
type=argparse.FileType("w", encoding="utf-8"),
help="write the output of infile to outfile",
default=sys.stdout,
)
return parser.parse_args()
def main():
options = parse_args()
yaml = YAML()
yaml.preserve_quotes = True # double quotes remain double quotes, for lesser diffs
yaml.indent(mapping=2, sequence=4, offset=2)
with options.infile as infile, options.outfile as outfile:
try:
yaml.dump(yaml.load(infile), outfile)
except ValueError as ex:
raise SystemExit from ex
if __name__ == "__main__":
try:
main()
except BrokenPipeError as exc:
sys.exit(exc.errno)