blob: 54ad30fc1d52e38d0f3796ab5ffb412f25aad4a8 [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 Tsaic0ad1992020-06-18 09:36:06 -070039 golangVersions = []string{"1.9.7", "1.10.8", "1.11.13", "1.12.17", "1.13.12", "1.14.4"}
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
104 runGo := func(label, workDir string, args ...string) {
105 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 Tsai7164af52019-08-07 19:27:43 -0700112 command{Dir: workDir}.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)
118 runGo("Normal", workDir, "go", "test", "-race", "./...")
119 runGo("PureGo", workDir, "go", "test", "-race", "-tags", "purego", "./...")
120 runGo("Reflect", workDir, "go", "test", "-race", "-tags", "protoreflect", "./...")
121 if goVersion == golangLatest {
Joe Tsai1799d112019-08-08 13:31:59 -0700122 runGo("ProtoLegacy", workDir, "go", "test", "-race", "-tags", "protolegacy", "./...")
Joe Tsai62200db2019-07-11 17:34:10 -0700123 runGo("ProtocGenGo", "cmd/protoc-gen-go/testdata", "go", "test")
Joe Tsaidd271b62019-08-16 01:09:33 -0700124 runGo("Conformance", "internal/conformance", "go", "test", "-execute")
Joe Tsai62200db2019-07-11 17:34:10 -0700125 }
Joe Tsai707894e2019-03-01 12:50:52 -0800126 }
Joe Tsai62200db2019-07-11 17:34:10 -0700127 wg.Wait()
Joe Tsai707894e2019-03-01 12:50:52 -0800128
Joe Tsai8de66752019-12-19 16:38:52 -0800129 t.Run("GoStaticCheck", func(t *testing.T) {
130 checks := []string{
131 "all", // start with all checks enabled
132 "-SA1019", // disable deprecated usage check
133 "-S*", // disable code simplication checks
134 "-ST*", // disable coding style checks
135 "-U*", // disable unused declaration checks
136 }
137 out := mustRunCommand(t, "staticcheck", "-checks="+strings.Join(checks, ","), "-fail=none", "./...")
138
139 // Filter out findings from certain paths.
140 var findings []string
141 for _, finding := range strings.Split(strings.TrimSpace(out), "\n") {
142 switch {
143 case strings.HasPrefix(finding, "internal/testprotos/legacy/"):
144 default:
145 findings = append(findings, finding)
146 }
147 }
148 if len(findings) > 0 {
149 t.Fatalf("staticcheck findings:\n%v", strings.Join(findings, "\n"))
150 }
151 })
Joe Tsai707894e2019-03-01 12:50:52 -0800152 t.Run("CommittedGitChanges", func(t *testing.T) {
Joe Tsaif75a3382019-12-19 17:42:41 -0800153 if strings.TrimSpace(gitDiff) != "" {
Damien Neil4d8936d2020-02-21 10:32:56 -0800154 t.Fatalf("uncommitted changes")
Joe Tsai707894e2019-03-01 12:50:52 -0800155 }
156 })
157 t.Run("TrackedGitFiles", func(t *testing.T) {
Joe Tsaif75a3382019-12-19 17:42:41 -0800158 if strings.TrimSpace(gitUntracked) != "" {
Damien Neil4d8936d2020-02-21 10:32:56 -0800159 t.Fatalf("untracked files")
Joe Tsai707894e2019-03-01 12:50:52 -0800160 }
161 })
162}
163
164func mustInitDeps(t *testing.T) {
165 check := func(err error) {
166 t.Helper()
167 if err != nil {
168 t.Fatal(err)
169 }
170 }
171
172 // Determine the directory to place the test directory.
173 repoRoot, err := os.Getwd()
174 check(err)
175 testDir := filepath.Join(repoRoot, ".cache")
176 check(os.MkdirAll(testDir, 0775))
177
Joe Tsaif3987842019-03-02 13:35:17 -0800178 // Travis-CI has a hard-coded timeout where it kills the test after
179 // 10 minutes of a lack of activity on stdout.
180 // We work around this restriction by periodically printing the timestamp.
181 ticker := time.NewTicker(5 * time.Minute)
182 done := make(chan struct{})
183 go func() {
184 now := time.Now()
185 for {
186 select {
187 case t := <-ticker.C:
188 fmt.Printf("\tt=%0.fmin\n", t.Sub(now).Minutes())
189 case <-done:
190 return
191 }
192 }
193 }()
194 defer close(done)
195 defer ticker.Stop()
196
Joe Tsai707894e2019-03-01 12:50:52 -0800197 // Delete the current directory if non-empty,
198 // which only occurs if a dependency failed to initialize properly.
199 var workingDir string
200 defer func() {
201 if workingDir != "" {
202 os.RemoveAll(workingDir) // best-effort
203 }
204 }()
205
206 // Delete other sub-directories that are no longer relevant.
207 defer func() {
Joe Tsaif75a3382019-12-19 17:42:41 -0800208 subDirs := map[string]bool{"bin": true, "gopath": true}
Joe Tsai707894e2019-03-01 12:50:52 -0800209 subDirs["protobuf-"+protobufVersion] = true
210 for _, v := range golangVersions {
211 subDirs["go"+v] = true
212 }
Joe Tsai707894e2019-03-01 12:50:52 -0800213
Joe Tsai9e88bc02019-03-12 01:30:40 -0700214 now := time.Now()
Joe Tsai707894e2019-03-01 12:50:52 -0800215 fis, _ := ioutil.ReadDir(testDir)
216 for _, fi := range fis {
Joe Tsai9e88bc02019-03-12 01:30:40 -0700217 if subDirs[fi.Name()] {
218 os.Chtimes(filepath.Join(testDir, fi.Name()), now, now) // best-effort
219 continue
Joe Tsai707894e2019-03-01 12:50:52 -0800220 }
Joe Tsai9e88bc02019-03-12 01:30:40 -0700221 if now.Sub(fi.ModTime()) < purgeTimeout {
222 continue
223 }
224 fmt.Printf("delete %v\n", fi.Name())
225 os.RemoveAll(filepath.Join(testDir, fi.Name())) // best-effort
Joe Tsai707894e2019-03-01 12:50:52 -0800226 }
227 }()
228
229 // The bin directory contains symlinks to each tool by version.
230 // It is safe to delete this directory and run the test script from scratch.
231 binPath := filepath.Join(testDir, "bin")
232 check(os.RemoveAll(binPath))
233 check(os.Mkdir(binPath, 0775))
234 check(os.Setenv("PATH", binPath+":"+os.Getenv("PATH")))
235 registerBinary := func(name, path string) {
236 check(os.Symlink(path, filepath.Join(binPath, name)))
237 }
238
239 // Download and build the protobuf toolchain.
240 // We avoid downloading the pre-compiled binaries since they do not contain
241 // the conformance test runner.
242 workingDir = filepath.Join(testDir, "protobuf-"+protobufVersion)
Herbie Ongd64dceb2019-04-25 01:19:57 -0700243 protobufPath = workingDir
244 if _, err := os.Stat(protobufPath); err != nil {
245 fmt.Printf("download %v\n", filepath.Base(protobufPath))
Joe Tsai387873d2020-04-28 14:44:38 -0700246 if isCommit := strings.Trim(protobufVersion, "0123456789abcdef") == ""; isCommit {
247 command{Dir: testDir}.mustRun(t, "git", "clone", "https://github.com/protocolbuffers/protobuf", "protobuf-"+protobufVersion)
248 command{Dir: protobufPath}.mustRun(t, "git", "checkout", protobufVersion)
249 } else {
250 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 -0800251 downloadArchive(check, protobufPath, url, "protobuf-"+protobufVersion, protobufSHA256)
Joe Tsai387873d2020-04-28 14:44:38 -0700252 }
Joe Tsai707894e2019-03-01 12:50:52 -0800253
Herbie Ongd64dceb2019-04-25 01:19:57 -0700254 fmt.Printf("build %v\n", filepath.Base(protobufPath))
Joe Tsai7164af52019-08-07 19:27:43 -0700255 command{Dir: protobufPath}.mustRun(t, "./autogen.sh")
256 command{Dir: protobufPath}.mustRun(t, "./configure")
257 command{Dir: protobufPath}.mustRun(t, "make")
258 command{Dir: filepath.Join(protobufPath, "conformance")}.mustRun(t, "make")
Joe Tsai707894e2019-03-01 12:50:52 -0800259 }
Herbie Ongd64dceb2019-04-25 01:19:57 -0700260 check(os.Setenv("PROTOBUF_ROOT", protobufPath)) // for generate-protos
261 registerBinary("conform-test-runner", filepath.Join(protobufPath, "conformance", "conformance-test-runner"))
262 registerBinary("protoc", filepath.Join(protobufPath, "src", "protoc"))
Joe Tsai707894e2019-03-01 12:50:52 -0800263 workingDir = ""
264
265 // Download each Go toolchain version.
266 for _, v := range golangVersions {
267 workingDir = filepath.Join(testDir, "go"+v)
268 if _, err := os.Stat(workingDir); err != nil {
269 fmt.Printf("download %v\n", filepath.Base(workingDir))
270 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 -0800271 downloadArchive(check, workingDir, url, "go", "") // skip SHA256 check as we fetch over https from a trusted domain
Joe Tsai707894e2019-03-01 12:50:52 -0800272 }
273 registerBinary("go"+v, filepath.Join(workingDir, "bin", "go"))
274 }
275 registerBinary("go", filepath.Join(testDir, "go"+golangLatest, "bin", "go"))
276 registerBinary("gofmt", filepath.Join(testDir, "go"+golangLatest, "bin", "gofmt"))
277 workingDir = ""
278
Joe Tsai8de66752019-12-19 16:38:52 -0800279 // Download the staticcheck tool.
280 workingDir = filepath.Join(testDir, "staticcheck-"+staticcheckVersion)
281 if _, err := os.Stat(workingDir); err != nil {
282 fmt.Printf("download %v\n", filepath.Base(workingDir))
283 url := fmt.Sprintf("https://github.com/dominikh/go-tools/releases/download/%v/staticcheck_%v_%v.tar.gz", staticcheckVersion, runtime.GOOS, runtime.GOARCH)
284 downloadArchive(check, workingDir, url, "staticcheck", staticcheckSHA256s[runtime.GOOS+"/"+runtime.GOARCH])
285 }
286 registerBinary("staticcheck", filepath.Join(workingDir, "staticcheck"))
287 workingDir = ""
288
Joe Tsai707894e2019-03-01 12:50:52 -0800289 // Travis-CI sets GOROOT, which confuses invocations of the Go toolchain.
290 // Explicitly clear GOROOT, so each toolchain uses their default GOROOT.
291 check(os.Unsetenv("GOROOT"))
292
Joe Tsai6a2180f2019-07-11 16:34:17 -0700293 // Set a cache directory outside the test directory.
294 check(os.Setenv("GOCACHE", filepath.Join(repoRoot, ".gocache")))
Joe Tsai707894e2019-03-01 12:50:52 -0800295
296 // Setup GOPATH for pre-module support (i.e., go1.10 and earlier).
297 goPath = filepath.Join(testDir, "gopath")
Joe Tsai7164af52019-08-07 19:27:43 -0700298 modulePath = strings.TrimSpace(command{Dir: testDir}.mustRun(t, "go", "list", "-m", "-f", "{{.Path}}"))
Joe Tsai707894e2019-03-01 12:50:52 -0800299 check(os.RemoveAll(filepath.Join(goPath, "src")))
300 check(os.MkdirAll(filepath.Join(goPath, "src", filepath.Dir(modulePath)), 0775))
301 check(os.Symlink(repoRoot, filepath.Join(goPath, "src", modulePath)))
Joe Tsai7164af52019-08-07 19:27:43 -0700302 command{Dir: repoRoot}.mustRun(t, "go", "mod", "tidy")
303 command{Dir: repoRoot}.mustRun(t, "go", "mod", "vendor")
Joe Tsai707894e2019-03-01 12:50:52 -0800304 check(os.Setenv("GOPATH", goPath))
305}
306
Damien Neila80229e2019-06-20 12:53:48 -0700307func downloadFile(check func(error), dstPath, srcURL string) {
308 resp, err := http.Get(srcURL)
309 check(err)
310 defer resp.Body.Close()
311
312 check(os.MkdirAll(filepath.Dir(dstPath), 0775))
313 f, err := os.Create(dstPath)
314 check(err)
315
316 _, err = io.Copy(f, resp.Body)
317 check(err)
318}
319
Joe Tsai8de66752019-12-19 16:38:52 -0800320func downloadArchive(check func(error), dstPath, srcURL, skipPrefix, wantSHA256 string) {
Joe Tsai707894e2019-03-01 12:50:52 -0800321 check(os.RemoveAll(dstPath))
322
323 resp, err := http.Get(srcURL)
324 check(err)
325 defer resp.Body.Close()
326
Joe Tsai8de66752019-12-19 16:38:52 -0800327 var r io.Reader = resp.Body
328 if wantSHA256 != "" {
329 b, err := ioutil.ReadAll(resp.Body)
330 check(err)
331 r = bytes.NewReader(b)
332
333 if gotSHA256 := fmt.Sprintf("%x", sha256.Sum256(b)); gotSHA256 != wantSHA256 {
334 check(fmt.Errorf("checksum validation error:\ngot %v\nwant %v", gotSHA256, wantSHA256))
335 }
336 }
337
338 zr, err := gzip.NewReader(r)
Joe Tsai707894e2019-03-01 12:50:52 -0800339 check(err)
340
341 tr := tar.NewReader(zr)
342 for {
343 h, err := tr.Next()
344 if err == io.EOF {
345 return
346 }
347 check(err)
348
Joe Tsaif3987842019-03-02 13:35:17 -0800349 // Skip directories or files outside the prefix directory.
350 if len(skipPrefix) > 0 {
351 if !strings.HasPrefix(h.Name, skipPrefix) {
352 continue
353 }
354 if len(h.Name) > len(skipPrefix) && h.Name[len(skipPrefix)] != '/' {
355 continue
356 }
357 }
358
359 path := strings.TrimPrefix(strings.TrimPrefix(h.Name, skipPrefix), "/")
Joe Tsai707894e2019-03-01 12:50:52 -0800360 path = filepath.Join(dstPath, filepath.FromSlash(path))
361 mode := os.FileMode(h.Mode & 0777)
362 switch h.Typeflag {
363 case tar.TypeReg:
364 b, err := ioutil.ReadAll(tr)
365 check(err)
366 check(ioutil.WriteFile(path, b, mode))
367 case tar.TypeDir:
368 check(os.Mkdir(path, mode))
369 }
370 }
371}
372
Joe Tsai4f3de442019-08-07 19:33:51 -0700373func mustHandleFlags(t *testing.T) {
374 if *regenerate {
375 t.Run("Generate", func(t *testing.T) {
376 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-types", "-execute"))
377 fmt.Print(mustRunCommand(t, "go", "run", "-tags", "protolegacy", "./internal/cmd/generate-protos", "-execute"))
378 files := strings.Split(strings.TrimSpace(mustRunCommand(t, "git", "ls-files", "*.go")), "\n")
379 mustRunCommand(t, append([]string{"gofmt", "-w"}, files...)...)
380 })
381 }
382 if *buildRelease {
383 t.Run("BuildRelease", func(t *testing.T) {
Joe Tsai4ab2bc92020-03-10 17:38:07 -0700384 v := version.String()
Joe Tsai4f3de442019-08-07 19:33:51 -0700385 for _, goos := range []string{"linux", "darwin", "windows"} {
386 for _, goarch := range []string{"386", "amd64"} {
387 binPath := filepath.Join("bin", fmt.Sprintf("protoc-gen-go.%v.%v.%v", v, goos, goarch))
388
389 // Build the binary.
390 cmd := command{Env: append(os.Environ(), "GOOS="+goos, "GOARCH="+goarch)}
Joe Tsai576cfb32019-09-04 22:50:42 -0700391 cmd.mustRun(t, "go", "build", "-trimpath", "-ldflags", "-s -w -buildid=", "-o", binPath, "./cmd/protoc-gen-go")
Joe Tsai4f3de442019-08-07 19:33:51 -0700392
393 // Archive and compress the binary.
394 in, err := ioutil.ReadFile(binPath)
395 if err != nil {
396 t.Fatal(err)
397 }
398 out := new(bytes.Buffer)
399 gz, _ := gzip.NewWriterLevel(out, gzip.BestCompression)
400 gz.Comment = fmt.Sprintf("protoc-gen-go VERSION=%v GOOS=%v GOARCH=%v", v, goos, goarch)
401 tw := tar.NewWriter(gz)
402 tw.WriteHeader(&tar.Header{
403 Name: "protoc-gen-go",
404 Mode: int64(0775),
405 Size: int64(len(in)),
406 })
407 tw.Write(in)
408 tw.Close()
409 gz.Close()
410 if err := ioutil.WriteFile(binPath+".tar.gz", out.Bytes(), 0664); err != nil {
411 t.Fatal(err)
412 }
413 }
414 }
415 })
416 }
417 if *regenerate || *buildRelease {
418 t.SkipNow()
419 }
420}
421
Damien Neil3a185602020-02-21 09:16:19 -0800422var copyrightRegex = []*regexp.Regexp{
423 regexp.MustCompile(`^// Copyright \d\d\d\d The Go Authors\. All rights reserved.
424// Use of this source code is governed by a BSD-style
425// license that can be found in the LICENSE file\.
426`),
427 // Generated .pb.go files from main protobuf repo.
428 regexp.MustCompile(`^// Protocol Buffers - Google's data interchange format
429// Copyright \d\d\d\d Google Inc\. All rights reserved\.
430`),
431}
432
Damien Neil3a185602020-02-21 09:16:19 -0800433func mustHaveCopyrightHeader(t *testing.T, files []string) {
434 var bad []string
435File:
436 for _, file := range files {
Damien Neil3a185602020-02-21 09:16:19 -0800437 b, err := ioutil.ReadFile(file)
438 if err != nil {
439 t.Fatal(err)
440 }
441 for _, re := range copyrightRegex {
442 if loc := re.FindIndex(b); loc != nil && loc[0] == 0 {
443 continue File
444 }
445 }
446 bad = append(bad, file)
447 }
448 if len(bad) > 0 {
449 t.Fatalf("files with missing/bad copyright headers:\n %v", strings.Join(bad, "\n "))
450 }
451}
452
Joe Tsai7164af52019-08-07 19:27:43 -0700453type command struct {
454 Dir string
455 Env []string
456}
457
458func (c command) mustRun(t *testing.T, args ...string) string {
Joe Tsai707894e2019-03-01 12:50:52 -0800459 t.Helper()
460 stdout := new(bytes.Buffer)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700461 stderr := new(bytes.Buffer)
Joe Tsai707894e2019-03-01 12:50:52 -0800462 cmd := exec.Command(args[0], args[1:]...)
Joe Tsai7164af52019-08-07 19:27:43 -0700463 cmd.Dir = "."
464 if c.Dir != "" {
465 cmd.Dir = c.Dir
466 }
467 cmd.Env = os.Environ()
468 if c.Env != nil {
469 cmd.Env = c.Env
470 }
471 cmd.Env = append(cmd.Env, "PWD="+cmd.Dir)
Herbie Ong4630b3d2019-03-19 16:42:01 -0700472 cmd.Stdout = stdout
473 cmd.Stderr = stderr
Joe Tsai707894e2019-03-01 12:50:52 -0800474 if err := cmd.Run(); err != nil {
Herbie Ong4630b3d2019-03-19 16:42:01 -0700475 t.Fatalf("executing (%v): %v\n%s%s", strings.Join(args, " "), err, stdout.String(), stderr.String())
Joe Tsai707894e2019-03-01 12:50:52 -0800476 }
477 return stdout.String()
478}
Damien Neila80229e2019-06-20 12:53:48 -0700479
Joe Tsai7164af52019-08-07 19:27:43 -0700480func mustRunCommand(t *testing.T, args ...string) string {
481 t.Helper()
482 return command{}.mustRun(t, args...)
483}