blob: cfc8c8a85084d5cdf434e29a46816b5b9a547bc5 [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":
56 gengo.GenerateFile(gen, file)
Joe Tsaica46d8c2019-03-20 16:51:09 -070057 generateFieldNumbers(gen, file)
Joe Tsaid56458e2019-03-01 18:11:42 -080058 case "gogrpc":
59 gengogrpc.GenerateFile(gen, file)
60 }
61 }
Joe Tsai19058432019-02-27 21:46:29 -080062 }
63 }
64 return nil
65 })
66 os.Exit(0)
67 }
68}
69
70var (
Joe Tsaid56458e2019-03-01 18:11:42 -080071 run bool
72 protoRoot string
73 repoRoot string
74 modulePath string
Joe Tsai1af1de02019-03-01 16:12:32 -080075
76 generatedPreamble = []string{
77 "// Copyright 2019 The Go Authors. All rights reserved.",
78 "// Use of this source code is governed by a BSD-style.",
79 "// license that can be found in the LICENSE file.",
80 "",
81 "// Code generated by generate-protos. DO NOT EDIT.",
82 "",
83 }
Joe Tsai19058432019-02-27 21:46:29 -080084)
85
86func main() {
87 flag.BoolVar(&run, "execute", false, "Write generated files to destination.")
88 flag.StringVar(&protoRoot, "protoroot", os.Getenv("PROTOBUF_ROOT"), "The root of the protobuf source tree.")
89 flag.Parse()
90 if protoRoot == "" {
91 panic("protobuf source root is not set")
92 }
93
Joe Tsai19058432019-02-27 21:46:29 -080094 generateLocalProtos()
95 generateRemoteProtos()
96}
97
98func generateLocalProtos() {
99 tmpDir, err := ioutil.TempDir(repoRoot, "tmp")
100 check(err)
101 defer os.RemoveAll(tmpDir)
102
103 // Generate all local proto files (except version-locked files).
104 dirs := []struct {
105 path string
Joe Tsaid56458e2019-03-01 18:11:42 -0800106 grpcPlugin bool
Joe Tsai19058432019-02-27 21:46:29 -0800107 annotateFor map[string]bool
Damien Neil5b6d0472019-06-14 11:54:07 -0700108 exclude map[string]bool
Joe Tsai19058432019-02-27 21:46:29 -0800109 }{
Joe Tsaid56458e2019-03-01 18:11:42 -0800110 {path: "cmd/protoc-gen-go/testdata", annotateFor: map[string]bool{"annotations/annotations.proto": true}},
111 {path: "cmd/protoc-gen-go-grpc/testdata", grpcPlugin: true},
Damien Neil5b6d0472019-06-14 11:54:07 -0700112 {path: "internal/testprotos", exclude: map[string]bool{"irregular/irregular.proto": true}},
Joe Tsaid56458e2019-03-01 18:11:42 -0800113 {path: "encoding/testprotos"},
114 {path: "reflect/protoregistry/testprotos"},
Joe Tsai19058432019-02-27 21:46:29 -0800115 }
116 semVerRx := regexp.MustCompile(`v[0-9]+\.[0-9]+\.[0-9]+`)
117 for _, d := range dirs {
Joe Tsaid56458e2019-03-01 18:11:42 -0800118 subDirs := map[string]bool{}
119
Joe Tsai19058432019-02-27 21:46:29 -0800120 dstDir := filepath.Join(tmpDir, filepath.FromSlash(d.path))
121 check(os.MkdirAll(dstDir, 0775))
122
123 srcDir := filepath.Join(repoRoot, filepath.FromSlash(d.path))
124 filepath.Walk(srcDir, func(srcPath string, _ os.FileInfo, _ error) error {
125 if !strings.HasSuffix(srcPath, ".proto") || semVerRx.MatchString(srcPath) {
126 return nil
127 }
128 relPath, err := filepath.Rel(srcDir, srcPath)
129 check(err)
Joe Tsaid56458e2019-03-01 18:11:42 -0800130 subDirs[filepath.Dir(relPath)] = true
Joe Tsai19058432019-02-27 21:46:29 -0800131
Damien Neil5b6d0472019-06-14 11:54:07 -0700132 if d.exclude[filepath.ToSlash(relPath)] {
133 return nil
134 }
135
Joe Tsai19058432019-02-27 21:46:29 -0800136 // Emit a .meta file for certain files.
137 var opts string
138 if d.annotateFor[filepath.ToSlash(relPath)] {
139 opts = ",annotate_code"
140 }
141
Joe Tsaid56458e2019-03-01 18:11:42 -0800142 // Determine which set of plugins to use.
143 plugins := "go"
144 if d.grpcPlugin {
145 plugins += ",gogrpc"
146 }
147
148 protoc(plugins, "-I"+filepath.Join(protoRoot, "src"), "-I"+srcDir, "--go_out=paths=source_relative"+opts+":"+dstDir, relPath)
Joe Tsai19058432019-02-27 21:46:29 -0800149 return nil
150 })
Joe Tsaid56458e2019-03-01 18:11:42 -0800151
152 // For directories in testdata, generate a test that links in all
153 // generated packages to ensure that it builds and initializes properly.
154 // This is done because "go build ./..." does not build sub-packages
155 // under testdata.
156 if filepath.Base(d.path) == "testdata" {
157 var imports []string
158 for sd := range subDirs {
159 imports = append(imports, fmt.Sprintf("_ %q", path.Join(modulePath, d.path, filepath.ToSlash(sd))))
160 }
161 sort.Strings(imports)
162
163 s := strings.Join(append(generatedPreamble, []string{
164 "package main",
165 "",
166 "import (" + strings.Join(imports, "\n") + ")",
167 }...), "\n")
168 b, err := format.Source([]byte(s))
169 check(err)
170 check(ioutil.WriteFile(filepath.Join(tmpDir, filepath.FromSlash(d.path+"/gen_test.go")), b, 0664))
171 }
Joe Tsai19058432019-02-27 21:46:29 -0800172 }
173
174 syncOutput(repoRoot, tmpDir)
175}
176
177func generateRemoteProtos() {
178 tmpDir, err := ioutil.TempDir(repoRoot, "tmp")
179 check(err)
180 defer os.RemoveAll(tmpDir)
181
182 // Generate all remote proto files.
183 files := []struct{ prefix, path string }{
184 {"", "conformance/conformance.proto"},
185 {"src", "google/protobuf/any.proto"},
186 {"src", "google/protobuf/api.proto"},
187 {"src", "google/protobuf/descriptor.proto"},
188 {"src", "google/protobuf/duration.proto"},
189 {"src", "google/protobuf/empty.proto"},
190 {"src", "google/protobuf/field_mask.proto"},
191 {"src", "google/protobuf/source_context.proto"},
192 {"src", "google/protobuf/struct.proto"},
Herbie Ongd64dceb2019-04-25 01:19:57 -0700193 {"src", "google/protobuf/test_messages_proto2.proto"},
194 {"src", "google/protobuf/test_messages_proto3.proto"},
Joe Tsai19058432019-02-27 21:46:29 -0800195 {"src", "google/protobuf/timestamp.proto"},
196 {"src", "google/protobuf/type.proto"},
197 {"src", "google/protobuf/wrappers.proto"},
198 {"src", "google/protobuf/compiler/plugin.proto"},
199 }
200 for _, f := range files {
Joe Tsaid56458e2019-03-01 18:11:42 -0800201 protoc("go", "-I"+filepath.Join(protoRoot, f.prefix), "--go_out="+tmpDir, f.path)
Joe Tsai19058432019-02-27 21:46:29 -0800202 }
203
Joe Tsai19058432019-02-27 21:46:29 -0800204 syncOutput(repoRoot, filepath.Join(tmpDir, modulePath))
205}
206
Joe Tsaid56458e2019-03-01 18:11:42 -0800207func protoc(plugins string, args ...string) {
Joe Tsai19058432019-02-27 21:46:29 -0800208 cmd := exec.Command("protoc", "--plugin=protoc-gen-go="+os.Args[0])
209 cmd.Args = append(cmd.Args, args...)
Joe Tsaid56458e2019-03-01 18:11:42 -0800210 cmd.Env = append(os.Environ(), "RUN_AS_PROTOC_PLUGIN="+plugins)
Joe Tsai19058432019-02-27 21:46:29 -0800211 out, err := cmd.CombinedOutput()
212 if err != nil {
213 fmt.Printf("executing: %v\n%s\n", strings.Join(cmd.Args, " "), out)
214 }
215 check(err)
216}
217
Joe Tsaica46d8c2019-03-20 16:51:09 -0700218// generateFieldNumbers generates an internal package for descriptor.proto
219// and well-known types.
220func generateFieldNumbers(gen *protogen.Plugin, file *protogen.File) {
221 if file.Desc.Package() != "google.protobuf" {
Joe Tsai1af1de02019-03-01 16:12:32 -0800222 return
223 }
224
Joe Tsaica46d8c2019-03-20 16:51:09 -0700225 importPath := modulePath + "/internal/fieldnum"
226 base := strings.TrimSuffix(path.Base(file.Desc.Path()), ".proto")
227 g := gen.NewGeneratedFile(importPath+"/"+base+"_gen.go", protogen.GoImportPath(importPath))
Joe Tsai1af1de02019-03-01 16:12:32 -0800228 for _, s := range generatedPreamble {
229 g.P(s)
230 }
Joe Tsai1af1de02019-03-01 16:12:32 -0800231 g.P("package ", path.Base(importPath))
232 g.P("")
233
234 var processMessages func([]*protogen.Message)
235 processMessages = func(messages []*protogen.Message) {
236 for _, message := range messages {
237 g.P("// Field numbers for ", message.Desc.FullName(), ".")
238 g.P("const (")
239 for _, field := range message.Fields {
240 fd := field.Desc
241 typeName := fd.Kind().String()
242 switch fd.Kind() {
243 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700244 typeName = string(fd.Enum().FullName())
Joe Tsai1af1de02019-03-01 16:12:32 -0800245 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700246 typeName = string(fd.Message().FullName())
Joe Tsai1af1de02019-03-01 16:12:32 -0800247 }
248 g.P(message.GoIdent.GoName, "_", field.GoName, "=", fd.Number(), "// ", fd.Cardinality(), " ", typeName)
249 }
250 g.P(")")
251 processMessages(message.Messages)
252 }
253 }
254 processMessages(file.Messages)
255}
256
Joe Tsai19058432019-02-27 21:46:29 -0800257func syncOutput(dstDir, srcDir string) {
258 filepath.Walk(srcDir, func(srcPath string, _ os.FileInfo, _ error) error {
259 if !strings.HasSuffix(srcPath, ".go") && !strings.HasSuffix(srcPath, ".meta") {
260 return nil
261 }
262 relPath, err := filepath.Rel(srcDir, srcPath)
263 check(err)
264 dstPath := filepath.Join(dstDir, relPath)
265
266 if run {
267 fmt.Println("#", relPath)
268 b, err := ioutil.ReadFile(srcPath)
269 check(err)
270 check(os.MkdirAll(filepath.Dir(dstPath), 0775))
271 check(ioutil.WriteFile(dstPath, b, 0664))
272 } else {
273 cmd := exec.Command("diff", dstPath, srcPath, "-N", "-u")
274 cmd.Stdout = os.Stdout
275 cmd.Run()
276 }
277 return nil
278 })
279}
280
281func check(err error) {
282 if err != nil {
283 panic(err)
284 }
285}