blob: 3d09356eb69b005af1d6eda560416bcafd9a497b [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
205 defer func() {
206 if workingDir != "" {
207 os.RemoveAll(workingDir) // best-effort
208 }
209 }()
210
211 // Delete other sub-directories that are no longer relevant.
212 defer func() {
Joe Tsaif75a3382019-12-19 17:42:41 -0800213 subDirs := map[string]bool{"bin": true, "gopath": true}
Joe Tsai707894e2019-03-01 12:50:52 -0800214 subDirs["protobuf-"+protobufVersion] = true
215 for _, v := range golangVersions {
216 subDirs["go"+v] = true
217 }
Joe Tsai707894e2019-03-01 12:50:52 -0800218
Joe Tsai9e88bc02019-03-12 01:30:40 -0700219 now := time.Now()
Joe Tsai707894e2019-03-01 12:50:52 -0800220 fis, _ := ioutil.ReadDir(testDir)
221 for _, fi := range fis {
Joe Tsai9e88bc02019-03-12 01:30:40 -0700222 if subDirs[fi.Name()] {
223 os.Chtimes(filepath.Join(testDir, fi.Name()), now, now) // best-effort
224 continue
Joe Tsai707894e2019-03-01 12:50:52 -0800225 }
Joe Tsai9e88bc02019-03-12 01:30:40 -0700226 if now.Sub(fi.ModTime()) < purgeTimeout {
227 continue
228 }
229 fmt.Printf("delete %v\n", fi.Name())
230 os.RemoveAll(filepath.Join(testDir, fi.Name())) // best-effort
Joe Tsai707894e2019-03-01 12:50:52 -0800231 }
232 }()
233
234 // The bin directory contains symlinks to each tool by version.
235 // It is safe to delete this directory and run the test script from scratch.
236 binPath := filepath.Join(testDir, "bin")
237 check(os.RemoveAll(binPath))
238 check(os.Mkdir(binPath, 0775))
239 check(os.Setenv("PATH", binPath+":"+os.Getenv("PATH")))
240 registerBinary := func(name, path string) {
241 check(os.Symlink(path, filepath.Join(binPath, name)))
242 }
243
244 // Download and build the protobuf toolchain.
245 // We avoid downloading the pre-compiled binaries since they do not contain
246 // the conformance test runner.
247 workingDir = filepath.Join(testDir, "protobuf-"+protobufVersion)
Herbie Ongd64dceb2019-04-25 01:19:57 -0700248 protobufPath = workingDir
249 if _, err := os.Stat(protobufPath); err != nil {
250 fmt.Printf("download %v\n", filepath.Base(protobufPath))
Joe Tsai387873d2020-04-28 14:44:38 -0700251 if isCommit := strings.Trim(protobufVersion, "0123456789abcdef") == ""; isCommit {
252 command{Dir: testDir}.mustRun(t, "git", "clone", "https://github.com/protocolbuffers/protobuf", "protobuf-"+protobufVersion)
253 command{Dir: protobufPath}.mustRun(t, "git", "checkout", protobufVersion)
254 } else {
255 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 -0800256 downloadArchive(check, protobufPath, url, "protobuf-"+protobufVersion, protobufSHA256)
Joe Tsai387873d2020-04-28 14:44:38 -0700257 }
Joe Tsai707894e2019-03-01 12:50:52 -0800258
Herbie Ongd64dceb2019-04-25 01:19:57 -0700259 fmt.Printf("build %v\n", filepath.Base(protobufPath))
Joe Tsai7164af52019-08-07 19:27:43 -0700260 command{Dir: protobufPath}.mustRun(t, "./autogen.sh")
261 command{Dir: protobufPath}.mustRun(t, "./configure")
262 command{Dir: protobufPath}.mustRun(t, "make")
263 command{Dir: filepath.Join(protobufPath, "conformance")}.mustRun(t, "make")
Joe Tsai707894e2019-03-01 12:50:52 -0800264 }
Herbie Ongd64dceb2019-04-25 01:19:57 -0700265 check(os.Setenv("PROTOBUF_ROOT", protobufPath)) // for generate-protos
266 registerBinary("conform-test-runner", filepath.Join(protobufPath, "conformance", "conformance-test-runner"))
267 registerBinary("protoc", filepath.Join(protobufPath, "src", "protoc"))
Joe Tsai707894e2019-03-01 12:50:52 -0800268 workingDir = ""
269
270 // Download each Go toolchain version.
271 for _, v := range golangVersions {
272 workingDir = filepath.Join(testDir, "go"+v)
273 if _, err := os.Stat(workingDir); err != nil {
274 fmt.Printf("download %v\n", filepath.Base(workingDir))
275 url := fmt.Sprintf("https://dl.google.com/go/go%v.%v-%v.tar.gz", v, runtime.GOOS, runtime.GOARCH)
Joe Tsai8de66752019-12-19 16:38:52 -0800276 downloadArchive(check, workingDir, url, "go", "") // skip SHA256 check as we fetch over https from a trusted domain
Joe Tsai707894e2019-03-01 12:50:52 -0800277 }
278 registerBinary("go"+v, filepath.Join(workingDir, "bin", "go"))
279 }
280 registerBinary("go", filepath.Join(testDir, "go"+golangLatest, "bin", "go"))
281 registerBinary("gofmt", filepath.Join(testDir, "go"+golangLatest, "bin", "gofmt"))
282 workingDir = ""
283
Joe Tsai8de66752019-12-19 16:38:52 -0800284 // Download the staticcheck tool.
285 workingDir = filepath.Join(testDir, "staticcheck-"+staticcheckVersion)
286 if _, err := os.Stat(workingDir); err != nil {
287 fmt.Printf("download %v\n", filepath.Base(workingDir))
288 url := fmt.Sprintf("https://github.com/dominikh/go-tools/releases/download/%v/staticcheck_%v_%v.tar.gz", staticcheckVersion, runtime.GOOS, runtime.GOARCH)
289 downloadArchive(check, workingDir, url, "staticcheck", staticcheckSHA256s[runtime.GOOS+"/"+runtime.GOARCH])
290 }
291 registerBinary("staticcheck", filepath.Join(workingDir, "staticcheck"))
292 workingDir = ""
293
Joe Tsai707894e2019-03-01 12:50:52 -0800294 // Travis-CI sets GOROOT, which confuses invocations of the Go toolchain.
295 // Explicitly clear GOROOT, so each toolchain uses their default GOROOT.
296 check(os.Unsetenv("GOROOT"))
297
Joe Tsai6a2180f2019-07-11 16:34:17 -0700298 // Set a cache directory outside the test directory.
299 check(os.Setenv("GOCACHE", filepath.Join(repoRoot, ".gocache")))
Joe Tsai707894e2019-03-01 12:50:52 -0800300
301 // Setup GOPATH for pre-module support (i.e., go1.10 and earlier).
302 goPath = filepath.Join(testDir, "gopath")
Joe Tsai7164af52019-08-07 19:27:43 -0700303 modulePath = strings.TrimSpace(command{Dir: testDir}.mustRun(t, "go", "list", "-m", "-f", "{{.Path}}"))
Joe Tsai707894e2019-03-01 12:50:52 -0800304 check(os.RemoveAll(filepath.Join(goPath, "src")))
305 check(os.MkdirAll(filepath.Join(goPath, "src", filepath.Dir(modulePath)), 0775))
306 check(os.Symlink(repoRoot, filepath.Join(goPath, "src", modulePath)))
Joe Tsai7164af52019-08-07 19:27:43 -0700307 command{Dir: repoRoot}.mustRun(t, "go", "mod", "tidy")
308 command{Dir: repoRoot}.mustRun(t, "go", "mod", "vendor")
Joe Tsai707894e2019-03-01 12:50:52 -0800309 check(os.Setenv("GOPATH", goPath))
310}
311
Damien Neila80229e2019-06-20 12:53:48 -0700312func downloadFile(check func(error), dstPath, srcURL string) {
313 resp, err := http.Get(srcURL)
314 check(err)
315 defer resp.Body.Close()
316
317 check(os.MkdirAll(filepath.Dir(dstPath), 0775))
318 f, err := os.Create(dstPath)
319 check(err)
320
321 _, err = io.Copy(f, resp.Body)
322 check(err)
323}
324
Joe Tsai8de66752019-12-19 16:38:52 -0800325func downloadArchive(check func(error), dstPath, srcURL, skipPrefix, wantSHA256 string) {
Joe Tsai707894e2019-03-01 12:50:52 -0800326 check(os.RemoveAll(dstPath))
327
328 resp, err := http.Get(srcURL)
329 check(err)
330 defer resp.Body.Close()
331
Joe Tsai8de66752019-12-19 16:38:52 -0800332 var r io.Reader = resp.Body
333 if wantSHA256 != "" {
334 b, err := ioutil.ReadAll(resp.Body)
335 check(err)
336 r = bytes.NewReader(b)
337
338 if gotSHA256 := fmt.Sprintf("%x", sha256.Sum256(b)); gotSHA256 != wantSHA256 {
339 check(fmt.Errorf("checksum validation error:\ngot %v\nwant %v", gotSHA256, wantSHA256))
340 }
341 }
342
343 zr, err := gzip.NewReader(r)
Joe Tsai707894e2019-03-01 12:50:52 -0800344 check(err)
345
346 tr := tar.NewReader(zr)
347 for {
348 h, err := tr.Next()
349 if err == io.EOF {
350 return
351 }
352 check(err)
353
Joe Tsaif3987842019-03-02 13:35:17 -0800354 // Skip directories or files outside the prefix directory.
355 if len(skipPrefix) > 0 {
356 if !strings.HasPrefix(h.Name, skipPrefix) {
357 continue
358 }
359 if len(h.Name) > len(skipPrefix) && h.Name[len(skipPrefix)] != '/' {
360 continue
361 }
362 }
363
364 path := strings.TrimPrefix(strings.TrimPrefix(h.Name, skipPrefix), "/")
Joe Tsai707894e2019-03-01 12:50:52 -0800365 path = filepath.Join(dstPath, filepath.FromSlash(path))
366 mode := os.FileMode(h.Mode & 0777)
367 switch h.Typeflag {
368 case tar.TypeReg:
369 b, err := ioutil.ReadAll(tr)
370 check(err)
371 check(ioutil.WriteFile(path, b, mode))
372 case tar.TypeDir:
373 check(os.Mkdir(path, mode))
374 }
375 }
376}
377
Joe Tsai4f3de442019-08-07 19:33:51 -0700378func mustHandleFlags(t *testing.T) {
379 if *regenerate {
380 t.Run("Generate", func(t *testing.T) {
381 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-types", "-execute"))
382 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-protos", "-execute"))
383 files := strings.Split(strings.TrimSpace(mustRunCommand(t, "git", "ls-files", "*.go")), "\n")
384 mustRunCommand(t, append([]string{"gofmt", "-w"}, files...)...)
385 })
386 }
387 if *buildRelease {
388 t.Run("BuildRelease", func(t *testing.T) {
Joe Tsai4ab2bc92020-03-10 17:38:07 -0700389 v := version.String()
Joe Tsai4f3de442019-08-07 19:33:51 -0700390 for _, goos := range []string{"linux", "darwin", "windows"} {
391 for _, goarch := range []string{"386", "amd64"} {
Joe Tsai5ebc0b42020-09-08 11:32:36 -0700392 // Avoid Darwin since 10.15 dropped support for i386.
393 if goos == "darwin" && goarch == "386" {
394 continue
395 }
396
Joe Tsai4f3de442019-08-07 19:33:51 -0700397 binPath := filepath.Join("bin", fmt.Sprintf("protoc-gen-go.%v.%v.%v", v, goos, goarch))
398
399 // Build the binary.
400 cmd := command{Env: append(os.Environ(), "GOOS="+goos, "GOARCH="+goarch)}
Joe Tsai576cfb32019-09-04 22:50:42 -0700401 cmd.mustRun(t, "go", "build", "-trimpath", "-ldflags", "-s -w -buildid=", "-o", binPath, "./cmd/protoc-gen-go")
Joe Tsai4f3de442019-08-07 19:33:51 -0700402
403 // Archive and compress the binary.
404 in, err := ioutil.ReadFile(binPath)
405 if err != nil {
406 t.Fatal(err)
407 }
408 out := new(bytes.Buffer)
409 gz, _ := gzip.NewWriterLevel(out, gzip.BestCompression)
410 gz.Comment = fmt.Sprintf("protoc-gen-go VERSION=%v GOOS=%v GOARCH=%v", v, goos, goarch)
411 tw := tar.NewWriter(gz)
412 tw.WriteHeader(&tar.Header{
413 Name: "protoc-gen-go",
414 Mode: int64(0775),
415 Size: int64(len(in)),
416 })
417 tw.Write(in)
418 tw.Close()
419 gz.Close()
420 if err := ioutil.WriteFile(binPath+".tar.gz", out.Bytes(), 0664); err != nil {
421 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}