blob: c1ee6f6a264b71c0178d05e842cd3ed41302ff37 [file] [log] [blame]
Yilin Yang19da6932019-12-10 13:39:28 +08001#!/usr/bin/env python3
Hung-Te Lin65411122017-09-14 11:18:45 +08002# 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
Hung-Te Lin65411122017-09-14 11:18:45 +08008import json
9import os
10import sys
11
12import yaml
13
14
15def ConvertYAMLToJSON(yaml_str, pretty_print=True):
16 kargs = dict(
17 indent=1, separators=(',', ': '), sort_keys=True) if pretty_print else {}
18 return json.dumps(yaml.load(yaml_str), **kargs)
19
20
21def ConvertYAMLPathToJSONPath(yaml_path):
22 """Try to strip '.yaml' file extension and return a name ends with '.json'."""
23 name, ext = os.path.splitext(yaml_path)
24 if ext.lower() != '.yaml':
25 name = yaml_path
26 return name + '.json'
27
28
29def main():
30 if not 1 < len(sys.argv) < 4:
Fei Shao9cd93ea2020-06-16 18:31:22 +080031 sys.exit('Usage: %s input [output]' % sys.argv[0])
Hung-Te Lin65411122017-09-14 11:18:45 +080032 in_file = sys.argv[1]
33 out_file = sys.argv[2] if len(sys.argv) > 2 else (
34 ConvertYAMLPathToJSONPath(in_file))
35 print('%s => %s' % (in_file, out_file))
36 with open(in_file) as f_in:
37 with open(out_file, 'w') as f_out:
38 f_out.write(ConvertYAMLToJSON(f_in.read()))
39
40
41if __name__ == '__main__':
42 main()