#!/bin/python3
from __future__ import annotations
import json
from sys import argv, stdin
import yaml
def get_input(infile: str = None) -> str:
"""Handles getting input."""
if not infile:
return stdin.read()
else:
with open(infile) as f:
return f.read()
def set_output(data: str, outfile: str = None) -> None:
"""Handles setting output."""
if not outfile:
print(data)
else:
with open(outfile, 'w') as f:
f.write(data)
def y2j(data: str) -> str:
"""Convert from yaml to json."""
data = yaml.safe_load(data)
return json.dumps(data, indent=2)
def j2y(data: str) -> str:
"""Convert from json to yaml."""
data = json.loads(data)
return yaml.dump(data)
def usage(filename: str) -> None:
print(f'usage: {filename} [y2j|j2y] [infile] [outfile]')
print('\ty2j: convert yaml to json')
print('\tj2y: convert json to yaml')
print('\tinfile: the input file; if excluded, stdin will be used')
print('\toutfile: the output file; if excluded, stdout will be used')
def main() -> None:
if len(argv) < 2:
return usage(argv[0])
infile = argv[2] if len(argv) > 2 else None
outfile = argv[3] if len(argv) > 3 else None
if argv[1] == 'y2j':
set_output(y2j(get_input(infile)), outfile)
if argv[1] == 'j2y':
set_output(j2y(get_input(infile)), outfile)
def license():
"""Copyleft (c) 2022 k98kurz
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyleft notice and this permission notice appear in
all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""
return license.__doc__
if __name__ == '__main__':
main()
Comments