blob: 980d5deee180a42b1c433feed9189ab0dec63e75 [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{
44 "darwin/386": "05ccb332a0c5ba812af165b0e69ffe317cb3e8bb10b0f4b4c4eaaf956ba9a50b",
45 "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
Joe Tsaif3987842019-03-02 13:35:17 -0800184 // Travis-CI has a hard-coded timeout where it kills the test after
185 // 10 minutes of a lack of activity on stdout.
186 // We work around this restriction by periodically printing the timestamp.
187 ticker := time.NewTicker(5 * time.Minute)
188 done := make(chan struct{})
189 go func() {
190 now := time.Now()
191 for {
192 select {
193 case t := <-ticker.C:
194 fmt.Printf("\tt=%0.fmin\n", t.Sub(now).Minutes())
195 case <-done:
196 return
197 }
198 }
199 }()
200 defer close(done)
201 defer ticker.Stop()
202
Joe Tsai707894e2019-03-01 12:50:52 -0800203 // Delete the current directory if non-empty,
204 // which only occurs if a dependency failed to initialize properly.
205 var workingDir string
206 defer func() {
207 if workingDir != "" {
208 os.RemoveAll(workingDir) // best-effort
209 }
210 }()
211
212 // Delete other sub-directories that are no longer relevant.
213 defer func() {
Joe Tsaif75a3382019-12-19 17:42:41 -0800214 subDirs := map[string]bool{"bin": true, "gopath": true}
Joe Tsai707894e2019-03-01 12:50:52 -0800215 subDirs["protobuf-"+protobufVersion] = true
216 for _, v := range golangVersions {
217 subDirs["go"+v] = true
218 }
Joe Tsai707894e2019-03-01 12:50:52 -0800219
Joe Tsai9e88bc02019-03-12 01:30:40 -0700220 now := time.Now()
Joe Tsai707894e2019-03-01 12:50:52 -0800221 fis, _ := ioutil.ReadDir(testDir)
222 for _, fi := range fis {
Joe Tsai9e88bc02019-03-12 01:30:40 -0700223 if subDirs[fi.Name()] {
224 os.Chtimes(filepath.Join(testDir, fi.Name()), now, now) // best-effort
225 continue
Joe Tsai707894e2019-03-01 12:50:52 -0800226 }
Joe Tsai9e88bc02019-03-12 01:30:40 -0700227 if now.Sub(fi.ModTime()) < purgeTimeout {
228 continue
229 }
230 fmt.Printf("delete %v\n", fi.Name())
231 os.RemoveAll(filepath.Join(testDir, fi.Name())) // best-effort
Joe Tsai707894e2019-03-01 12:50:52 -0800232 }
233 }()
234
235 // The bin directory contains symlinks to each tool by version.
236 // It is safe to delete this directory and run the test script from scratch.
237 binPath := filepath.Join(testDir, "bin")
238 check(os.RemoveAll(binPath))
239 check(os.Mkdir(binPath, 0775))
240 check(os.Setenv("PATH", binPath+":"+os.Getenv("PATH")))
241 registerBinary := func(name, path string) {
242 check(os.Symlink(path, filepath.Join(binPath, name)))
243 }
244
245 // Download and build the protobuf toolchain.
246 // We avoid downloading the pre-compiled binaries since they do not contain
247 // the conformance test runner.
248 workingDir = filepath.Join(testDir, "protobuf-"+protobufVersion)
Herbie Ongd64dceb2019-04-25 01:19:57 -0700249 protobufPath = workingDir
250 if _, err := os.Stat(protobufPath); err != nil {
251 fmt.Printf("download %v\n", filepath.Base(protobufPath))
Joe Tsai387873d2020-04-28 14:44:38 -0700252 if isCommit := strings.Trim(protobufVersion, "0123456789abcdef") == ""; isCommit {
253 command{Dir: testDir}.mustRun(t, "git", "clone", "https://github.com/protocolbuffers/protobuf", "protobuf-"+protobufVersion)
254 command{Dir: protobufPath}.mustRun(t, "git", "checkout", protobufVersion)
255 } else {
256 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 -0800257 downloadArchive(check, protobufPath, url, "protobuf-"+protobufVersion, protobufSHA256)
Joe Tsai387873d2020-04-28 14:44:38 -0700258 }
Joe Tsai707894e2019-03-01 12:50:52 -0800259
Herbie Ongd64dceb2019-04-25 01:19:57 -0700260 fmt.Printf("build %v\n", filepath.Base(protobufPath))
Joe Tsai7164af52019-08-07 19:27:43 -0700261 command{Dir: protobufPath}.mustRun(t, "./autogen.sh")
262 command{Dir: protobufPath}.mustRun(t, "./configure")
263 command{Dir: protobufPath}.mustRun(t, "make")
264 command{Dir: filepath.Join(protobufPath, "conformance")}.mustRun(t, "make")
Joe Tsai707894e2019-03-01 12:50:52 -0800265 }
Herbie Ongd64dceb2019-04-25 01:19:57 -0700266 check(os.Setenv("PROTOBUF_ROOT", protobufPath)) // for generate-protos
267 registerBinary("conform-test-runner", filepath.Join(protobufPath, "conformance", "conformance-test-runner"))
268 registerBinary("protoc", filepath.Join(protobufPath, "src", "protoc"))
Joe Tsai707894e2019-03-01 12:50:52 -0800269 workingDir = ""
270
271 // Download each Go toolchain version.
272 for _, v := range golangVersions {
273 workingDir = filepath.Join(testDir, "go"+v)
274 if _, err := os.Stat(workingDir); err != nil {
275 fmt.Printf("download %v\n", filepath.Base(workingDir))
276 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 -0800277 downloadArchive(check, workingDir, url, "go", "") // skip SHA256 check as we fetch over https from a trusted domain
Joe Tsai707894e2019-03-01 12:50:52 -0800278 }
279 registerBinary("go"+v, filepath.Join(workingDir, "bin", "go"))
280 }
281 registerBinary("go", filepath.Join(testDir, "go"+golangLatest, "bin", "go"))
282 registerBinary("gofmt", filepath.Join(testDir, "go"+golangLatest, "bin", "gofmt"))
283 workingDir = ""
284
Joe Tsai8de66752019-12-19 16:38:52 -0800285 // Download the staticcheck tool.
286 workingDir = filepath.Join(testDir, "staticcheck-"+staticcheckVersion)
287 if _, err := os.Stat(workingDir); err != nil {
288 fmt.Printf("download %v\n", filepath.Base(workingDir))
289 url := fmt.Sprintf("https://github.com/dominikh/go-tools/releases/download/%v/staticcheck_%v_%v.tar.gz", staticcheckVersion, runtime.GOOS, runtime.GOARCH)
290 downloadArchive(check, workingDir, url, "staticcheck", staticcheckSHA256s[runtime.GOOS+"/"+runtime.GOARCH])
291 }
292 registerBinary("staticcheck", filepath.Join(workingDir, "staticcheck"))
293 workingDir = ""
294
Joe Tsai707894e2019-03-01 12:50:52 -0800295 // Travis-CI sets GOROOT, which confuses invocations of the Go toolchain.
296 // Explicitly clear GOROOT, so each toolchain uses their default GOROOT.
297 check(os.Unsetenv("GOROOT"))
298
Joe Tsai6a2180f2019-07-11 16:34:17 -0700299 // Set a cache directory outside the test directory.
300 check(os.Setenv("GOCACHE", filepath.Join(repoRoot, ".gocache")))
Joe Tsai707894e2019-03-01 12:50:52 -0800301
302 // Setup GOPATH for pre-module support (i.e., go1.10 and earlier).
303 goPath = filepath.Join(testDir, "gopath")
Joe Tsai7164af52019-08-07 19:27:43 -0700304 modulePath = strings.TrimSpace(command{Dir: testDir}.mustRun(t, "go", "list", "-m", "-f", "{{.Path}}"))
Joe Tsai707894e2019-03-01 12:50:52 -0800305 check(os.RemoveAll(filepath.Join(goPath, "src")))
306 check(os.MkdirAll(filepath.Join(goPath, "src", filepath.Dir(modulePath)), 0775))
307 check(os.Symlink(repoRoot, filepath.Join(goPath, "src", modulePath)))
Joe Tsai7164af52019-08-07 19:27:43 -0700308 command{Dir: repoRoot}.mustRun(t, "go", "mod", "tidy")
309 command{Dir: repoRoot}.mustRun(t, "go", "mod", "vendor")
Joe Tsai707894e2019-03-01 12:50:52 -0800310 check(os.Setenv("GOPATH", goPath))
311}
312
Damien Neila80229e2019-06-20 12:53:48 -0700313func downloadFile(check func(error), dstPath, srcURL string) {
314 resp, err := http.Get(srcURL)
315 check(err)
316 defer resp.Body.Close()
317
318 check(os.MkdirAll(filepath.Dir(dstPath), 0775))
319 f, err := os.Create(dstPath)
320 check(err)
321
322 _, err = io.Copy(f, resp.Body)
323 check(err)
324}
325
Joe Tsai8de66752019-12-19 16:38:52 -0800326func downloadArchive(check func(error), dstPath, srcURL, skipPrefix, wantSHA256 string) {
Joe Tsai707894e2019-03-01 12:50:52 -0800327 check(os.RemoveAll(dstPath))
328
329 resp, err := http.Get(srcURL)
330 check(err)
331 defer resp.Body.Close()
332
Joe Tsai8de66752019-12-19 16:38:52 -0800333 var r io.Reader = resp.Body
334 if wantSHA256 != "" {
335 b, err := ioutil.ReadAll(resp.Body)
336 check(err)
337 r = bytes.NewReader(b)
338
339 if gotSHA256 := fmt.Sprintf("%x", sha256.Sum256(b)); gotSHA256 != wantSHA256 {
340 check(fmt.Errorf("checksum validation error:\ngot %v\nwant %v", gotSHA256, wantSHA256))
341 }
342 }
343
344 zr, err := gzip.NewReader(r)
Joe Tsai707894e2019-03-01 12:50:52 -0800345 check(err)
346
347 tr := tar.NewReader(zr)
348 for {
349 h, err := tr.Next()
350 if err == io.EOF {
351 return
352 }
353 check(err)
354
Joe Tsaif3987842019-03-02 13:35:17 -0800355 // Skip directories or files outside the prefix directory.
356 if len(skipPrefix) > 0 {
357 if !strings.HasPrefix(h.Name, skipPrefix) {
358 continue
359 }
360 if len(h.Name) > len(skipPrefix) && h.Name[len(skipPrefix)] != '/' {
361 continue
362 }
363 }
364
365 path := strings.TrimPrefix(strings.TrimPrefix(h.Name, skipPrefix), "/")
Joe Tsai707894e2019-03-01 12:50:52 -0800366 path = filepath.Join(dstPath, filepath.FromSlash(path))
367 mode := os.FileMode(h.Mode & 0777)
368 switch h.Typeflag {
369 case tar.TypeReg:
370 b, err := ioutil.ReadAll(tr)
371 check(err)
372 check(ioutil.WriteFile(path, b, mode))
373 case tar.TypeDir:
374 check(os.Mkdir(path, mode))
375 }
376 }
377}
378
Joe Tsai4f3de442019-08-07 19:33:51 -0700379func mustHandleFlags(t *testing.T) {
380 if *regenerate {
381 t.Run("Generate", func(t *testing.T) {
382 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-types", "-execute"))
383 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-protos", "-execute"))
384 files := strings.Split(strings.TrimSpace(mustRunCommand(t, "git", "ls-files", "*.go")), "\n")
385 mustRunCommand(t, append([]string{"gofmt", "-w"}, files...)...)
386 })
387 }
388 if *buildRelease {
389 t.Run("BuildRelease", func(t *testing.T) {
Joe Tsai4ab2bc92020-03-10 17:38:07 -0700390 v := version.String()
Joe Tsai4f3de442019-08-07 19:33:51 -0700391 for _, goos := range []string{"linux", "darwin", "windows"} {
392 for _, goarch := range []string{"386", "amd64"} {
393 binPath := filepath.Join("bin", fmt.Sprintf("protoc-gen-go.%v.%v.%v", v, goos, goarch))
394
395 // Build the binary.
396 cmd := command{Env: append(os.Environ(), "GOOS="+goos, "GOARCH="+goarch)}
Joe Tsai576cfb32019-09-04 22:50:42 -0700397 cmd.mustRun(t, "go", "build", "-trimpath", "-ldflags", "-s -w -buildid=", "-o", binPath, "./cmd/protoc-gen-go")
Joe Tsai4f3de442019-08-07 19:33:51 -0700398
399 // Archive and compress the binary.
400 in, err := ioutil.ReadFile(binPath)
401 if err != nil {
402 t.Fatal(err)
403 }
404 out := new(bytes.Buffer)
405 gz, _ := gzip.NewWriterLevel(out, gzip.BestCompression)
406 gz.Comment = fmt.Sprintf("protoc-gen-go VERSION=%v GOOS=%v GOARCH=%v", v, goos, goarch)
407 tw := tar.NewWriter(gz)
408 tw.WriteHeader(&tar.Header{
409 Name: "protoc-gen-go",
410 Mode: int64(0775),
411 Size: int64(len(in)),
412 })
413 tw.Write(in)
414 tw.Close()
415 gz.Close()
416 if err := ioutil.WriteFile(binPath+".tar.gz", out.Bytes(), 0664); err != nil {
417 t.Fatal(err)
418 }
419 }
420 }
421 })
422 }
423 if *regenerate || *buildRelease {
424 t.SkipNow()
425 }
426}
427
Damien Neil3a185602020-02-21 09:16:19 -0800428var copyrightRegex = []*regexp.Regexp{
429 regexp.MustCompile(`^// Copyright \d\d\d\d The Go Authors\. All rights reserved.
430// Use of this source code is governed by a BSD-style
431// license that can be found in the LICENSE file\.
432`),
433 // Generated .pb.go files from main protobuf repo.
434 regexp.MustCompile(`^// Protocol Buffers - Google's data interchange format
435// Copyright \d\d\d\d Google Inc\. All rights reserved\.
436`),
437}
438
Damien Neil3a185602020-02-21 09:16:19 -0800439func mustHaveCopyrightHeader(t *testing.T, files []string) {
440 var bad []string
441File:
442 for _, file := range files {
Damien Neil3a185602020-02-21 09:16:19 -0800443 b, err := ioutil.ReadFile(file)
444 if err != nil {
445 t.Fatal(err)
446 }
447 for _, re := range copyrightRegex {
448 if loc := re.FindIndex(b); loc != nil && loc[0] == 0 {
449 continue File
450 }
451 }
452 bad = append(bad, file)
453 }
454 if len(bad) > 0 {
455 t.Fatalf("files with missing/bad copyright headers:\n %v", strings.Join(bad, "\n "))
456 }
457}
458
Joe Tsai7164af52019-08-07 19:27:43 -0700459type command struct {
460 Dir string
461 Env []string
462}
463
464func (c command) mustRun(t *testing.T, args ...string) string {
Joe Tsai707894e2019-03-01 12:50:52 -0800465 t.Helper()
466 stdout := new(bytes.Buffer)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700467 stderr := new(bytes.Buffer)
Joe Tsai707894e2019-03-01 12:50:52 -0800468 cmd := exec.Command(args[0], args[1:]...)
Joe Tsai7164af52019-08-07 19:27:43 -0700469 cmd.Dir = "."
470 if c.Dir != "" {
471 cmd.Dir = c.Dir
472 }
473 cmd.Env = os.Environ()
474 if c.Env != nil {
475 cmd.Env = c.Env
476 }
477 cmd.Env = append(cmd.Env, "PWD="+cmd.Dir)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700478 cmd.Stdout = stdout
479 cmd.Stderr = stderr
Joe Tsai707894e2019-03-01 12:50:52 -0800480 if err := cmd.Run(); err != nil {
Herbie Ong4630b3d2019-03-19 16:42:01 -0700481 t.Fatalf("executing (%v): %v\n%s%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
Joe Tsai707894e2019-03-01 12:50:52 -0800482 }
483 return stdout.String()
484}
Damien Neila80229e2019-06-20 12:53:48 -0700485
Joe Tsai7164af52019-08-07 19:27:43 -0700486func mustRunCommand(t *testing.T, args ...string) string {
487 t.Helper()
488 return command{}.mustRun(t, args...)
489}