blob: dfcfd10761f8e9169fa7b61146e2eef66dd03d96 [file] [log] [blame]
Joe Tsai707894e2019-03-01 12:50:52 -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
Joe Tsaif3987842019-03-02 13:35:17 -08005// +build ignore
Joe Tsai707894e2019-03-01 12:50:52 -08006
Joe Tsaif3987842019-03-02 13:35:17 -08007package main
Joe Tsai707894e2019-03-01 12:50:52 -08008
9import (
10 "archive/tar"
Damien Neil50a85912021-05-20 11:37:23 -070011 "archive/zip"
Joe Tsai707894e2019-03-01 12:50:52 -080012 "bytes"
13 "compress/gzip"
Joe Tsai8de66752019-12-19 16:38:52 -080014 "crypto/sha256"
Joe Tsai707894e2019-03-01 12:50:52 -080015 "flag"
16 "fmt"
17 "io"
18 "io/ioutil"
19 "net/http"
20 "os"
21 "os/exec"
22 "path/filepath"
Damien Neil3a185602020-02-21 09:16:19 -080023 "regexp"
Joe Tsai707894e2019-03-01 12:50:52 -080024 "runtime"
25 "strings"
Joe Tsai62200db2019-07-11 17:34:10 -070026 "sync"
Joe Tsai707894e2019-03-01 12:50:52 -080027 "testing"
Joe Tsaif3987842019-03-02 13:35:17 -080028 "time"
Joe Tsai4f3de442019-08-07 19:33:51 -070029
Joe Tsai4ab2bc92020-03-10 17:38:07 -070030 "google.golang.org/protobuf/internal/version"
Joe Tsai707894e2019-03-01 12:50:52 -080031)
32
33var (
Joe Tsai4f3de442019-08-07 19:33:51 -070034 regenerate = flag.Bool("regenerate", false, "regenerate files")
35 buildRelease = flag.Bool("buildRelease", false, "build release binaries")
Joe Tsai707894e2019-03-01 12:50:52 -080036
Joe Tsai85f47622020-05-26 16:26:02 -070037 protobufVersion = "3.15.3"
38 protobufSHA256 = "" // ignored if protobufVersion is a git hash
Joe Tsai8de66752019-12-19 16:38:52 -080039
Joe Tsai731520d2021-02-25 17:12:53 -080040 golangVersions = []string{"1.9.7", "1.10.8", "1.11.13", "1.12.17", "1.13.15", "1.14.15", "1.15.9", "1.16.1"}
Joe Tsai8de66752019-12-19 16:38:52 -080041 golangLatest = golangVersions[len(golangVersions)-1]
42
43 staticcheckVersion = "2020.1.4"
44 staticcheckSHA256s = map[string]string{
Joe Tsai8de66752019-12-19 16:38:52 -080045 "darwin/amd64": "5706d101426c025e8f165309e0cb2932e54809eb035ff23ebe19df0f810699d8",
46 "linux/386": "e4dbf94e940678ae7108f0d22c7c2992339bc10a8fb384e7e734b1531a429a1c",
47 "linux/amd64": "09d2c2002236296de2c757df111fe3ae858b89f9e183f645ad01f8135c83c519",
48 }
Joe Tsai707894e2019-03-01 12:50:52 -080049
Joe Tsai9e88bc02019-03-12 01:30:40 -070050 // purgeTimeout determines the maximum age of unused sub-directories.
51 purgeTimeout = 30 * 24 * time.Hour // 1 month
Joe Tsai707894e2019-03-01 12:50:52 -080052
53 // Variables initialized by mustInitDeps.
Herbie Ongd64dceb2019-04-25 01:19:57 -070054 goPath string
55 modulePath string
56 protobufPath string
Joe Tsai707894e2019-03-01 12:50:52 -080057)
58
59func Test(t *testing.T) {
60 mustInitDeps(t)
Joe Tsai4f3de442019-08-07 19:33:51 -070061 mustHandleFlags(t)
Joe Tsai707894e2019-03-01 12:50:52 -080062
Damien Neil4d8936d2020-02-21 10:32:56 -080063 // Report dirt in the working tree quickly, rather than after
64 // going through all the presubmits.
65 //
66 // Fail the test late, so we can test uncommitted changes with -failfast.
Joe Tsaif75a3382019-12-19 17:42:41 -080067 gitDiff := mustRunCommand(t, "git", "diff", "HEAD")
68 if strings.TrimSpace(gitDiff) != "" {
69 fmt.Printf("WARNING: working tree contains uncommitted changes:\n%v\n", gitDiff)
Damien Neil4d8936d2020-02-21 10:32:56 -080070 }
Joe Tsaif75a3382019-12-19 17:42:41 -080071 gitUntracked := mustRunCommand(t, "git", "ls-files", "--others", "--exclude-standard")
72 if strings.TrimSpace(gitUntracked) != "" {
73 fmt.Printf("WARNING: working tree contains untracked files:\n%v\n", gitUntracked)
Damien Neil4d8936d2020-02-21 10:32:56 -080074 }
75
76 // Do the relatively fast checks up-front.
77 t.Run("GeneratedGoFiles", func(t *testing.T) {
78 diff := mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-types")
79 if strings.TrimSpace(diff) != "" {
80 t.Fatalf("stale generated files:\n%v", diff)
81 }
82 diff = mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-protos")
83 if strings.TrimSpace(diff) != "" {
84 t.Fatalf("stale generated files:\n%v", diff)
85 }
86 })
87 t.Run("FormattedGoFiles", func(t *testing.T) {
88 files := strings.Split(strings.TrimSpace(mustRunCommand(t, "git", "ls-files", "*.go")), "\n")
89 diff := mustRunCommand(t, append([]string{"gofmt", "-d"}, files...)...)
90 if strings.TrimSpace(diff) != "" {
91 t.Fatalf("unformatted source files:\n%v", diff)
92 }
93 })
94 t.Run("CopyrightHeaders", func(t *testing.T) {
95 files := strings.Split(strings.TrimSpace(mustRunCommand(t, "git", "ls-files", "*.go", "*.proto")), "\n")
96 mustHaveCopyrightHeader(t, files)
97 })
98
Joe Tsai62200db2019-07-11 17:34:10 -070099 var wg sync.WaitGroup
100 sema := make(chan bool, (runtime.NumCPU()+1)/2)
101 for i := range golangVersions {
102 goVersion := golangVersions[i]
103 goLabel := "Go" + goVersion
Joe Tsai467a9cd2020-07-08 10:26:03 -0700104 runGo := func(label string, cmd command, args ...string) {
Joe Tsai62200db2019-07-11 17:34:10 -0700105 wg.Add(1)
106 sema <- true
107 go func() {
108 defer wg.Done()
109 defer func() { <-sema }()
110 t.Run(goLabel+"/"+label, func(t *testing.T) {
111 args[0] += goVersion
Joe Tsai467a9cd2020-07-08 10:26:03 -0700112 cmd.mustRun(t, args...)
Joe Tsai707894e2019-03-01 12:50:52 -0800113 })
Joe Tsai62200db2019-07-11 17:34:10 -0700114 }()
115 }
116
117 workDir := filepath.Join(goPath, "src", modulePath)
Joe Tsai467a9cd2020-07-08 10:26:03 -0700118 runGo("Normal", command{Dir: workDir}, "go", "test", "-race", "./...")
119 runGo("PureGo", command{Dir: workDir}, "go", "test", "-race", "-tags", "purego", "./...")
120 runGo("Reflect", command{Dir: workDir}, "go", "test", "-race", "-tags", "protoreflect", "./...")
Joe Tsai62200db2019-07-11 17:34:10 -0700121 if goVersion == golangLatest {
Joe Tsai467a9cd2020-07-08 10:26:03 -0700122 runGo("ProtoLegacy", command{Dir: workDir}, "go", "test", "-race", "-tags", "protolegacy", "./...")
123 runGo("ProtocGenGo", command{Dir: "cmd/protoc-gen-go/testdata"}, "go", "test")
124 runGo("Conformance", command{Dir: "internal/conformance"}, "go", "test", "-execute")
125
126 // Only run the 32-bit compatability tests for Linux;
127 // avoid Darwin since 10.15 dropped support i386 code execution.
128 if runtime.GOOS == "linux" {
129 runGo("Arch32Bit", command{Dir: workDir, Env: append(os.Environ(), "GOARCH=386")}, "go", "test", "./...")
130 }
Joe Tsai62200db2019-07-11 17:34:10 -0700131 }
Joe Tsai707894e2019-03-01 12:50:52 -0800132 }
Joe Tsai62200db2019-07-11 17:34:10 -0700133 wg.Wait()
Joe Tsai707894e2019-03-01 12:50:52 -0800134
Joe Tsai8de66752019-12-19 16:38:52 -0800135 t.Run("GoStaticCheck", func(t *testing.T) {
136 checks := []string{
137 "all", // start with all checks enabled
138 "-SA1019", // disable deprecated usage check
139 "-S*", // disable code simplication checks
140 "-ST*", // disable coding style checks
141 "-U*", // disable unused declaration checks
142 }
143 out := mustRunCommand(t, "staticcheck", "-checks="+strings.Join(checks, ","), "-fail=none", "./...")
144
145 // Filter out findings from certain paths.
146 var findings []string
147 for _, finding := range strings.Split(strings.TrimSpace(out), "\n") {
148 switch {
149 case strings.HasPrefix(finding, "internal/testprotos/legacy/"):
150 default:
151 findings = append(findings, finding)
152 }
153 }
154 if len(findings) > 0 {
155 t.Fatalf("staticcheck findings:\n%v", strings.Join(findings, "\n"))
156 }
157 })
Joe Tsai707894e2019-03-01 12:50:52 -0800158 t.Run("CommittedGitChanges", func(t *testing.T) {
Joe Tsaif75a3382019-12-19 17:42:41 -0800159 if strings.TrimSpace(gitDiff) != "" {
Damien Neil4d8936d2020-02-21 10:32:56 -0800160 t.Fatalf("uncommitted changes")
Joe Tsai707894e2019-03-01 12:50:52 -0800161 }
162 })
163 t.Run("TrackedGitFiles", func(t *testing.T) {
Joe Tsaif75a3382019-12-19 17:42:41 -0800164 if strings.TrimSpace(gitUntracked) != "" {
Damien Neil4d8936d2020-02-21 10:32:56 -0800165 t.Fatalf("untracked files")
Joe Tsai707894e2019-03-01 12:50:52 -0800166 }
167 })
168}
169
170func mustInitDeps(t *testing.T) {
171 check := func(err error) {
172 t.Helper()
173 if err != nil {
174 t.Fatal(err)
175 }
176 }
177
178 // Determine the directory to place the test directory.
179 repoRoot, err := os.Getwd()
180 check(err)
181 testDir := filepath.Join(repoRoot, ".cache")
182 check(os.MkdirAll(testDir, 0775))
183
184 // Delete the current directory if non-empty,
185 // which only occurs if a dependency failed to initialize properly.
186 var workingDir string
Joe Tsaidb5c9002020-09-05 11:24:42 -0700187 finishedDirs := map[string]bool{}
Joe Tsai707894e2019-03-01 12:50:52 -0800188 defer func() {
189 if workingDir != "" {
190 os.RemoveAll(workingDir) // best-effort
191 }
192 }()
Joe Tsaidb5c9002020-09-05 11:24:42 -0700193 startWork := func(name string) string {
194 workingDir = filepath.Join(testDir, name)
195 return workingDir
196 }
197 finishWork := func() {
198 finishedDirs[workingDir] = true
199 workingDir = ""
200 }
Joe Tsai707894e2019-03-01 12:50:52 -0800201
202 // Delete other sub-directories that are no longer relevant.
203 defer func() {
Joe Tsai9e88bc02019-03-12 01:30:40 -0700204 now := time.Now()
Joe Tsai707894e2019-03-01 12:50:52 -0800205 fis, _ := ioutil.ReadDir(testDir)
206 for _, fi := range fis {
Joe Tsaidb5c9002020-09-05 11:24:42 -0700207 dir := filepath.Join(testDir, fi.Name())
208 if finishedDirs[dir] {
209 os.Chtimes(dir, now, now) // best-effort
Joe Tsai9e88bc02019-03-12 01:30:40 -0700210 continue
Joe Tsai707894e2019-03-01 12:50:52 -0800211 }
Joe Tsai9e88bc02019-03-12 01:30:40 -0700212 if now.Sub(fi.ModTime()) < purgeTimeout {
213 continue
214 }
215 fmt.Printf("delete %v\n", fi.Name())
Joe Tsaidb5c9002020-09-05 11:24:42 -0700216 os.RemoveAll(dir) // best-effort
Joe Tsai707894e2019-03-01 12:50:52 -0800217 }
218 }()
219
220 // The bin directory contains symlinks to each tool by version.
221 // It is safe to delete this directory and run the test script from scratch.
Joe Tsaidb5c9002020-09-05 11:24:42 -0700222 binPath := startWork("bin")
Joe Tsai707894e2019-03-01 12:50:52 -0800223 check(os.RemoveAll(binPath))
224 check(os.Mkdir(binPath, 0775))
225 check(os.Setenv("PATH", binPath+":"+os.Getenv("PATH")))
226 registerBinary := func(name, path string) {
227 check(os.Symlink(path, filepath.Join(binPath, name)))
228 }
Joe Tsaidb5c9002020-09-05 11:24:42 -0700229 finishWork()
Joe Tsai707894e2019-03-01 12:50:52 -0800230
231 // Download and build the protobuf toolchain.
232 // We avoid downloading the pre-compiled binaries since they do not contain
233 // the conformance test runner.
Joe Tsaidb5c9002020-09-05 11:24:42 -0700234 protobufPath = startWork("protobuf-" + protobufVersion)
Herbie Ongd64dceb2019-04-25 01:19:57 -0700235 if _, err := os.Stat(protobufPath); err != nil {
236 fmt.Printf("download %v\n", filepath.Base(protobufPath))
Joe Tsai387873d2020-04-28 14:44:38 -0700237 if isCommit := strings.Trim(protobufVersion, "0123456789abcdef") == ""; isCommit {
238 command{Dir: testDir}.mustRun(t, "git", "clone", "https://github.com/protocolbuffers/protobuf", "protobuf-"+protobufVersion)
239 command{Dir: protobufPath}.mustRun(t, "git", "checkout", protobufVersion)
240 } else {
241 url := fmt.Sprintf("https://github.com/google/protobuf/releases/download/v%v/protobuf-all-%v.tar.gz", protobufVersion, protobufVersion)
Joe Tsai8de66752019-12-19 16:38:52 -0800242 downloadArchive(check, protobufPath, url, "protobuf-"+protobufVersion, protobufSHA256)
Joe Tsai387873d2020-04-28 14:44:38 -0700243 }
Joe Tsai707894e2019-03-01 12:50:52 -0800244
Herbie Ongd64dceb2019-04-25 01:19:57 -0700245 fmt.Printf("build %v\n", filepath.Base(protobufPath))
Joe Tsai7164af52019-08-07 19:27:43 -0700246 command{Dir: protobufPath}.mustRun(t, "./autogen.sh")
247 command{Dir: protobufPath}.mustRun(t, "./configure")
248 command{Dir: protobufPath}.mustRun(t, "make")
249 command{Dir: filepath.Join(protobufPath, "conformance")}.mustRun(t, "make")
Joe Tsai707894e2019-03-01 12:50:52 -0800250 }
Herbie Ongd64dceb2019-04-25 01:19:57 -0700251 check(os.Setenv("PROTOBUF_ROOT", protobufPath)) // for generate-protos
252 registerBinary("conform-test-runner", filepath.Join(protobufPath, "conformance", "conformance-test-runner"))
253 registerBinary("protoc", filepath.Join(protobufPath, "src", "protoc"))
Joe Tsaidb5c9002020-09-05 11:24:42 -0700254 finishWork()
Joe Tsai707894e2019-03-01 12:50:52 -0800255
256 // Download each Go toolchain version.
257 for _, v := range golangVersions {
Joe Tsaidb5c9002020-09-05 11:24:42 -0700258 goDir := startWork("go" + v)
259 if _, err := os.Stat(goDir); err != nil {
260 fmt.Printf("download %v\n", filepath.Base(goDir))
Joe Tsai707894e2019-03-01 12:50:52 -0800261 url := fmt.Sprintf("https://dl.google.com/go/go%v.%v-%v.tar.gz", v, runtime.GOOS, runtime.GOARCH)
Joe Tsaidb5c9002020-09-05 11:24:42 -0700262 downloadArchive(check, goDir, url, "go", "") // skip SHA256 check as we fetch over https from a trusted domain
Joe Tsai707894e2019-03-01 12:50:52 -0800263 }
Joe Tsaidb5c9002020-09-05 11:24:42 -0700264 registerBinary("go"+v, filepath.Join(goDir, "bin", "go"))
265 finishWork()
Joe Tsai707894e2019-03-01 12:50:52 -0800266 }
267 registerBinary("go", filepath.Join(testDir, "go"+golangLatest, "bin", "go"))
268 registerBinary("gofmt", filepath.Join(testDir, "go"+golangLatest, "bin", "gofmt"))
Joe Tsai707894e2019-03-01 12:50:52 -0800269
Joe Tsai8de66752019-12-19 16:38:52 -0800270 // Download the staticcheck tool.
Joe Tsaidb5c9002020-09-05 11:24:42 -0700271 checkDir := startWork("staticcheck-" + staticcheckVersion)
272 if _, err := os.Stat(checkDir); err != nil {
273 fmt.Printf("download %v\n", filepath.Base(checkDir))
Joe Tsai8de66752019-12-19 16:38:52 -0800274 url := fmt.Sprintf("https://github.com/dominikh/go-tools/releases/download/%v/staticcheck_%v_%v.tar.gz", staticcheckVersion, runtime.GOOS, runtime.GOARCH)
Joe Tsaidb5c9002020-09-05 11:24:42 -0700275 downloadArchive(check, checkDir, url, "staticcheck", staticcheckSHA256s[runtime.GOOS+"/"+runtime.GOARCH])
Joe Tsai8de66752019-12-19 16:38:52 -0800276 }
Joe Tsaidb5c9002020-09-05 11:24:42 -0700277 registerBinary("staticcheck", filepath.Join(checkDir, "staticcheck"))
278 finishWork()
Joe Tsai8de66752019-12-19 16:38:52 -0800279
Joe Tsaie7ab1122021-03-02 17:09:55 -0800280 // GitHub actions sets GOROOT, which confuses invocations of the Go toolchain.
Joe Tsai707894e2019-03-01 12:50:52 -0800281 // Explicitly clear GOROOT, so each toolchain uses their default GOROOT.
282 check(os.Unsetenv("GOROOT"))
283
Joe Tsai6a2180f2019-07-11 16:34:17 -0700284 // Set a cache directory outside the test directory.
285 check(os.Setenv("GOCACHE", filepath.Join(repoRoot, ".gocache")))
Joe Tsai707894e2019-03-01 12:50:52 -0800286
287 // Setup GOPATH for pre-module support (i.e., go1.10 and earlier).
Joe Tsaidb5c9002020-09-05 11:24:42 -0700288 goPath = startWork("gopath")
Joe Tsai7164af52019-08-07 19:27:43 -0700289 modulePath = strings.TrimSpace(command{Dir: testDir}.mustRun(t, "go", "list", "-m", "-f", "{{.Path}}"))
Joe Tsai707894e2019-03-01 12:50:52 -0800290 check(os.RemoveAll(filepath.Join(goPath, "src")))
291 check(os.MkdirAll(filepath.Join(goPath, "src", filepath.Dir(modulePath)), 0775))
292 check(os.Symlink(repoRoot, filepath.Join(goPath, "src", modulePath)))
Joe Tsai7164af52019-08-07 19:27:43 -0700293 command{Dir: repoRoot}.mustRun(t, "go", "mod", "tidy")
294 command{Dir: repoRoot}.mustRun(t, "go", "mod", "vendor")
Joe Tsai707894e2019-03-01 12:50:52 -0800295 check(os.Setenv("GOPATH", goPath))
Joe Tsaidb5c9002020-09-05 11:24:42 -0700296 finishWork()
Joe Tsai707894e2019-03-01 12:50:52 -0800297}
298
Damien Neila80229e2019-06-20 12:53:48 -0700299func downloadFile(check func(error), dstPath, srcURL string) {
300 resp, err := http.Get(srcURL)
301 check(err)
302 defer resp.Body.Close()
303
304 check(os.MkdirAll(filepath.Dir(dstPath), 0775))
305 f, err := os.Create(dstPath)
306 check(err)
307
308 _, err = io.Copy(f, resp.Body)
309 check(err)
310}
311
Joe Tsai8de66752019-12-19 16:38:52 -0800312func downloadArchive(check func(error), dstPath, srcURL, skipPrefix, wantSHA256 string) {
Joe Tsai707894e2019-03-01 12:50:52 -0800313 check(os.RemoveAll(dstPath))
314
315 resp, err := http.Get(srcURL)
316 check(err)
317 defer resp.Body.Close()
318
Joe Tsai8de66752019-12-19 16:38:52 -0800319 var r io.Reader = resp.Body
320 if wantSHA256 != "" {
321 b, err := ioutil.ReadAll(resp.Body)
322 check(err)
323 r = bytes.NewReader(b)
324
325 if gotSHA256 := fmt.Sprintf("%x", sha256.Sum256(b)); gotSHA256 != wantSHA256 {
326 check(fmt.Errorf("checksum validation error:\ngot %v\nwant %v", gotSHA256, wantSHA256))
327 }
328 }
329
330 zr, err := gzip.NewReader(r)
Joe Tsai707894e2019-03-01 12:50:52 -0800331 check(err)
332
333 tr := tar.NewReader(zr)
334 for {
335 h, err := tr.Next()
336 if err == io.EOF {
337 return
338 }
339 check(err)
340
Joe Tsaif3987842019-03-02 13:35:17 -0800341 // Skip directories or files outside the prefix directory.
342 if len(skipPrefix) > 0 {
343 if !strings.HasPrefix(h.Name, skipPrefix) {
344 continue
345 }
346 if len(h.Name) > len(skipPrefix) && h.Name[len(skipPrefix)] != '/' {
347 continue
348 }
349 }
350
351 path := strings.TrimPrefix(strings.TrimPrefix(h.Name, skipPrefix), "/")
Joe Tsai707894e2019-03-01 12:50:52 -0800352 path = filepath.Join(dstPath, filepath.FromSlash(path))
353 mode := os.FileMode(h.Mode & 0777)
354 switch h.Typeflag {
355 case tar.TypeReg:
356 b, err := ioutil.ReadAll(tr)
357 check(err)
358 check(ioutil.WriteFile(path, b, mode))
359 case tar.TypeDir:
360 check(os.Mkdir(path, mode))
361 }
362 }
363}
364
Joe Tsai4f3de442019-08-07 19:33:51 -0700365func mustHandleFlags(t *testing.T) {
366 if *regenerate {
367 t.Run("Generate", func(t *testing.T) {
368 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-types", "-execute"))
369 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-protos", "-execute"))
370 files := strings.Split(strings.TrimSpace(mustRunCommand(t, "git", "ls-files", "*.go")), "\n")
371 mustRunCommand(t, append([]string{"gofmt", "-w"}, files...)...)
372 })
373 }
374 if *buildRelease {
375 t.Run("BuildRelease", func(t *testing.T) {
Joe Tsai4ab2bc92020-03-10 17:38:07 -0700376 v := version.String()
Joe Tsai4f3de442019-08-07 19:33:51 -0700377 for _, goos := range []string{"linux", "darwin", "windows"} {
378 for _, goarch := range []string{"386", "amd64"} {
Joe Tsai5ebc0b42020-09-08 11:32:36 -0700379 // Avoid Darwin since 10.15 dropped support for i386.
380 if goos == "darwin" && goarch == "386" {
381 continue
382 }
383
Joe Tsai4f3de442019-08-07 19:33:51 -0700384 binPath := filepath.Join("bin", fmt.Sprintf("protoc-gen-go.%v.%v.%v", v, goos, goarch))
385
386 // Build the binary.
387 cmd := command{Env: append(os.Environ(), "GOOS="+goos, "GOARCH="+goarch)}
Joe Tsai576cfb32019-09-04 22:50:42 -0700388 cmd.mustRun(t, "go", "build", "-trimpath", "-ldflags", "-s -w -buildid=", "-o", binPath, "./cmd/protoc-gen-go")
Joe Tsai4f3de442019-08-07 19:33:51 -0700389
390 // Archive and compress the binary.
391 in, err := ioutil.ReadFile(binPath)
392 if err != nil {
393 t.Fatal(err)
394 }
395 out := new(bytes.Buffer)
Damien Neil50a85912021-05-20 11:37:23 -0700396 suffix := ""
397 comment := fmt.Sprintf("protoc-gen-go VERSION=%v GOOS=%v GOARCH=%v", v, goos, goarch)
398 switch goos {
399 case "windows":
400 suffix = ".zip"
401 zw := zip.NewWriter(out)
402 zw.SetComment(comment)
403 fw, _ := zw.Create("protoc-gen-go.exe")
404 fw.Write(in)
405 zw.Close()
406 default:
407 suffix = ".tar.gz"
408 gz, _ := gzip.NewWriterLevel(out, gzip.BestCompression)
409 gz.Comment = comment
410 tw := tar.NewWriter(gz)
411 tw.WriteHeader(&tar.Header{
412 Name: "protoc-gen-go",
413 Mode: int64(0775),
414 Size: int64(len(in)),
415 })
416 tw.Write(in)
417 tw.Close()
418 gz.Close()
419 }
420 if err := ioutil.WriteFile(binPath+suffix, out.Bytes(), 0664); err != nil {
Joe Tsai4f3de442019-08-07 19:33:51 -0700421 t.Fatal(err)
422 }
423 }
424 }
425 })
426 }
427 if *regenerate || *buildRelease {
428 t.SkipNow()
429 }
430}
431
Damien Neil3a185602020-02-21 09:16:19 -0800432var copyrightRegex = []*regexp.Regexp{
433 regexp.MustCompile(`^// Copyright \d\d\d\d The Go Authors\. All rights reserved.
434// Use of this source code is governed by a BSD-style
435// license that can be found in the LICENSE file\.
436`),
437 // Generated .pb.go files from main protobuf repo.
438 regexp.MustCompile(`^// Protocol Buffers - Google's data interchange format
439// Copyright \d\d\d\d Google Inc\. All rights reserved\.
440`),
441}
442
Damien Neil3a185602020-02-21 09:16:19 -0800443func mustHaveCopyrightHeader(t *testing.T, files []string) {
444 var bad []string
445File:
446 for _, file := range files {
Damien Neil3a185602020-02-21 09:16:19 -0800447 b, err := ioutil.ReadFile(file)
448 if err != nil {
449 t.Fatal(err)
450 }
451 for _, re := range copyrightRegex {
452 if loc := re.FindIndex(b); loc != nil && loc[0] == 0 {
453 continue File
454 }
455 }
456 bad = append(bad, file)
457 }
458 if len(bad) > 0 {
459 t.Fatalf("files with missing/bad copyright headers:\n %v", strings.Join(bad, "\n "))
460 }
461}
462
Joe Tsai7164af52019-08-07 19:27:43 -0700463type command struct {
464 Dir string
465 Env []string
466}
467
468func (c command) mustRun(t *testing.T, args ...string) string {
Joe Tsai707894e2019-03-01 12:50:52 -0800469 t.Helper()
470 stdout := new(bytes.Buffer)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700471 stderr := new(bytes.Buffer)
Joe Tsai707894e2019-03-01 12:50:52 -0800472 cmd := exec.Command(args[0], args[1:]...)
Joe Tsai7164af52019-08-07 19:27:43 -0700473 cmd.Dir = "."
474 if c.Dir != "" {
475 cmd.Dir = c.Dir
476 }
477 cmd.Env = os.Environ()
478 if c.Env != nil {
479 cmd.Env = c.Env
480 }
481 cmd.Env = append(cmd.Env, "PWD="+cmd.Dir)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700482 cmd.Stdout = stdout
483 cmd.Stderr = stderr
Joe Tsai707894e2019-03-01 12:50:52 -0800484 if err := cmd.Run(); err != nil {
Herbie Ong4630b3d2019-03-19 16:42:01 -0700485 t.Fatalf("executing (%v): %v\n%s%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
Joe Tsai707894e2019-03-01 12:50:52 -0800486 }
487 return stdout.String()
488}
Damien Neila80229e2019-06-20 12:53:48 -0700489
Joe Tsai7164af52019-08-07 19:27:43 -0700490func mustRunCommand(t *testing.T, args ...string) string {
491 t.Helper()
492 return command{}.mustRun(t, args...)
493}