Commit a8fe953e authored by Alejandro Homs Puron's avatar Alejandro Homs Puron Committed by Alejandro Homs Puron
Browse files

[TANGO_RES_2_JSON] Refactoring

parent 82dd4bc2
......@@ -6,14 +6,6 @@ import argparse
import json
from contextlib import closing
parser = argparse.ArgumentParser(description='Tango DB res -> JSON converter.')
parser.add_argument('res_in', nargs='?', default='-',
help='input Tango DB res. file name or "-" for stdin')
parser.add_argument('json_out', nargs='?', default='-',
help='output JSON file name or "-" for stdout')
args = parser.parse_args()
def load_tango_res(f):
executable = 'lima_launcher'
klass = 'LimaLauncher'
......@@ -66,22 +58,36 @@ def load_tango_res(f):
return dict(executable=executable, server=server, klass=klass,
device=device, config=config)
def json_indent(x, levels=1, indent=4):
def json_indent_body(x, levels=1, indent=4):
raw_lines = x.split('\n')
lines = [' ' * (levels * indent) + l for l in raw_lines[1:-1]]
return '\n'.join(raw_lines[:1] + lines + raw_lines[-1:])
return raw_lines[:1] + lines + raw_lines[-1:]
def main():
parser = argparse.ArgumentParser(description=('Tango DB res -> '
'JSON converter.'))
parser.add_argument('res_in', nargs='?', default='-',
help='input Tango DB res. file name or "-" for stdin')
parser.add_argument('json_out', nargs='?', default='-',
help='output JSON file name or "-" for stdout')
out_file = sys.stdout if args.json_out == '-' else open(args.json_out, 'wt')
with closing(out_file):
in_file = sys.stdin if args.res_in == '-' else open(args.res_in, 'rt')
with closing(in_file):
data = load_tango_res(in_file)
json_data = dict([(k, v if k == 'config' else f'"{v}"')
for k, v in data.items()])
args = parser.parse_args()
out_file = sys.stdout if args.json_out == '-' else open(args.json_out, 'wt')
with closing(out_file):
in_file = sys.stdin if args.res_in == '-' else open(args.res_in, 'rt')
with closing(in_file):
data = load_tango_res(in_file)
data = {k: v if k == 'config' else f'"{v}"' for k, v in data.items()}
keys = ['executable', 'server', 'klass', 'device', 'config']
good_key = lambda x: 'class' if x == 'klass' else x
json_lines = ['{']
json_lines += [',\n'.join([f'"{good_key(k)}": {json_data[k]}'
json_lines += [',\n'.join([f'"{good_key(k)}": {data[k]}'
for k in keys])]
json_lines += ['}']
out_file.write(json_indent('\n'.join(json_lines)) + '\n')
lines = json_indent_body('\n'.join(json_lines))
out_file.write('\n'.join(lines + ['']))
if __name__ == '__main__':
main()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment