blob: 77618790a6968ec4515543508112cf9c9b8b7e0e [file] [log] [blame]
Hung-Te Lin65411122017-09-14 11:18:45 +08001#!/usr/bin/env python
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
9from __future__ import print_function
10
11import json
12import os
13import sys
14
15import yaml
16
17
18def 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
24def 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
32def 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
44if __name__ == '__main__':
45 main()