gen_py_protos.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import os
  2. from os import path
  3. import shutil
  4. import subprocess
  5. import tempfile
  6. import argparse
  7. import re
  8. OUT_DIR_ARG = '--python_out='
  9. def _noext(fname):
  10. return fname[: fname.rfind('.')]
  11. def main():
  12. parser = argparse.ArgumentParser()
  13. parser.add_argument("--suffixes", nargs="*", default=[])
  14. parser.add_argument("--input")
  15. parser.add_argument("--ns")
  16. parser.add_argument("protoc_args", nargs=argparse.REMAINDER)
  17. script_args = parser.parse_args()
  18. args = script_args.protoc_args
  19. if args[0] == "--":
  20. args = args[1:]
  21. out_dir_orig = None
  22. out_dir_temp = None
  23. plugin_out_dirs_orig = {}
  24. for i in range(len(args)):
  25. if args[i].startswith(OUT_DIR_ARG):
  26. assert not out_dir_orig, 'Duplicate "{0}" param'.format(OUT_DIR_ARG)
  27. out_dir_orig = args[i][len(OUT_DIR_ARG) :]
  28. out_dir_temp = tempfile.mkdtemp(dir=out_dir_orig)
  29. args[i] = OUT_DIR_ARG + out_dir_temp
  30. continue
  31. match = re.match(r"^(--(\w+)_out=).*", args[i])
  32. if match:
  33. plugin_out_dir_arg = match.group(1)
  34. plugin = match.group(2)
  35. assert plugin not in plugin_out_dirs_orig, 'Duplicate "{0}" param'.format(plugin_out_dir_arg)
  36. plugin_out_dirs_orig[plugin] = args[i][len(plugin_out_dir_arg) :]
  37. assert (
  38. plugin_out_dirs_orig[plugin] == out_dir_orig
  39. ), 'Params "{0}" and "{1}" expected to have the same value'.format(OUT_DIR_ARG, plugin_out_dir_arg)
  40. args[i] = plugin_out_dir_arg + out_dir_temp
  41. assert out_dir_temp, 'Param "{0}" not found'.format(OUT_DIR_ARG)
  42. retcode = subprocess.call(args)
  43. assert not retcode, 'Protoc failed for command {}'.format(' '.join(args))
  44. temp_name = out_dir_temp
  45. orig_name = out_dir_orig
  46. dir_name, file_name = path.split(script_args.input[len(script_args.ns) - 1 :])
  47. for part in dir_name.split('/'):
  48. temp_part = part.replace('-', '_')
  49. temp_name = path.join(temp_name, temp_part)
  50. assert path.exists(temp_name)
  51. orig_name = path.join(orig_name, part)
  52. if not path.exists(orig_name):
  53. os.mkdir(orig_name)
  54. orig_base_name = _noext(file_name)
  55. temp_base_name = orig_base_name.replace('-', '_')
  56. for suf in script_args.suffixes:
  57. temp_file_name = path.join(temp_name, temp_base_name + suf)
  58. assert path.exists(temp_file_name)
  59. orig_file_name = path.join(orig_name, orig_base_name + '__int__' + suf)
  60. os.rename(temp_file_name, orig_file_name)
  61. shutil.rmtree(out_dir_temp)
  62. if __name__ == '__main__':
  63. main()