gen_proto.sh 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/bin/bash
  2. # 添加必要的工具路径
  3. export PATH=$PATH:/usr/local/bin:$(go env GOPATH)/bin
  4. # 进入 proto 文件目录
  5. cd bin/client_msg || { echo "Error: Failed to enter bin/client_msg"; exit 1; }
  6. # 目标目录(确保存在)
  7. TARGET_DIR="../../src/server/msg"
  8. mkdir -p "$TARGET_DIR" || { echo "Error: Failed to create $TARGET_DIR"; exit 1; }
  9. # 遍历所有 .proto 文件并编译
  10. for proto_file in *.proto; do
  11. if [ -f "$proto_file" ]; then
  12. echo "Compiling $proto_file..."
  13. # 生成 Go 代码(自动处理 go_package 路径)
  14. protoc --proto_path=. --go_out=paths=source_relative:. "$proto_file" || {
  15. echo "Error: protoc failed for $proto_file"
  16. exit 1
  17. }
  18. # 提取 go_package 名称(从 .proto 文件中解析)
  19. go_package=$(grep "^option go_package" "$proto_file" | awk -F'"' '{print $2}')
  20. if [ -z "$go_package" ]; then
  21. echo "Warning: Missing 'option go_package' in $proto_file, using default"
  22. go_package="msg"
  23. fi
  24. # 移动生成的 .pb.go 文件
  25. gen_file="${proto_file%.proto}.pb.go"
  26. if [ -f "$gen_file" ]; then
  27. mv "$gen_file" "$TARGET_DIR/" || {
  28. echo "Error: Failed to move $gen_file"
  29. exit 1
  30. }
  31. echo "Moved $gen_file to $TARGET_DIR/"
  32. else
  33. echo "Error: Generated file $gen_file not found"
  34. exit 1
  35. fi
  36. fi
  37. done
  38. echo "All proto files compiled and moved successfully!"