|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + |
| 6 | + "google.golang.org/protobuf/compiler/protogen" |
| 7 | +) |
| 8 | + |
| 9 | +func main() { |
| 10 | + opts := protogen.Options{} |
| 11 | + opts.Run(func(gen *protogen.Plugin) error { |
| 12 | + for _, f := range gen.Files { |
| 13 | + if f.Generate { |
| 14 | + generateFile(gen, f) |
| 15 | + } |
| 16 | + } |
| 17 | + return nil |
| 18 | + }) |
| 19 | +} |
| 20 | + |
| 21 | +func generateFile(gen *protogen.Plugin, file *protogen.File) { |
| 22 | + filename := file.GeneratedFilenamePrefix + "_bash.pb.sh" |
| 23 | + g := gen.NewGeneratedFile(filename, file.GoImportPath) |
| 24 | + g.P("#!/usr/bin/env bash") |
| 25 | + g.P("set -euo pipefail") |
| 26 | + g.P() |
| 27 | + g.P("#################################################") |
| 28 | + g.P("# Code generated by protoc-gen-bash. DO NOT EDIT.") |
| 29 | + g.P("#") |
| 30 | + g.P("# source file: ", *file.Proto.Name) |
| 31 | + g.P("#################################################") |
| 32 | + g.P() |
| 33 | + g.P(`printf 'The messages defined in the provided proto file(s) are:\n'`) |
| 34 | + g.P() |
| 35 | + g.P(`printf '`) |
| 36 | + printMessages(g, file.Messages) |
| 37 | + g.P(`'`) |
| 38 | +} |
| 39 | + |
| 40 | +// printMessages traverses nested Messages recursively and prints their |
| 41 | +// FullNames along with their Field information |
| 42 | +func printMessages(g *protogen.GeneratedFile, msgs []*protogen.Message) { |
| 43 | + for _, msg := range msgs { |
| 44 | + var fields []string |
| 45 | + for _, field := range msg.Fields { |
| 46 | + fieldName := string(field.Desc.Name()) |
| 47 | + |
| 48 | + // Cardinality tells us e.g. if a field is repeated |
| 49 | + fieldCardinality := field.Desc.Cardinality().String() |
| 50 | + if fieldCardinality != "repeated" { |
| 51 | + fieldCardinality = "" |
| 52 | + } else { |
| 53 | + fieldCardinality += "_" |
| 54 | + } |
| 55 | + |
| 56 | + fieldType := field.Desc.Kind().String() |
| 57 | + fields = append(fields, fieldName+":"+fieldCardinality+fieldType) |
| 58 | + } |
| 59 | + // In case a message has no fields, like ListEmployeesRequest |
| 60 | + if len(fields) == 0 { |
| 61 | + fields = []string{"None"} |
| 62 | + } |
| 63 | + |
| 64 | + g.P(` `, msg.Desc.FullName(), " (fields: ", strings.Join(fields, ", "), ")") |
| 65 | + if len(msg.Messages) > 0 { |
| 66 | + printMessages(g, msg.Messages) |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments