convert_protocol_to_json.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/env python3
  2. # Copyright 2017 The Chromium 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. import argparse
  6. import json
  7. import os.path
  8. import sys
  9. import pdl
  10. def open_to_write(path):
  11. if sys.version_info >= (3,0):
  12. return open(path, 'w', encoding='utf-8')
  13. else:
  14. return open(path, 'wb')
  15. def main(argv):
  16. parser = argparse.ArgumentParser(description=(
  17. "Converts from .pdl to .json by invoking the pdl Python module."))
  18. parser.add_argument('--map_binary_to_string', type=bool,
  19. help=('If set, binary in the .pdl is mapped to a '
  20. 'string in .json. Client code will have to '
  21. 'base64 decode the string to get the payload.'))
  22. parser.add_argument("pdl_file", help="The .pdl input file to parse.")
  23. parser.add_argument("json_file", help="The .json output file write.")
  24. args = parser.parse_args(argv)
  25. file_name = os.path.normpath(args.pdl_file)
  26. input_file = open(file_name, "r")
  27. pdl_string = input_file.read()
  28. protocol = pdl.loads(pdl_string, file_name, args.map_binary_to_string)
  29. input_file.close()
  30. output_file = open_to_write(os.path.normpath(args.json_file))
  31. json.dump(protocol, output_file, indent=4, separators=(',', ': '))
  32. output_file.close()
  33. if __name__ == '__main__':
  34. sys.exit(main(sys.argv[1:]))