Mike Frysinger | 63bb3c7 | 2019-09-01 15:16:26 -0400 | [diff] [blame] | 1 | #!/usr/bin/env python2 |
Hung-Te Lin | 6541112 | 2017-09-14 11:18:45 +0800 | [diff] [blame] | 2 | # Copyright 2017 The Chromium OS Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | """An utility to convert existing YAML files to JSON format.""" |
| 7 | |
| 8 | |
| 9 | from __future__ import print_function |
| 10 | |
| 11 | import json |
| 12 | import os |
| 13 | import sys |
| 14 | |
| 15 | import yaml |
| 16 | |
| 17 | |
| 18 | def ConvertYAMLToJSON(yaml_str, pretty_print=True): |
| 19 | kargs = dict( |
| 20 | indent=1, separators=(',', ': '), sort_keys=True) if pretty_print else {} |
| 21 | return json.dumps(yaml.load(yaml_str), **kargs) |
| 22 | |
| 23 | |
| 24 | def ConvertYAMLPathToJSONPath(yaml_path): |
| 25 | """Try to strip '.yaml' file extension and return a name ends with '.json'.""" |
| 26 | name, ext = os.path.splitext(yaml_path) |
| 27 | if ext.lower() != '.yaml': |
| 28 | name = yaml_path |
| 29 | return name + '.json' |
| 30 | |
| 31 | |
| 32 | def main(): |
| 33 | if not 1 < len(sys.argv) < 4: |
| 34 | exit('Usage: %s input [output]' % sys.argv[0]) |
| 35 | in_file = sys.argv[1] |
| 36 | out_file = sys.argv[2] if len(sys.argv) > 2 else ( |
| 37 | ConvertYAMLPathToJSONPath(in_file)) |
| 38 | print('%s => %s' % (in_file, out_file)) |
| 39 | with open(in_file) as f_in: |
| 40 | with open(out_file, 'w') as f_out: |
| 41 | f_out.write(ConvertYAMLToJSON(f_in.read())) |
| 42 | |
| 43 | |
| 44 | if __name__ == '__main__': |
| 45 | main() |