gen_py_protos.py 2.6 KB

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