blob: 734aa26fef1a7954fd76ec323eb014c17b5a67a5 [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 Tsaid56458e2019-03-01 18:11:42 -0800114 {path: "encoding/testprotos"},
115 {path: "reflect/protoregistry/testprotos"},
Joe Tsai19058432019-02-27 21:46:29 -0800116 }
117 semVerRx := regexp.MustCompile(`v[0-9]+\.[0-9]+\.[0-9]+`)
118 for _, d := range dirs {
Joe Tsaid56458e2019-03-01 18:11:42 -0800119 subDirs := map[string]bool{}
120
Joe Tsai19058432019-02-27 21:46:29 -0800121 dstDir := filepath.Join(tmpDir, filepath.FromSlash(d.path))
122 check(os.MkdirAll(dstDir, 0775))
123
124 srcDir := filepath.Join(repoRoot, filepath.FromSlash(d.path))
125 filepath.Walk(srcDir, func(srcPath string, _ os.FileInfo, _ error) error {
126 if !strings.HasSuffix(srcPath, ".proto") || semVerRx.MatchString(srcPath) {
127 return nil
128 }
129 relPath, err := filepath.Rel(srcDir, srcPath)
130 check(err)
Joe Tsaid56458e2019-03-01 18:11:42 -0800131 subDirs[filepath.Dir(relPath)] = true
Joe Tsai19058432019-02-27 21:46:29 -0800132
Damien Neil5b6d0472019-06-14 11:54:07 -0700133 if d.exclude[filepath.ToSlash(relPath)] {
134 return nil
135 }
136
Joe Tsai19058432019-02-27 21:46:29 -0800137 // Emit a .meta file for certain files.
138 var opts string
139 if d.annotateFor[filepath.ToSlash(relPath)] {
140 opts = ",annotate_code"
141 }
142
Joe Tsaid56458e2019-03-01 18:11:42 -0800143 // Determine which set of plugins to use.
144 plugins := "go"
145 if d.grpcPlugin {
146 plugins += ",gogrpc"
147 }
148
149 protoc(plugins, "-I"+filepath.Join(protoRoot, "src"), "-I"+srcDir, "--go_out=paths=source_relative"+opts+":"+dstDir, relPath)
Joe Tsai19058432019-02-27 21:46:29 -0800150 return nil
151 })
Joe Tsaid56458e2019-03-01 18:11:42 -0800152
153 // For directories in testdata, generate a test that links in all
154 // generated packages to ensure that it builds and initializes properly.
155 // This is done because "go build ./..." does not build sub-packages
156 // under testdata.
157 if filepath.Base(d.path) == "testdata" {
158 var imports []string
159 for sd := range subDirs {
160 imports = append(imports, fmt.Sprintf("_ %q", path.Join(modulePath, d.path, filepath.ToSlash(sd))))
161 }
162 sort.Strings(imports)
163
164 s := strings.Join(append(generatedPreamble, []string{
165 "package main",
166 "",
167 "import (" + strings.Join(imports, "\n") + ")",
168 }...), "\n")
169 b, err := format.Source([]byte(s))
170 check(err)
171 check(ioutil.WriteFile(filepath.Join(tmpDir, filepath.FromSlash(d.path+"/gen_test.go")), b, 0664))
172 }
Joe Tsai19058432019-02-27 21:46:29 -0800173 }
174
175 syncOutput(repoRoot, tmpDir)
176}
177
178func generateRemoteProtos() {
179 tmpDir, err := ioutil.TempDir(repoRoot, "tmp")
180 check(err)
181 defer os.RemoveAll(tmpDir)
182
183 // Generate all remote proto files.
184 files := []struct{ prefix, path string }{
185 {"", "conformance/conformance.proto"},
Damien Neila80229e2019-06-20 12:53:48 -0700186 {"benchmarks", "benchmarks.proto"},
187 {"benchmarks", "datasets/google_message1/proto2/benchmark_message1_proto2.proto"},
188 {"benchmarks", "datasets/google_message1/proto3/benchmark_message1_proto3.proto"},
189 {"benchmarks", "datasets/google_message2/benchmark_message2.proto"},
190 {"benchmarks", "datasets/google_message3/benchmark_message3.proto"},
191 {"benchmarks", "datasets/google_message3/benchmark_message3_1.proto"},
192 {"benchmarks", "datasets/google_message3/benchmark_message3_2.proto"},
193 {"benchmarks", "datasets/google_message3/benchmark_message3_3.proto"},
194 {"benchmarks", "datasets/google_message3/benchmark_message3_4.proto"},
195 {"benchmarks", "datasets/google_message3/benchmark_message3_5.proto"},
196 {"benchmarks", "datasets/google_message3/benchmark_message3_6.proto"},
197 {"benchmarks", "datasets/google_message3/benchmark_message3_7.proto"},
198 {"benchmarks", "datasets/google_message3/benchmark_message3_8.proto"},
199 {"benchmarks", "datasets/google_message4/benchmark_message4.proto"},
200 {"benchmarks", "datasets/google_message4/benchmark_message4_1.proto"},
201 {"benchmarks", "datasets/google_message4/benchmark_message4_2.proto"},
202 {"benchmarks", "datasets/google_message4/benchmark_message4_3.proto"},
Joe Tsai19058432019-02-27 21:46:29 -0800203 {"src", "google/protobuf/any.proto"},
204 {"src", "google/protobuf/api.proto"},
Damien Neila80229e2019-06-20 12:53:48 -0700205 {"src", "google/protobuf/compiler/plugin.proto"},
Joe Tsai19058432019-02-27 21:46:29 -0800206 {"src", "google/protobuf/descriptor.proto"},
207 {"src", "google/protobuf/duration.proto"},
208 {"src", "google/protobuf/empty.proto"},
209 {"src", "google/protobuf/field_mask.proto"},
210 {"src", "google/protobuf/source_context.proto"},
211 {"src", "google/protobuf/struct.proto"},
Herbie Ongd64dceb2019-04-25 01:19:57 -0700212 {"src", "google/protobuf/test_messages_proto2.proto"},
213 {"src", "google/protobuf/test_messages_proto3.proto"},
Joe Tsai19058432019-02-27 21:46:29 -0800214 {"src", "google/protobuf/timestamp.proto"},
215 {"src", "google/protobuf/type.proto"},
216 {"src", "google/protobuf/wrappers.proto"},
Joe Tsai19058432019-02-27 21:46:29 -0800217 }
218 for _, f := range files {
Joe Tsaid56458e2019-03-01 18:11:42 -0800219 protoc("go", "-I"+filepath.Join(protoRoot, f.prefix), "--go_out="+tmpDir, f.path)
Joe Tsai19058432019-02-27 21:46:29 -0800220 }
221
Joe Tsai19058432019-02-27 21:46:29 -0800222 syncOutput(repoRoot, filepath.Join(tmpDir, modulePath))
223}
224
Joe Tsaid56458e2019-03-01 18:11:42 -0800225func protoc(plugins string, args ...string) {
Joe Tsai19058432019-02-27 21:46:29 -0800226 cmd := exec.Command("protoc", "--plugin=protoc-gen-go="+os.Args[0])
227 cmd.Args = append(cmd.Args, args...)
Joe Tsaid56458e2019-03-01 18:11:42 -0800228 cmd.Env = append(os.Environ(), "RUN_AS_PROTOC_PLUGIN="+plugins)
Joe Tsai19058432019-02-27 21:46:29 -0800229 out, err := cmd.CombinedOutput()
230 if err != nil {
231 fmt.Printf("executing: %v\n%s\n", strings.Join(cmd.Args, " "), out)
232 }
233 check(err)
234}
235
Joe Tsaica46d8c2019-03-20 16:51:09 -0700236// generateFieldNumbers generates an internal package for descriptor.proto
237// and well-known types.
238func generateFieldNumbers(gen *protogen.Plugin, file *protogen.File) {
239 if file.Desc.Package() != "google.protobuf" {
Joe Tsai1af1de02019-03-01 16:12:32 -0800240 return
241 }
242
Joe Tsaica46d8c2019-03-20 16:51:09 -0700243 importPath := modulePath + "/internal/fieldnum"
244 base := strings.TrimSuffix(path.Base(file.Desc.Path()), ".proto")
245 g := gen.NewGeneratedFile(importPath+"/"+base+"_gen.go", protogen.GoImportPath(importPath))
Joe Tsai1af1de02019-03-01 16:12:32 -0800246 for _, s := range generatedPreamble {
247 g.P(s)
248 }
Joe Tsai1af1de02019-03-01 16:12:32 -0800249 g.P("package ", path.Base(importPath))
250 g.P("")
251
252 var processMessages func([]*protogen.Message)
253 processMessages = func(messages []*protogen.Message) {
254 for _, message := range messages {
255 g.P("// Field numbers for ", message.Desc.FullName(), ".")
256 g.P("const (")
257 for _, field := range message.Fields {
258 fd := field.Desc
259 typeName := fd.Kind().String()
260 switch fd.Kind() {
261 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700262 typeName = string(fd.Enum().FullName())
Joe Tsai1af1de02019-03-01 16:12:32 -0800263 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700264 typeName = string(fd.Message().FullName())
Joe Tsai1af1de02019-03-01 16:12:32 -0800265 }
266 g.P(message.GoIdent.GoName, "_", field.GoName, "=", fd.Number(), "// ", fd.Cardinality(), " ", typeName)
267 }
268 g.P(")")
269 processMessages(message.Messages)
270 }
271 }
272 processMessages(file.Messages)
273}
274
Joe Tsai19058432019-02-27 21:46:29 -0800275func syncOutput(dstDir, srcDir string) {
276 filepath.Walk(srcDir, func(srcPath string, _ os.FileInfo, _ error) error {
277 if !strings.HasSuffix(srcPath, ".go") && !strings.HasSuffix(srcPath, ".meta") {
278 return nil
279 }
280 relPath, err := filepath.Rel(srcDir, srcPath)
281 check(err)
282 dstPath := filepath.Join(dstDir, relPath)
283
284 if run {
285 fmt.Println("#", relPath)
286 b, err := ioutil.ReadFile(srcPath)
287 check(err)
288 check(os.MkdirAll(filepath.Dir(dstPath), 0775))
289 check(ioutil.WriteFile(dstPath, b, 0664))
290 } else {
291 cmd := exec.Command("diff", dstPath, srcPath, "-N", "-u")
292 cmd.Stdout = os.Stdout
293 cmd.Run()
294 }
295 return nil
296 })
297}
298
299func check(err error) {
300 if err != nil {
301 panic(err)
302 }
303}