blob: e467c087d382f255b4edb43bd244482286bbd6b4 [file] [log] [blame]
Joe Tsai19058432019-02-27 21:46:29 -08001// Copyright 2019 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5//go:generate go run . -execute
6
7package main
8
9import (
10 "flag"
11 "fmt"
Joe Tsaid56458e2019-03-01 18:11:42 -080012 "go/format"
Joe Tsai19058432019-02-27 21:46:29 -080013 "io/ioutil"
14 "os"
15 "os/exec"
Joe Tsai1af1de02019-03-01 16:12:32 -080016 "path"
Joe Tsai19058432019-02-27 21:46:29 -080017 "path/filepath"
18 "regexp"
Joe Tsaid56458e2019-03-01 18:11:42 -080019 "sort"
Joe Tsai19058432019-02-27 21:46:29 -080020 "strings"
21
Damien Neile89e6242019-05-13 23:55:40 -070022 gengogrpc "google.golang.org/protobuf/cmd/protoc-gen-go-grpc/internal_gengogrpc"
23 gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo"
Damien Neil5c5b5312019-05-14 12:44:37 -070024 "google.golang.org/protobuf/compiler/protogen"
Damien Neile89e6242019-05-13 23:55:40 -070025 "google.golang.org/protobuf/internal/detrand"
Damien Neile89e6242019-05-13 23:55:40 -070026 "google.golang.org/protobuf/reflect/protoreflect"
Joe Tsai19058432019-02-27 21:46:29 -080027)
28
29func init() {
Joe Tsaica46d8c2019-03-20 16:51:09 -070030 // Determine repository root path.
31 out, err := exec.Command("git", "rev-parse", "--show-toplevel").CombinedOutput()
32 check(err)
33 repoRoot = strings.TrimSpace(string(out))
34
35 // Determine the module path.
36 cmd := exec.Command("go", "list", "-m", "-f", "{{.Path}}")
37 cmd.Dir = repoRoot
38 out, err = cmd.CombinedOutput()
39 check(err)
40 modulePath = strings.TrimSpace(string(out))
41
Joe Tsai19058432019-02-27 21:46:29 -080042 // When the environment variable RUN_AS_PROTOC_PLUGIN is set,
43 // we skip running main and instead act as a protoc plugin.
44 // This allows the binary to pass itself to protoc.
Joe Tsaid56458e2019-03-01 18:11:42 -080045 if plugins := os.Getenv("RUN_AS_PROTOC_PLUGIN"); plugins != "" {
Joe Tsaice07f392019-03-18 16:25:54 -070046 // Disable deliberate output instability for generated files.
47 // This is reasonable since we fully control the output.
48 detrand.Disable()
49
Joe Tsai19058432019-02-27 21:46:29 -080050 protogen.Run(nil, func(gen *protogen.Plugin) error {
Joe Tsaid56458e2019-03-01 18:11:42 -080051 for _, plugin := range strings.Split(plugins, ",") {
52 for _, file := range gen.Files {
53 if file.Generate {
54 switch plugin {
55 case "go":
Joe Tsaibab3d402019-07-10 00:15:35 -070056 gengo.GenerateVersionMarkers = false
Joe Tsaid56458e2019-03-01 18:11:42 -080057 gengo.GenerateFile(gen, file)
Joe Tsaica46d8c2019-03-20 16:51:09 -070058 generateFieldNumbers(gen, file)
Joe Tsaid56458e2019-03-01 18:11:42 -080059 case "gogrpc":
60 gengogrpc.GenerateFile(gen, file)
61 }
62 }
Joe Tsai19058432019-02-27 21:46:29 -080063 }
64 }
65 return nil
66 })
67 os.Exit(0)
68 }
69}
70
71var (
Joe Tsaid56458e2019-03-01 18:11:42 -080072 run bool
73 protoRoot string
74 repoRoot string
75 modulePath string
Joe Tsai1af1de02019-03-01 16:12:32 -080076
77 generatedPreamble = []string{
78 "// Copyright 2019 The Go Authors. All rights reserved.",
79 "// Use of this source code is governed by a BSD-style.",
80 "// license that can be found in the LICENSE file.",
81 "",
82 "// Code generated by generate-protos. DO NOT EDIT.",
83 "",
84 }
Joe Tsai19058432019-02-27 21:46:29 -080085)
86
87func main() {
88 flag.BoolVar(&run, "execute", false, "Write generated files to destination.")
89 flag.StringVar(&protoRoot, "protoroot", os.Getenv("PROTOBUF_ROOT"), "The root of the protobuf source tree.")
90 flag.Parse()
91 if protoRoot == "" {
92 panic("protobuf source root is not set")
93 }
94
Joe Tsai19058432019-02-27 21:46:29 -080095 generateLocalProtos()
96 generateRemoteProtos()
97}
98
99func generateLocalProtos() {
100 tmpDir, err := ioutil.TempDir(repoRoot, "tmp")
101 check(err)
102 defer os.RemoveAll(tmpDir)
103
104 // Generate all local proto files (except version-locked files).
105 dirs := []struct {
106 path string
Joe Tsaid56458e2019-03-01 18:11:42 -0800107 grpcPlugin bool
Joe Tsai19058432019-02-27 21:46:29 -0800108 annotateFor map[string]bool
Damien Neil5b6d0472019-06-14 11:54:07 -0700109 exclude map[string]bool
Joe Tsai19058432019-02-27 21:46:29 -0800110 }{
Joe Tsaid56458e2019-03-01 18:11:42 -0800111 {path: "cmd/protoc-gen-go/testdata", annotateFor: map[string]bool{"annotations/annotations.proto": true}},
112 {path: "cmd/protoc-gen-go-grpc/testdata", grpcPlugin: true},
Damien Neil5b6d0472019-06-14 11:54:07 -0700113 {path: "internal/testprotos", exclude: map[string]bool{"irregular/irregular.proto": true}},
Joe Tsai19058432019-02-27 21:46:29 -0800114 }
Joe Tsai55f18252020-01-11 00:25:01 -0800115 excludeRx := regexp.MustCompile(`legacy/proto[23]_[0-9]{8}_[0-9a-f]{8}/`)
Joe Tsai19058432019-02-27 21:46:29 -0800116 for _, d := range dirs {
Joe Tsaid56458e2019-03-01 18:11:42 -0800117 subDirs := map[string]bool{}
118
Joe Tsai19058432019-02-27 21:46:29 -0800119 dstDir := filepath.Join(tmpDir, filepath.FromSlash(d.path))
120 check(os.MkdirAll(dstDir, 0775))
121
122 srcDir := filepath.Join(repoRoot, filepath.FromSlash(d.path))
123 filepath.Walk(srcDir, func(srcPath string, _ os.FileInfo, _ error) error {
Joe Tsai55f18252020-01-11 00:25:01 -0800124 if !strings.HasSuffix(srcPath, ".proto") || excludeRx.MatchString(srcPath) {
Joe Tsai19058432019-02-27 21:46:29 -0800125 return nil
126 }
127 relPath, err := filepath.Rel(srcDir, srcPath)
128 check(err)
Joe Tsaid56458e2019-03-01 18:11:42 -0800129 subDirs[filepath.Dir(relPath)] = true
Joe Tsai19058432019-02-27 21:46:29 -0800130
Damien Neil5b6d0472019-06-14 11:54:07 -0700131 if d.exclude[filepath.ToSlash(relPath)] {
132 return nil
133 }
134
Joe Tsai19058432019-02-27 21:46:29 -0800135 // Emit a .meta file for certain files.
136 var opts string
137 if d.annotateFor[filepath.ToSlash(relPath)] {
138 opts = ",annotate_code"
139 }
140
Joe Tsaid56458e2019-03-01 18:11:42 -0800141 // Determine which set of plugins to use.
142 plugins := "go"
143 if d.grpcPlugin {
144 plugins += ",gogrpc"
145 }
146
147 protoc(plugins, "-I"+filepath.Join(protoRoot, "src"), "-I"+srcDir, "--go_out=paths=source_relative"+opts+":"+dstDir, relPath)
Joe Tsai19058432019-02-27 21:46:29 -0800148 return nil
149 })
Joe Tsaid56458e2019-03-01 18:11:42 -0800150
151 // For directories in testdata, generate a test that links in all
152 // generated packages to ensure that it builds and initializes properly.
153 // This is done because "go build ./..." does not build sub-packages
154 // under testdata.
155 if filepath.Base(d.path) == "testdata" {
156 var imports []string
157 for sd := range subDirs {
158 imports = append(imports, fmt.Sprintf("_ %q", path.Join(modulePath, d.path, filepath.ToSlash(sd))))
159 }
160 sort.Strings(imports)
161
162 s := strings.Join(append(generatedPreamble, []string{
163 "package main",
164 "",
165 "import (" + strings.Join(imports, "\n") + ")",
166 }...), "\n")
167 b, err := format.Source([]byte(s))
168 check(err)
169 check(ioutil.WriteFile(filepath.Join(tmpDir, filepath.FromSlash(d.path+"/gen_test.go")), b, 0664))
170 }
Joe Tsai19058432019-02-27 21:46:29 -0800171 }
172
173 syncOutput(repoRoot, tmpDir)
174}
175
176func generateRemoteProtos() {
177 tmpDir, err := ioutil.TempDir(repoRoot, "tmp")
178 check(err)
179 defer os.RemoveAll(tmpDir)
180
181 // Generate all remote proto files.
182 files := []struct{ prefix, path string }{
183 {"", "conformance/conformance.proto"},
Damien Neila80229e2019-06-20 12:53:48 -0700184 {"benchmarks", "benchmarks.proto"},
185 {"benchmarks", "datasets/google_message1/proto2/benchmark_message1_proto2.proto"},
186 {"benchmarks", "datasets/google_message1/proto3/benchmark_message1_proto3.proto"},
187 {"benchmarks", "datasets/google_message2/benchmark_message2.proto"},
188 {"benchmarks", "datasets/google_message3/benchmark_message3.proto"},
189 {"benchmarks", "datasets/google_message3/benchmark_message3_1.proto"},
190 {"benchmarks", "datasets/google_message3/benchmark_message3_2.proto"},
191 {"benchmarks", "datasets/google_message3/benchmark_message3_3.proto"},
192 {"benchmarks", "datasets/google_message3/benchmark_message3_4.proto"},
193 {"benchmarks", "datasets/google_message3/benchmark_message3_5.proto"},
194 {"benchmarks", "datasets/google_message3/benchmark_message3_6.proto"},
195 {"benchmarks", "datasets/google_message3/benchmark_message3_7.proto"},
196 {"benchmarks", "datasets/google_message3/benchmark_message3_8.proto"},
197 {"benchmarks", "datasets/google_message4/benchmark_message4.proto"},
198 {"benchmarks", "datasets/google_message4/benchmark_message4_1.proto"},
199 {"benchmarks", "datasets/google_message4/benchmark_message4_2.proto"},
200 {"benchmarks", "datasets/google_message4/benchmark_message4_3.proto"},
Joe Tsai19058432019-02-27 21:46:29 -0800201 {"src", "google/protobuf/any.proto"},
202 {"src", "google/protobuf/api.proto"},
Damien Neila80229e2019-06-20 12:53:48 -0700203 {"src", "google/protobuf/compiler/plugin.proto"},
Joe Tsai19058432019-02-27 21:46:29 -0800204 {"src", "google/protobuf/descriptor.proto"},
205 {"src", "google/protobuf/duration.proto"},
206 {"src", "google/protobuf/empty.proto"},
207 {"src", "google/protobuf/field_mask.proto"},
208 {"src", "google/protobuf/source_context.proto"},
209 {"src", "google/protobuf/struct.proto"},
Herbie Ongd64dceb2019-04-25 01:19:57 -0700210 {"src", "google/protobuf/test_messages_proto2.proto"},
211 {"src", "google/protobuf/test_messages_proto3.proto"},
Joe Tsai19058432019-02-27 21:46:29 -0800212 {"src", "google/protobuf/timestamp.proto"},
213 {"src", "google/protobuf/type.proto"},
214 {"src", "google/protobuf/wrappers.proto"},
Joe Tsai19058432019-02-27 21:46:29 -0800215 }
216 for _, f := range files {
Joe Tsaid56458e2019-03-01 18:11:42 -0800217 protoc("go", "-I"+filepath.Join(protoRoot, f.prefix), "--go_out="+tmpDir, f.path)
Joe Tsai19058432019-02-27 21:46:29 -0800218 }
219
Joe Tsai19058432019-02-27 21:46:29 -0800220 syncOutput(repoRoot, filepath.Join(tmpDir, modulePath))
221}
222
Joe Tsaid56458e2019-03-01 18:11:42 -0800223func protoc(plugins string, args ...string) {
Joe Tsai19058432019-02-27 21:46:29 -0800224 cmd := exec.Command("protoc", "--plugin=protoc-gen-go="+os.Args[0])
225 cmd.Args = append(cmd.Args, args...)
Joe Tsaid56458e2019-03-01 18:11:42 -0800226 cmd.Env = append(os.Environ(), "RUN_AS_PROTOC_PLUGIN="+plugins)
Joe Tsai19058432019-02-27 21:46:29 -0800227 out, err := cmd.CombinedOutput()
228 if err != nil {
229 fmt.Printf("executing: %v\n%s\n", strings.Join(cmd.Args, " "), out)
230 }
231 check(err)
232}
233
Joe Tsaica46d8c2019-03-20 16:51:09 -0700234// generateFieldNumbers generates an internal package for descriptor.proto
235// and well-known types.
236func generateFieldNumbers(gen *protogen.Plugin, file *protogen.File) {
237 if file.Desc.Package() != "google.protobuf" {
Joe Tsai1af1de02019-03-01 16:12:32 -0800238 return
239 }
240
Joe Tsaica46d8c2019-03-20 16:51:09 -0700241 importPath := modulePath + "/internal/fieldnum"
242 base := strings.TrimSuffix(path.Base(file.Desc.Path()), ".proto")
243 g := gen.NewGeneratedFile(importPath+"/"+base+"_gen.go", protogen.GoImportPath(importPath))
Joe Tsai1af1de02019-03-01 16:12:32 -0800244 for _, s := range generatedPreamble {
245 g.P(s)
246 }
Joe Tsai1af1de02019-03-01 16:12:32 -0800247 g.P("package ", path.Base(importPath))
248 g.P("")
249
250 var processMessages func([]*protogen.Message)
251 processMessages = func(messages []*protogen.Message) {
252 for _, message := range messages {
253 g.P("// Field numbers for ", message.Desc.FullName(), ".")
254 g.P("const (")
255 for _, field := range message.Fields {
256 fd := field.Desc
257 typeName := fd.Kind().String()
258 switch fd.Kind() {
259 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700260 typeName = string(fd.Enum().FullName())
Joe Tsai1af1de02019-03-01 16:12:32 -0800261 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700262 typeName = string(fd.Message().FullName())
Joe Tsai1af1de02019-03-01 16:12:32 -0800263 }
264 g.P(message.GoIdent.GoName, "_", field.GoName, "=", fd.Number(), "// ", fd.Cardinality(), " ", typeName)
265 }
266 g.P(")")
267 processMessages(message.Messages)
268 }
269 }
270 processMessages(file.Messages)
271}
272
Joe Tsai19058432019-02-27 21:46:29 -0800273func syncOutput(dstDir, srcDir string) {
274 filepath.Walk(srcDir, func(srcPath string, _ os.FileInfo, _ error) error {
275 if !strings.HasSuffix(srcPath, ".go") && !strings.HasSuffix(srcPath, ".meta") {
276 return nil
277 }
278 relPath, err := filepath.Rel(srcDir, srcPath)
279 check(err)
280 dstPath := filepath.Join(dstDir, relPath)
281
282 if run {
283 fmt.Println("#", relPath)
284 b, err := ioutil.ReadFile(srcPath)
285 check(err)
286 check(os.MkdirAll(filepath.Dir(dstPath), 0775))
287 check(ioutil.WriteFile(dstPath, b, 0664))
288 } else {
289 cmd := exec.Command("diff", dstPath, srcPath, "-N", "-u")
290 cmd.Stdout = os.Stdout
291 cmd.Run()
292 }
293 return nil
294 })
295}
296
297func check(err error) {
298 if err != nil {
299 panic(err)
300 }
301}