gen_py_protos.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import os
  2. from os import path
  3. import shutil
  4. import subprocess
  5. import sys
  6. import tempfile
  7. import argparse
  8. import re
  9. OUT_DIR_ARG = '--python_out='
  10. def main():
  11. parser = argparse.ArgumentParser()
  12. parser.add_argument("--suffixes", nargs="*", default=[])
  13. parser.add_argument("protoc_args", nargs=argparse.REMAINDER)
  14. script_args = parser.parse_args()
  15. args = script_args.protoc_args
  16. if args[0] == "--":
  17. args = args[1:]
  18. out_dir_orig = None
  19. out_dir_temp = None
  20. plugin_out_dirs_orig = {}
  21. for i in range(len(args)):
  22. if args[i].startswith(OUT_DIR_ARG):
  23. assert not out_dir_orig, 'Duplicate "{0}" param'.format(OUT_DIR_ARG)
  24. out_dir_orig = args[i][len(OUT_DIR_ARG):]
  25. out_dir_temp = tempfile.mkdtemp(dir=out_dir_orig)
  26. args[i] = OUT_DIR_ARG + out_dir_temp
  27. continue
  28. match = re.match(r"^(--(\w+)_out=).*", args[i])
  29. if match:
  30. plugin_out_dir_arg = match.group(1)
  31. plugin = match.group(2)
  32. assert plugin not in plugin_out_dirs_orig, 'Duplicate "{0}" param'.format(plugin_out_dir_arg)
  33. plugin_out_dirs_orig[plugin] = args[i][len(plugin_out_dir_arg):]
  34. assert plugin_out_dirs_orig[plugin] == out_dir_orig, 'Params "{0}" and "{1}" expected to have the same value'.format(OUT_DIR_ARG, plugin_out_dir_arg)
  35. args[i] = plugin_out_dir_arg + out_dir_temp
  36. assert out_dir_temp, 'Param "{0}" not found'.format(OUT_DIR_ARG)
  37. retcode = subprocess.call(args)
  38. assert not retcode, 'Protoc failed for command {}'.format(' '.join(args))
  39. for root_temp, dirs, files in os.walk(out_dir_temp):
  40. sub_dir = path.relpath(root_temp, out_dir_temp)
  41. root_orig = path.join(out_dir_orig, sub_dir)
  42. for d in dirs:
  43. d_orig = path.join(root_orig, d)
  44. if not path.exists(d_orig):
  45. os.mkdir(d_orig)
  46. for f in files:
  47. f_orig = f
  48. for suf in script_args.suffixes:
  49. if f.endswith(suf):
  50. f_orig = f[:-len(suf)] + "__int__" + suf
  51. break
  52. os.rename(path.join(root_temp, f), path.join(root_orig, f_orig))
  53. shutil.rmtree(out_dir_temp)
  54. if __name__ == '__main__':
  55. main()