blob: 15735d9c7dd2e24af8c3140efcd9dbee79685c3f [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"
11 "bytes"
12 "compress/gzip"
Joe Tsai8de66752019-12-19 16:38:52 -080013 "crypto/sha256"
Joe Tsai707894e2019-03-01 12:50:52 -080014 "flag"
15 "fmt"
16 "io"
17 "io/ioutil"
18 "net/http"
19 "os"
20 "os/exec"
21 "path/filepath"
Damien Neil3a185602020-02-21 09:16:19 -080022 "regexp"
Joe Tsai707894e2019-03-01 12:50:52 -080023 "runtime"
24 "strings"
Joe Tsai62200db2019-07-11 17:34:10 -070025 "sync"
Joe Tsai707894e2019-03-01 12:50:52 -080026 "testing"
Joe Tsaif3987842019-03-02 13:35:17 -080027 "time"
Joe Tsai4f3de442019-08-07 19:33:51 -070028
Joe Tsai4ab2bc92020-03-10 17:38:07 -070029 "google.golang.org/protobuf/internal/version"
Joe Tsai707894e2019-03-01 12:50:52 -080030)
31
32var (
Joe Tsai4f3de442019-08-07 19:33:51 -070033 regenerate = flag.Bool("regenerate", false, "regenerate files")
34 buildRelease = flag.Bool("buildRelease", false, "build release binaries")
Joe Tsai707894e2019-03-01 12:50:52 -080035
Joe Tsai164b5262020-05-04 11:09:31 -070036 protobufVersion = "ef7cc811" // v3.12.0-rc1
Joe Tsai8de66752019-12-19 16:38:52 -080037 protobufSHA256 = "" // ignored if protobufVersion is a git hash
38
Joe Tsai16365ed2020-08-12 11:14:11 -070039 golangVersions = []string{"1.9.7", "1.10.8", "1.11.13", "1.12.17", "1.13.15", "1.14.7", "1.15"}
Joe Tsai8de66752019-12-19 16:38:52 -080040 golangLatest = golangVersions[len(golangVersions)-1]
41
42 staticcheckVersion = "2020.1.4"
43 staticcheckSHA256s = map[string]string{
Joe Tsai8de66752019-12-19 16:38:52 -080044 "darwin/amd64": "5706d101426c025e8f165309e0cb2932e54809eb035ff23ebe19df0f810699d8",
45 "linux/386": "e4dbf94e940678ae7108f0d22c7c2992339bc10a8fb384e7e734b1531a429a1c",
46 "linux/amd64": "09d2c2002236296de2c757df111fe3ae858b89f9e183f645ad01f8135c83c519",
47 }
Joe Tsai707894e2019-03-01 12:50:52 -080048
Joe Tsai9e88bc02019-03-12 01:30:40 -070049 // purgeTimeout determines the maximum age of unused sub-directories.
50 purgeTimeout = 30 * 24 * time.Hour // 1 month
Joe Tsai707894e2019-03-01 12:50:52 -080051
52 // Variables initialized by mustInitDeps.
Herbie Ongd64dceb2019-04-25 01:19:57 -070053 goPath string
54 modulePath string
55 protobufPath string
Joe Tsai707894e2019-03-01 12:50:52 -080056)
57
58func Test(t *testing.T) {
59 mustInitDeps(t)
Joe Tsai4f3de442019-08-07 19:33:51 -070060 mustHandleFlags(t)
Joe Tsai707894e2019-03-01 12:50:52 -080061
Damien Neil4d8936d2020-02-21 10:32:56 -080062 // Report dirt in the working tree quickly, rather than after
63 // going through all the presubmits.
64 //
65 // Fail the test late, so we can test uncommitted changes with -failfast.
Joe Tsaif75a3382019-12-19 17:42:41 -080066 gitDiff := mustRunCommand(t, "git", "diff", "HEAD")
67 if strings.TrimSpace(gitDiff) != "" {
68 fmt.Printf("WARNING: working tree contains uncommitted changes:\n%v\n", gitDiff)
Damien Neil4d8936d2020-02-21 10:32:56 -080069 }
Joe Tsaif75a3382019-12-19 17:42:41 -080070 gitUntracked := mustRunCommand(t, "git", "ls-files", "--others", "--exclude-standard")
71 if strings.TrimSpace(gitUntracked) != "" {
72 fmt.Printf("WARNING: working tree contains untracked files:\n%v\n", gitUntracked)
Damien Neil4d8936d2020-02-21 10:32:56 -080073 }
74
75 // Do the relatively fast checks up-front.
76 t.Run("GeneratedGoFiles", func(t *testing.T) {
77 diff := mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-types")
78 if strings.TrimSpace(diff) != "" {
79 t.Fatalf("stale generated files:\n%v", diff)
80 }
81 diff = mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-protos")
82 if strings.TrimSpace(diff) != "" {
83 t.Fatalf("stale generated files:\n%v", diff)
84 }
85 })
86 t.Run("FormattedGoFiles", func(t *testing.T) {
87 files := strings.Split(strings.TrimSpace(mustRunCommand(t, "git", "ls-files", "*.go")), "\n")
88 diff := mustRunCommand(t, append([]string{"gofmt", "-d"}, files...)...)
89 if strings.TrimSpace(diff) != "" {
90 t.Fatalf("unformatted source files:\n%v", diff)
91 }
92 })
93 t.Run("CopyrightHeaders", func(t *testing.T) {
94 files := strings.Split(strings.TrimSpace(mustRunCommand(t, "git", "ls-files", "*.go", "*.proto")), "\n")
95 mustHaveCopyrightHeader(t, files)
96 })
97
Joe Tsai62200db2019-07-11 17:34:10 -070098 var wg sync.WaitGroup
99 sema := make(chan bool, (runtime.NumCPU()+1)/2)
100 for i := range golangVersions {
101 goVersion := golangVersions[i]
102 goLabel := "Go" + goVersion
Joe Tsai467a9cd2020-07-08 10:26:03 -0700103 runGo := func(label string, cmd command, args ...string) {
Joe Tsai62200db2019-07-11 17:34:10 -0700104 wg.Add(1)
105 sema <- true
106 go func() {
107 defer wg.Done()
108 defer func() { <-sema }()
109 t.Run(goLabel+"/"+label, func(t *testing.T) {
110 args[0] += goVersion
Joe Tsai467a9cd2020-07-08 10:26:03 -0700111 cmd.mustRun(t, args...)
Joe Tsai707894e2019-03-01 12:50:52 -0800112 })
Joe Tsai62200db2019-07-11 17:34:10 -0700113 }()
114 }
115
116 workDir := filepath.Join(goPath, "src", modulePath)
Joe Tsai467a9cd2020-07-08 10:26:03 -0700117 runGo("Normal", command{Dir: workDir}, "go", "test", "-race", "./...")
118 runGo("PureGo", command{Dir: workDir}, "go", "test", "-race", "-tags", "purego", "./...")
119 runGo("Reflect", command{Dir: workDir}, "go", "test", "-race", "-tags", "protoreflect", "./...")
Joe Tsai62200db2019-07-11 17:34:10 -0700120 if goVersion == golangLatest {
Joe Tsai467a9cd2020-07-08 10:26:03 -0700121 runGo("ProtoLegacy", command{Dir: workDir}, "go", "test", "-race", "-tags", "protolegacy", "./...")
122 runGo("ProtocGenGo", command{Dir: "cmd/protoc-gen-go/testdata"}, "go", "test")
123 runGo("Conformance", command{Dir: "internal/conformance"}, "go", "test", "-execute")
124
125 // Only run the 32-bit compatability tests for Linux;
126 // avoid Darwin since 10.15 dropped support i386 code execution.
127 if runtime.GOOS == "linux" {
128 runGo("Arch32Bit", command{Dir: workDir, Env: append(os.Environ(), "GOARCH=386")}, "go", "test", "./...")
129 }
Joe Tsai62200db2019-07-11 17:34:10 -0700130 }
Joe Tsai707894e2019-03-01 12:50:52 -0800131 }
Joe Tsai62200db2019-07-11 17:34:10 -0700132 wg.Wait()
Joe Tsai707894e2019-03-01 12:50:52 -0800133
Joe Tsai8de66752019-12-19 16:38:52 -0800134 t.Run("GoStaticCheck", func(t *testing.T) {
135 checks := []string{
136 "all", // start with all checks enabled
137 "-SA1019", // disable deprecated usage check
138 "-S*", // disable code simplication checks
139 "-ST*", // disable coding style checks
140 "-U*", // disable unused declaration checks
141 }
142 out := mustRunCommand(t, "staticcheck", "-checks="+strings.Join(checks, ","), "-fail=none", "./...")
143
144 // Filter out findings from certain paths.
145 var findings []string
146 for _, finding := range strings.Split(strings.TrimSpace(out), "\n") {
147 switch {
148 case strings.HasPrefix(finding, "internal/testprotos/legacy/"):
149 default:
150 findings = append(findings, finding)
151 }
152 }
153 if len(findings) > 0 {
154 t.Fatalf("staticcheck findings:\n%v", strings.Join(findings, "\n"))
155 }
156 })
Joe Tsai707894e2019-03-01 12:50:52 -0800157 t.Run("CommittedGitChanges", func(t *testing.T) {
Joe Tsaif75a3382019-12-19 17:42:41 -0800158 if strings.TrimSpace(gitDiff) != "" {
Damien Neil4d8936d2020-02-21 10:32:56 -0800159 t.Fatalf("uncommitted changes")
Joe Tsai707894e2019-03-01 12:50:52 -0800160 }
161 })
162 t.Run("TrackedGitFiles", func(t *testing.T) {
Joe Tsaif75a3382019-12-19 17:42:41 -0800163 if strings.TrimSpace(gitUntracked) != "" {
Damien Neil4d8936d2020-02-21 10:32:56 -0800164 t.Fatalf("untracked files")
Joe Tsai707894e2019-03-01 12:50:52 -0800165 }
166 })
167}
168
169func mustInitDeps(t *testing.T) {
170 check := func(err error) {
171 t.Helper()
172 if err != nil {
173 t.Fatal(err)
174 }
175 }
176
177 // Determine the directory to place the test directory.
178 repoRoot, err := os.Getwd()
179 check(err)
180 testDir := filepath.Join(repoRoot, ".cache")
181 check(os.MkdirAll(testDir, 0775))
182
Joe Tsaif3987842019-03-02 13:35:17 -0800183 // Travis-CI has a hard-coded timeout where it kills the test after
184 // 10 minutes of a lack of activity on stdout.
185 // We work around this restriction by periodically printing the timestamp.
186 ticker := time.NewTicker(5 * time.Minute)
187 done := make(chan struct{})
188 go func() {
189 now := time.Now()
190 for {
191 select {
192 case t := <-ticker.C:
193 fmt.Printf("\tt=%0.fmin\n", t.Sub(now).Minutes())
194 case <-done:
195 return
196 }
197 }
198 }()
199 defer close(done)
200 defer ticker.Stop()
201
Joe Tsai707894e2019-03-01 12:50:52 -0800202 // Delete the current directory if non-empty,
203 // which only occurs if a dependency failed to initialize properly.
204 var workingDir string
Joe Tsaidb5c9002020-09-05 11:24:42 -0700205 finishedDirs := map[string]bool{}
Joe Tsai707894e2019-03-01 12:50:52 -0800206 defer func() {
207 if workingDir != "" {
208 os.RemoveAll(workingDir) // best-effort
209 }
210 }()
Joe Tsaidb5c9002020-09-05 11:24:42 -0700211 startWork := func(name string) string {
212 workingDir = filepath.Join(testDir, name)
213 return workingDir
214 }
215 finishWork := func() {
216 finishedDirs[workingDir] = true
217 workingDir = ""
218 }
Joe Tsai707894e2019-03-01 12:50:52 -0800219
220 // Delete other sub-directories that are no longer relevant.
221 defer func() {
Joe Tsai9e88bc02019-03-12 01:30:40 -0700222 now := time.Now()
Joe Tsai707894e2019-03-01 12:50:52 -0800223 fis, _ := ioutil.ReadDir(testDir)
224 for _, fi := range fis {
Joe Tsaidb5c9002020-09-05 11:24:42 -0700225 dir := filepath.Join(testDir, fi.Name())
226 if finishedDirs[dir] {
227 os.Chtimes(dir, now, now) // best-effort
Joe Tsai9e88bc02019-03-12 01:30:40 -0700228 continue
Joe Tsai707894e2019-03-01 12:50:52 -0800229 }
Joe Tsai9e88bc02019-03-12 01:30:40 -0700230 if now.Sub(fi.ModTime()) < purgeTimeout {
231 continue
232 }
233 fmt.Printf("delete %v\n", fi.Name())
Joe Tsaidb5c9002020-09-05 11:24:42 -0700234 os.RemoveAll(dir) // best-effort
Joe Tsai707894e2019-03-01 12:50:52 -0800235 }
236 }()
237
238 // The bin directory contains symlinks to each tool by version.
239 // It is safe to delete this directory and run the test script from scratch.
Joe Tsaidb5c9002020-09-05 11:24:42 -0700240 binPath := startWork("bin")
Joe Tsai707894e2019-03-01 12:50:52 -0800241 check(os.RemoveAll(binPath))
242 check(os.Mkdir(binPath, 0775))
243 check(os.Setenv("PATH", binPath+":"+os.Getenv("PATH")))
244 registerBinary := func(name, path string) {
245 check(os.Symlink(path, filepath.Join(binPath, name)))
246 }
Joe Tsaidb5c9002020-09-05 11:24:42 -0700247 finishWork()
Joe Tsai707894e2019-03-01 12:50:52 -0800248
249 // Download and build the protobuf toolchain.
250 // We avoid downloading the pre-compiled binaries since they do not contain
251 // the conformance test runner.
Joe Tsaidb5c9002020-09-05 11:24:42 -0700252 protobufPath = startWork("protobuf-" + protobufVersion)
Herbie Ongd64dceb2019-04-25 01:19:57 -0700253 if _, err := os.Stat(protobufPath); err != nil {
254 fmt.Printf("download %v\n", filepath.Base(protobufPath))
Joe Tsai387873d2020-04-28 14:44:38 -0700255 if isCommit := strings.Trim(protobufVersion, "0123456789abcdef") == ""; isCommit {
256 command{Dir: testDir}.mustRun(t, "git", "clone", "https://github.com/protocolbuffers/protobuf", "protobuf-"+protobufVersion)
257 command{Dir: protobufPath}.mustRun(t, "git", "checkout", protobufVersion)
258 } else {
259 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 -0800260 downloadArchive(check, protobufPath, url, "protobuf-"+protobufVersion, protobufSHA256)
Joe Tsai387873d2020-04-28 14:44:38 -0700261 }
Joe Tsai707894e2019-03-01 12:50:52 -0800262
Herbie Ongd64dceb2019-04-25 01:19:57 -0700263 fmt.Printf("build %v\n", filepath.Base(protobufPath))
Joe Tsai7164af52019-08-07 19:27:43 -0700264 command{Dir: protobufPath}.mustRun(t, "./autogen.sh")
265 command{Dir: protobufPath}.mustRun(t, "./configure")
266 command{Dir: protobufPath}.mustRun(t, "make")
267 command{Dir: filepath.Join(protobufPath, "conformance")}.mustRun(t, "make")
Joe Tsai707894e2019-03-01 12:50:52 -0800268 }
Herbie Ongd64dceb2019-04-25 01:19:57 -0700269 check(os.Setenv("PROTOBUF_ROOT", protobufPath)) // for generate-protos
270 registerBinary("conform-test-runner", filepath.Join(protobufPath, "conformance", "conformance-test-runner"))
271 registerBinary("protoc", filepath.Join(protobufPath, "src", "protoc"))
Joe Tsaidb5c9002020-09-05 11:24:42 -0700272 finishWork()
Joe Tsai707894e2019-03-01 12:50:52 -0800273
274 // Download each Go toolchain version.
275 for _, v := range golangVersions {
Joe Tsaidb5c9002020-09-05 11:24:42 -0700276 goDir := startWork("go" + v)
277 if _, err := os.Stat(goDir); err != nil {
278 fmt.Printf("download %v\n", filepath.Base(goDir))
Joe Tsai707894e2019-03-01 12:50:52 -0800279 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 -0700280 downloadArchive(check, goDir, url, "go", "") // skip SHA256 check as we fetch over https from a trusted domain
Joe Tsai707894e2019-03-01 12:50:52 -0800281 }
Joe Tsaidb5c9002020-09-05 11:24:42 -0700282 registerBinary("go"+v, filepath.Join(goDir, "bin", "go"))
283 finishWork()
Joe Tsai707894e2019-03-01 12:50:52 -0800284 }
285 registerBinary("go", filepath.Join(testDir, "go"+golangLatest, "bin", "go"))
286 registerBinary("gofmt", filepath.Join(testDir, "go"+golangLatest, "bin", "gofmt"))
Joe Tsai707894e2019-03-01 12:50:52 -0800287
Joe Tsai8de66752019-12-19 16:38:52 -0800288 // Download the staticcheck tool.
Joe Tsaidb5c9002020-09-05 11:24:42 -0700289 checkDir := startWork("staticcheck-" + staticcheckVersion)
290 if _, err := os.Stat(checkDir); err != nil {
291 fmt.Printf("download %v\n", filepath.Base(checkDir))
Joe Tsai8de66752019-12-19 16:38:52 -0800292 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 -0700293 downloadArchive(check, checkDir, url, "staticcheck", staticcheckSHA256s[runtime.GOOS+"/"+runtime.GOARCH])
Joe Tsai8de66752019-12-19 16:38:52 -0800294 }
Joe Tsaidb5c9002020-09-05 11:24:42 -0700295 registerBinary("staticcheck", filepath.Join(checkDir, "staticcheck"))
296 finishWork()
Joe Tsai8de66752019-12-19 16:38:52 -0800297
Joe Tsai707894e2019-03-01 12:50:52 -0800298 // Travis-CI sets GOROOT, which confuses invocations of the Go toolchain.
299 // Explicitly clear GOROOT, so each toolchain uses their default GOROOT.
300 check(os.Unsetenv("GOROOT"))
301
Joe Tsai6a2180f2019-07-11 16:34:17 -0700302 // Set a cache directory outside the test directory.
303 check(os.Setenv("GOCACHE", filepath.Join(repoRoot, ".gocache")))
Joe Tsai707894e2019-03-01 12:50:52 -0800304
305 // Setup GOPATH for pre-module support (i.e., go1.10 and earlier).
Joe Tsaidb5c9002020-09-05 11:24:42 -0700306 goPath = startWork("gopath")
Joe Tsai7164af52019-08-07 19:27:43 -0700307 modulePath = strings.TrimSpace(command{Dir: testDir}.mustRun(t, "go", "list", "-m", "-f", "{{.Path}}"))
Joe Tsai707894e2019-03-01 12:50:52 -0800308 check(os.RemoveAll(filepath.Join(goPath, "src")))
309 check(os.MkdirAll(filepath.Join(goPath, "src", filepath.Dir(modulePath)), 0775))
310 check(os.Symlink(repoRoot, filepath.Join(goPath, "src", modulePath)))
Joe Tsai7164af52019-08-07 19:27:43 -0700311 command{Dir: repoRoot}.mustRun(t, "go", "mod", "tidy")
312 command{Dir: repoRoot}.mustRun(t, "go", "mod", "vendor")
Joe Tsai707894e2019-03-01 12:50:52 -0800313 check(os.Setenv("GOPATH", goPath))
Joe Tsaidb5c9002020-09-05 11:24:42 -0700314 finishWork()
Joe Tsai707894e2019-03-01 12:50:52 -0800315}
316
Damien Neila80229e2019-06-20 12:53:48 -0700317func downloadFile(check func(error), dstPath, srcURL string) {
318 resp, err := http.Get(srcURL)
319 check(err)
320 defer resp.Body.Close()
321
322 check(os.MkdirAll(filepath.Dir(dstPath), 0775))
323 f, err := os.Create(dstPath)
324 check(err)
325
326 _, err = io.Copy(f, resp.Body)
327 check(err)
328}
329
Joe Tsai8de66752019-12-19 16:38:52 -0800330func downloadArchive(check func(error), dstPath, srcURL, skipPrefix, wantSHA256 string) {
Joe Tsai707894e2019-03-01 12:50:52 -0800331 check(os.RemoveAll(dstPath))
332
333 resp, err := http.Get(srcURL)
334 check(err)
335 defer resp.Body.Close()
336
Joe Tsai8de66752019-12-19 16:38:52 -0800337 var r io.Reader = resp.Body
338 if wantSHA256 != "" {
339 b, err := ioutil.ReadAll(resp.Body)
340 check(err)
341 r = bytes.NewReader(b)
342
343 if gotSHA256 := fmt.Sprintf("%x", sha256.Sum256(b)); gotSHA256 != wantSHA256 {
344 check(fmt.Errorf("checksum validation error:\ngot %v\nwant %v", gotSHA256, wantSHA256))
345 }
346 }
347
348 zr, err := gzip.NewReader(r)
Joe Tsai707894e2019-03-01 12:50:52 -0800349 check(err)
350
351 tr := tar.NewReader(zr)
352 for {
353 h, err := tr.Next()
354 if err == io.EOF {
355 return
356 }
357 check(err)
358
Joe Tsaif3987842019-03-02 13:35:17 -0800359 // Skip directories or files outside the prefix directory.
360 if len(skipPrefix) > 0 {
361 if !strings.HasPrefix(h.Name, skipPrefix) {
362 continue
363 }
364 if len(h.Name) > len(skipPrefix) && h.Name[len(skipPrefix)] != '/' {
365 continue
366 }
367 }
368
369 path := strings.TrimPrefix(strings.TrimPrefix(h.Name, skipPrefix), "/")
Joe Tsai707894e2019-03-01 12:50:52 -0800370 path = filepath.Join(dstPath, filepath.FromSlash(path))
371 mode := os.FileMode(h.Mode & 0777)
372 switch h.Typeflag {
373 case tar.TypeReg:
374 b, err := ioutil.ReadAll(tr)
375 check(err)
376 check(ioutil.WriteFile(path, b, mode))
377 case tar.TypeDir:
378 check(os.Mkdir(path, mode))
379 }
380 }
381}
382
Joe Tsai4f3de442019-08-07 19:33:51 -0700383func mustHandleFlags(t *testing.T) {
384 if *regenerate {
385 t.Run("Generate", func(t *testing.T) {
386 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-types", "-execute"))
387 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-protos", "-execute"))
388 files := strings.Split(strings.TrimSpace(mustRunCommand(t, "git", "ls-files", "*.go")), "\n")
389 mustRunCommand(t, append([]string{"gofmt", "-w"}, files...)...)
390 })
391 }
392 if *buildRelease {
393 t.Run("BuildRelease", func(t *testing.T) {
Joe Tsai4ab2bc92020-03-10 17:38:07 -0700394 v := version.String()
Joe Tsai4f3de442019-08-07 19:33:51 -0700395 for _, goos := range []string{"linux", "darwin", "windows"} {
396 for _, goarch := range []string{"386", "amd64"} {
Joe Tsai5ebc0b42020-09-08 11:32:36 -0700397 // Avoid Darwin since 10.15 dropped support for i386.
398 if goos == "darwin" && goarch == "386" {
399 continue
400 }
401
Joe Tsai4f3de442019-08-07 19:33:51 -0700402 binPath := filepath.Join("bin", fmt.Sprintf("protoc-gen-go.%v.%v.%v", v, goos, goarch))
403
404 // Build the binary.
405 cmd := command{Env: append(os.Environ(), "GOOS="+goos, "GOARCH="+goarch)}
Joe Tsai576cfb32019-09-04 22:50:42 -0700406 cmd.mustRun(t, "go", "build", "-trimpath", "-ldflags", "-s -w -buildid=", "-o", binPath, "./cmd/protoc-gen-go")
Joe Tsai4f3de442019-08-07 19:33:51 -0700407
408 // Archive and compress the binary.
409 in, err := ioutil.ReadFile(binPath)
410 if err != nil {
411 t.Fatal(err)
412 }
413 out := new(bytes.Buffer)
414 gz, _ := gzip.NewWriterLevel(out, gzip.BestCompression)
415 gz.Comment = fmt.Sprintf("protoc-gen-go VERSION=%v GOOS=%v GOARCH=%v", v, goos, goarch)
416 tw := tar.NewWriter(gz)
417 tw.WriteHeader(&tar.Header{
418 Name: "protoc-gen-go",
419 Mode: int64(0775),
420 Size: int64(len(in)),
421 })
422 tw.Write(in)
423 tw.Close()
424 gz.Close()
425 if err := ioutil.WriteFile(binPath+".tar.gz", out.Bytes(), 0664); err != nil {
426 t.Fatal(err)
427 }
428 }
429 }
430 })
431 }
432 if *regenerate || *buildRelease {
433 t.SkipNow()
434 }
435}
436
Damien Neil3a185602020-02-21 09:16:19 -0800437var copyrightRegex = []*regexp.Regexp{
438 regexp.MustCompile(`^// Copyright \d\d\d\d The Go Authors\. All rights reserved.
439// Use of this source code is governed by a BSD-style
440// license that can be found in the LICENSE file\.
441`),
442 // Generated .pb.go files from main protobuf repo.
443 regexp.MustCompile(`^// Protocol Buffers - Google's data interchange format
444// Copyright \d\d\d\d Google Inc\. All rights reserved\.
445`),
446}
447
Damien Neil3a185602020-02-21 09:16:19 -0800448func mustHaveCopyrightHeader(t *testing.T, files []string) {
449 var bad []string
450File:
451 for _, file := range files {
Damien Neil3a185602020-02-21 09:16:19 -0800452 b, err := ioutil.ReadFile(file)
453 if err != nil {
454 t.Fatal(err)
455 }
456 for _, re := range copyrightRegex {
457 if loc := re.FindIndex(b); loc != nil && loc[0] == 0 {
458 continue File
459 }
460 }
461 bad = append(bad, file)
462 }
463 if len(bad) > 0 {
464 t.Fatalf("files with missing/bad copyright headers:\n %v", strings.Join(bad, "\n "))
465 }
466}
467
Joe Tsai7164af52019-08-07 19:27:43 -0700468type command struct {
469 Dir string
470 Env []string
471}
472
473func (c command) mustRun(t *testing.T, args ...string) string {
Joe Tsai707894e2019-03-01 12:50:52 -0800474 t.Helper()
475 stdout := new(bytes.Buffer)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700476 stderr := new(bytes.Buffer)
Joe Tsai707894e2019-03-01 12:50:52 -0800477 cmd := exec.Command(args[0], args[1:]...)
Joe Tsai7164af52019-08-07 19:27:43 -0700478 cmd.Dir = "."
479 if c.Dir != "" {
480 cmd.Dir = c.Dir
481 }
482 cmd.Env = os.Environ()
483 if c.Env != nil {
484 cmd.Env = c.Env
485 }
486 cmd.Env = append(cmd.Env, "PWD="+cmd.Dir)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700487 cmd.Stdout = stdout
488 cmd.Stderr = stderr
Joe Tsai707894e2019-03-01 12:50:52 -0800489 if err := cmd.Run(); err != nil {
Herbie Ong4630b3d2019-03-19 16:42:01 -0700490 t.Fatalf("executing (%v): %v\n%s%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
Joe Tsai707894e2019-03-01 12:50:52 -0800491 }
492 return stdout.String()
493}
Damien Neila80229e2019-06-20 12:53:48 -0700494
Joe Tsai7164af52019-08-07 19:27:43 -0700495func mustRunCommand(t *testing.T, args ...string) string {
496 t.Helper()
497 return command{}.mustRun(t, args...)
498}