protogen.sh 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/bin/bash
  2. curentdirname=$(basename "$PWD")
  3. parentfulldir=$(dirname "$PWD")
  4. gomodfile=go.mod
  5. pbdir=pb # 指定proto所在目录
  6. # 判断是否有go.mod文件
  7. if [ ! -f "$gomodfile" ]; then
  8. echo "No '$gomodfile' file!"
  9. exit 1
  10. fi
  11. # 从go.mod中取出工程包名
  12. packname=`awk 'NR==1{print $2}' $gomodfile`
  13. # 判断当前目录名是否与go.mod中的module 名称相同,不同直接提示错误
  14. if [ "$packname" != "$curentdirname" ]; then
  15. echo "The module name is not the current directory! See 'go.mod'"
  16. exit 1
  17. fi
  18. # 判断是否有pb目录
  19. if [ ! -d $pbdir ]; then
  20. echo "No '$pbdir' directory!"
  21. exit 1
  22. fi
  23. # 取出操作系统
  24. OS=`uname -s`
  25. # 将pbdir目录下所有一级目录下的所有.proto文件作统一处理并生成.pb.go文件
  26. dir=$(ls -l $pbdir |awk '/^d/ {print $NF}')
  27. for i in $dir
  28. do
  29. cd $pbdir/$i
  30. # 判断是否有.proto文件
  31. num=$(ls *.proto 2> /dev/null | wc -l)
  32. if [ $num != 0 ] ; then
  33. if [ $OS == "Linux" ]; then
  34. # 替换以 package 开头的整行
  35. sed -i "s/^package.*$/package $i;/g" *.proto
  36. # 替换以 option go_package 开头的整行
  37. sed -i "s/^option go_package.*$/option go_package = \"$packname\/$pbdir\/$i\";/g" *.proto
  38. elif [ $OS == "Darwin" ]; then
  39. # 替换以 package 开头的整行
  40. sed -i '' "s/^package.*$/package $i;/g" *.proto
  41. # 替换以 option go_package 开头的整行
  42. sed -i '' "s/^option go_package.*$/option go_package = \"$packname\/$pbdir\/$i\";/g" *.proto
  43. else
  44. echo "Unsupport OS: "$OS
  45. fi
  46. protoc --go_out=$parentfulldir *.proto
  47. fi
  48. cd ../..
  49. done
  50. cd $pbdir
  51. # 判断是否有.proto文件
  52. num=$(ls *.proto 2> /dev/null | wc -l)
  53. if [ $num != 0 ] ; then
  54. if [ $OS == "Linux" ]; then
  55. # 替换以 option go_package 开头的整行
  56. sed -i "s/^option go_package.*$/option go_package = \"$packname\/$pbdir\";/g" *.proto
  57. elif [ $OS == "Darwin" ]; then
  58. # 替换以 option go_package 开头的整行
  59. sed -i '' "s/^option go_package.*$/option go_package = \"$packname\/$pbdir\";/g" *.proto
  60. else
  61. echo "Unsupport OS: "$OS
  62. fi
  63. protoc --go_out=plugins=grpc:$parentfulldir *.proto
  64. fi
  65. cd ../