-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
lint_test.go
2797 lines (2527 loc) · 76.5 KB
/
lint_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
//go:build lint
// +build lint
package lint
import (
"bufio"
"bytes"
_ "embed"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"testing"
"github.com/cockroachdb/cockroach/pkg/build/bazel"
"github.com/cockroachdb/cockroach/pkg/internal/codeowners"
"github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
"github.com/cockroachdb/cockroach/pkg/testutils/datapathutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/errors"
"github.com/ghemawat/stream"
"github.com/jordanlewis/gcassert"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/tools/go/packages"
)
// Various copyright file headers we lint on.
var (
cslHeader = regexp.MustCompile(`// Copyright 20\d\d The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
`)
cslHeaderHash = regexp.MustCompile(`# Copyright 20\d\d The Cockroach Authors.
#
# Use of this software is governed by the CockroachDB Software License
# included in the /LICENSE file.
`)
// etcdApacheHeader is the header of pkg/raft at the time it was imported.
etcdApacheHeader = regexp.MustCompile(`// Copyright 20\d\d The etcd Authors
//
// Licensed under the Apache License, Version 2.0 \(the "License"\);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
`)
// cockroachModifiedCopyright is a header that's required to be added any
// time a file with etcdApacheHeader is modified by authors from CRL.
cockroachModifiedCopyright = regexp.MustCompile(
`// This code has been modified from its original form by The Cockroach Authors.
// All modifications are Copyright 20\d\d The Cockroach Authors.`)
)
const cockroachDB = "github.com/cockroachdb/cockroach"
//go:embed gcassert_paths.txt
var rawGcassertPaths string
func init() {
if bazel.BuiltWithBazel() {
goSdk := os.Getenv("GO_SDK")
if goSdk == "" {
panic("expected GO_SDK")
}
if err := os.Setenv("PATH", fmt.Sprintf("%s%c%s", filepath.Join(goSdk, "bin"), os.PathListSeparator, os.Getenv("PATH"))); err != nil {
panic(err)
}
if err := os.Setenv("GOROOT", goSdk); err != nil {
panic(err)
}
}
}
func dirCmd(
dir string, name string, args ...string,
) (*exec.Cmd, *bytes.Buffer, stream.Filter, error) {
cmd := exec.Command(name, args...)
cmd.Dir = dir
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, nil, nil, err
}
stderr := new(bytes.Buffer)
cmd.Stderr = stderr
return cmd, stderr, stream.ReadLines(stdout), nil
}
// vetCmd executes commands like dirCmd, but stderr is used as the output
// instead of stdout, as produced by programs like `go vet`.
func vetCmd(t *testing.T, dir, name string, args []string, filters []stream.Filter) {
cmd := exec.Command(name, args...)
cmd.Dir = dir
var b bytes.Buffer
cmd.Stdout = &b
cmd.Stderr = &b
err := cmd.Run()
if err != nil && !errors.HasType(err, (*exec.ExitError)(nil)) {
t.Fatal(err)
}
filters = append([]stream.Filter{
stream.FilterFunc(func(arg stream.Arg) error {
scanner := bufio.NewScanner(&b)
for scanner.Scan() {
if s := scanner.Text(); strings.TrimSpace(s) != "" {
arg.Out <- s
}
}
return scanner.Err()
})}, filters...)
var msgs strings.Builder
if err := stream.ForEach(stream.Sequence(filters...), func(s string) {
fmt.Fprintln(&msgs, s)
}); err != nil {
t.Error(err)
}
if msgs.Len() > 0 {
t.Errorf("\n%s", strings.ReplaceAll(msgs.String(), "\\n++", "\n"))
}
}
// TestLint runs a suite of linters on the codebase.
//
// Linters may be skipped for two reasons: The "short" flag (i.e.
// `make lintshort`), which skips the most expensive linters (more for
// memory than for CPU usage), and the PKG variable. Some linters in
// the global group may be skipped if the PKG flag is set regardless
// of the short flag since they cannot be restricted to the package.
// It should be reasonable to run `make lintshort` and `make lint
// PKG=some/modified/pkg` locally and rely on CI for the more
// expensive linters.
//
// Linters which run in a single process without internal
// parallelization, and which have reasonable memory consumption
// should be marked with t.Parallel().
func TestLint(t *testing.T) {
var crdbDir, pkgDir string
if bazel.BuiltWithBazel() {
var set bool
crdbDir, set = envutil.EnvString("COCKROACH_WORKSPACE", 0)
if !set || crdbDir == "" {
t.Fatal("must supply COCKROACH_WORKSPACE variable (./dev lint does this for you automatically)")
}
pkgDir = filepath.Join(crdbDir, "pkg")
} else {
cwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
for filepath.Base(cwd) != "pkg" {
cwd = filepath.Dir(cwd)
}
pkgDir = cwd
crdbDir = filepath.Dir(pkgDir)
}
pkgVar, pkgSpecified := os.LookupEnv("PKG")
var nogoConfig map[string]any
var nogoJSON []byte
if bazel.BuiltWithBazel() {
nogoJSONPath, err := bazel.Runfile("build/bazelutil/nogo_config.json")
if err != nil {
t.Fatal(err)
}
nogoJSON, err = os.ReadFile(nogoJSONPath)
if err != nil {
t.Fatal(err)
}
} else {
var err error
nogoJSON, err = os.ReadFile(filepath.Join(crdbDir, "build", "bazelutil", "nogo_config.json"))
if err != nil {
t.Fatal(err)
}
}
if err := json.Unmarshal(nogoJSON, &nogoConfig); err != nil {
t.Error(err)
}
t.Run("TestLowercaseFunctionNames", func(t *testing.T) {
skip.UnderShort(t)
t.Parallel()
reSkipCasedFunction, err := regexp.Compile(`^(Binary file.*|[^:]+:\d+:(` +
`query error .*` + // OK when in logic tests
`|` +
`\s*(//|#).*` + // OK when mentioned in comment
`|` +
`.*lint: uppercase function OK` + // linter annotation at end of line
`))$`)
if err != nil {
t.Fatal(err)
}
var names []string
for _, name := range builtins.AllBuiltinNames() {
if _, ok := builtins.CastBuiltinNames[name]; ok {
continue
}
switch name {
case "extract", "trim", "overlay", "position", "substring", "st_x", "st_y":
// Exempt special forms: EXTRACT(... FROM ...), etc.
default:
names = append(names, strings.ToUpper(name))
}
}
cmd, stderr, filter, err := dirCmd(crdbDir,
"git", "grep", "-nE", fmt.Sprintf(`[^_a-zA-Z](%s)\(`, strings.Join(names, "|")),
"--", "pkg", ":!pkg/cmd/roachtest/testdata/regression.diffs")
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
if reSkipCasedFunction.MatchString(s) {
// OK when mentioned in comment or lint disabled.
return
}
if strings.Contains(s, "FAMILY"+"(") {
t.Errorf("\n%s <- forbidden; use \"FAMILY (\" (with space) or "+
"lowercase \"family(\" for the built-in function", s)
} else {
t.Errorf("\n%s <- forbidden; use lowercase for SQL built-in functions", s)
}
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestCopyrightHeadersWithSlash", func(t *testing.T) {
t.Parallel()
// These extensions identify source files that should have copyright headers.
extensions := []string{
"*.go", "*.cc", "*.h", "*.js", "*.ts", "*.tsx", "*.s", "*.S", "*.scss", "*.styl", "*.proto", "*.rl",
}
fullExtensions := make([]string, len(extensions)*2)
for i, extension := range extensions {
fullExtensions[i*2] = "build/**/" + extension
fullExtensions[i*2+1] = "pkg/**/" + extension
}
cmd, stderr, filter, err := dirCmd(crdbDir, "git", append([]string{"ls-files"}, fullExtensions...)...)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(stream.Sequence(filter,
stream.GrepNot(`\.pb\.go`),
stream.GrepNot(`\.pb\.gw\.go`),
stream.GrepNot(`\.og\.go`),
stream.GrepNot(`\.eg\.go`),
stream.GrepNot(`_string\.go`),
stream.GrepNot(`_generated(_test)?\.go`),
stream.GrepNot(`/embedded.go`),
stream.GrepNot(`geo/geographiclib/geodesic\.c$`),
stream.GrepNot(`geo/geographiclib/geodesic\.h$`),
// These files are copied from bazel upstream with its own license.
stream.GrepNot(`build/bazel/bes/.*.proto$`),
// These files are copied from raft upstream with its own license.
stream.GrepNot(`^pkg/raft/.*`),
// Generated files for plpgsql.
stream.GrepNot(`sql/plpgsql/parser/plpgsqllexbase/.*.go`),
), func(filename string) {
file, err := os.Open(filepath.Join(crdbDir, filename))
if err != nil {
t.Error(err)
return
}
defer file.Close()
data := make([]byte, 1024)
n, err := file.Read(data)
if err != nil {
t.Errorf("reading start of %s: %s", filename, err)
}
data = data[0:n]
if cslHeader.Find(data) == nil {
t.Errorf("did not find expected CSL license header in %s", filename)
}
}); err != nil {
t.Fatal(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestCopyrightHeadersWithHash", func(t *testing.T) {
t.Parallel()
// These extensions identify source files that should have copyright headers.
extensions := []string{"GNUmakefile", "Makefile", "*.py", "*.sh"}
cmd, stderr, filter, err := dirCmd(crdbDir, "git", append([]string{"ls-files"}, extensions...)...)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(stream.Sequence(filter,
stream.GrepNot(`^c-deps/.*`),
// These files are copied from raft upstream with its own license.
stream.GrepNot(`^raft/.*`),
), func(filename string) {
file, err := os.Open(filepath.Join(crdbDir, filename))
if err != nil {
t.Error(err)
return
}
defer file.Close()
data := make([]byte, 1024)
n, err := file.Read(data)
if err != nil {
t.Errorf("reading start of %s: %s", filename, err)
}
data = data[0:n]
if cslHeaderHash.Find(data) == nil {
t.Errorf("did not find expected CSL license header in %s", filename)
}
}); err != nil {
t.Fatal(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
// TestRaftCopyrightHeaders checks that all the source files in pkg/raft have
// the original copyright headers from etcd-io/raft, and the modified files
// have Cockroach attribution.
t.Run("TestRaftCopyrightHeaders", func(t *testing.T) {
t.Parallel()
if pkgSpecified {
skip.IgnoreLint(t, "PKG specified")
}
raftDir := filepath.Join(pkgDir, "raft")
// These extensions identify source files that should have copyright headers.
// TODO(pav-kv): add "*.proto". Currently raft.proto has no header.
extensions := []string{"*.go"}
// The commit that imported etcd-io/raft into pkg/raft.
const baseSHA = "cd6f4f263bd42688096064825dfa668bde2d3720"
const modifiedFlag = "M"
const addedFlag = "A"
gitDiff := func(flag string) map[string]struct{} {
// List the source files that have been modified.
cmd, stderr, filter, err := dirCmd(raftDir, "git", append([]string{
"diff", baseSHA, "--name-status", fmt.Sprintf("--diff-filter=%s", flag), "--"},
extensions...)...)
require.NoError(t, err)
require.NoError(t, cmd.Start())
// The command outputs lines of the form "M\t<filename>".
paths := make(map[string]struct{})
require.NoError(t, stream.ForEach(stream.Sequence(filter), func(row string) {
parts := strings.Split(row, "\t")
require.Len(t, parts, 2)
paths[parts[1]] = struct{}{}
}))
if err := cmd.Wait(); err != nil {
require.Empty(t, stderr.String(), "err=%s", err)
}
return paths
}
// modified will contain the set of all files in pkg/raft that were
// modified since importing etcd-io/raft into it.
modified := gitDiff(modifiedFlag)
// added will contain the set of all files in pkg/raft that were added
// since importing etcd-io/raft into it.
added := gitDiff(addedFlag)
cmd, stderr, filter, err := dirCmd(raftDir, "git",
append([]string{"ls-files", "--full-name"}, extensions...)...)
require.NoError(t, err)
require.NoError(t, cmd.Start())
require.NoError(t, stream.ForEach(stream.Sequence(filter,
stream.GrepNot(`\.pb\.go`),
stream.GrepNot(`_string\.go`),
), func(filename string) {
file, err := os.Open(filepath.Join(crdbDir, filename))
require.NoError(t, err)
defer file.Close()
data := make([]byte, 1024)
n, err := file.Read(data)
require.NoError(t, err)
data = data[0:n]
if _, ok := added[filename]; ok {
// Typically, any new file that is added will include a
// CockroachDB Software Licens header. However, if most of it isn't
// new code, and is moved from an existing etcd forked file, the
// author may consider it as modified; the linter is liberal enough
// to allow either of these.
assert.True(t, (cslHeader.Find(data) != nil) ||
(etcdApacheHeader.Find(data) != nil && cockroachModifiedCopyright.Find(data) != nil),
"did not find expected a) CockroachDB Software License header or b) "+
"Apache license header and Cockroach copyright header in %s",
filename)
} else {
assert.NotNilf(t, etcdApacheHeader.Find(data),
"did not find expected Apache license header in %s", filename)
}
if _, ok := modified[filename]; ok {
assert.NotNilf(t, cockroachModifiedCopyright.Find(data),
"did not find expected Cockroach copyright header in %s", filename)
}
}))
if err := cmd.Wait(); err != nil {
require.Empty(t, stderr.String(), "err=%s", err)
}
})
t.Run("TestMissingLeakTest", func(t *testing.T) {
t.Parallel()
cmd, stderr, filter, err := dirCmd(pkgDir, "util/leaktest/check-leaktest.sh")
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf("\n%s", s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestNoContextTODOInTests", func(t *testing.T) {
t.Parallel()
cmd, stderr, filter, err := dirCmd(
pkgDir,
"git",
"grep",
"-nE",
`context.TODO\(\)`,
"--",
"*_test.go",
":!raft/*.go",
)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf("\n%s <- forbidden; use context.Background() in tests.", s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestTabsInShellScripts", func(t *testing.T) {
t.Parallel()
cmd, stderr, filter, err := dirCmd(pkgDir, "git", "grep", "-nE", "^ *\t", "--", "*.sh")
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf(`%s <- tab detected, use spaces instead`, s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestOptfmt", func(t *testing.T) {
t.Parallel()
if pkgSpecified {
skip.IgnoreLint(t, "PKG specified")
}
// If run outside of Bazel, we assume this binary must be in the PATH.
optfmt := "optfmt"
if bazel.BuiltWithBazel() {
var err error
optfmt, err = bazel.Runfile("pkg/sql/opt/optgen/cmd/optfmt/optfmt_/optfmt")
if err != nil {
t.Fatal(err)
}
}
cmd, stderr, filter, err := dirCmd(pkgDir, "git", "ls-files", "*.opt", ":!*/testdata/*")
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
if err := stream.ForEach(
stream.Sequence(
filter,
stream.Map(func(s string) string {
return filepath.Join(pkgDir, s)
}),
stream.Xargs(optfmt, "-l"),
), func(s string) {
fmt.Fprintln(&buf, s)
}); err != nil {
t.Error(err)
}
errs := buf.String()
if len(errs) > 0 {
t.Errorf("\n%s", errs)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestHttputil", func(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
re string
excludes []string
}{
{re: `\bhttp\.(Get|Put|Head)\(`},
} {
cmd, stderr, filter, err := dirCmd(
pkgDir,
"git",
append([]string{
"grep",
"-nE",
tc.re,
"--",
"*.go",
}, tc.excludes...)...,
)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf("\n%s <- forbidden; use 'httputil' instead", s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
}
})
t.Run("TestEnvutil", func(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
re string
excludes []string
}{
{re: `\bos\.(Getenv|LookupEnv)\("COCKROACH`,
excludes: []string{
":!cmd/bazci/githubpost",
":!acceptance/test_acceptance.go", // For COCKROACH_RUN_ACCEPTANCE
":!compose/compare/compare/compare_test.go", // For COCKROACH_RUN_COMPOSE_COMPARE
":!compose/compose_test.go", // For COCKROACH_RUN_COMPOSE
},
},
{
re: `\bos\.(Getenv|LookupEnv)\(`,
excludes: []string{
":!acceptance",
":!build/bazel",
":!ccl/acceptanceccl/backup_test.go",
":!ccl/backupccl/backup_cloud_test.go",
// KMS requires AWS credentials from environment variables.
":!ccl/backupccl/backup_test.go",
":!ccl/changefeedccl/helpers_test.go",
":!ccl/cloudccl",
":!cloud",
":!ccl/workloadccl/fixture_test.go",
":!internal/reporoot/reporoot.go",
":!cmd",
":!util/cgroups/cgroups.go",
":!nightly",
":!testutils/lint",
":!util/envutil/env.go",
":!testutils/data_path.go",
":!testutils/bazelcodecover/code_cover_on.go", // For BAZEL_COVER_DIR.
":!util/log/tracebacks.go",
":!util/sdnotify/sdnotify_unix.go",
":!util/grpcutil", // GRPC_GO_* variables
":!roachprod", // roachprod requires AWS environment variables
":!cli/env.go", // The CLI needs the PGHOST variable.
":!cli/start.go", // The CLI needs the GOMEMLIMIT and GOGC variables.
":!internal/codeowners/codeowners.go", // For BAZEL_TEST.
":!internal/team/team.go", // For BAZEL_TEST.
":!util/log/test_log_scope.go", // For TEST_UNDECLARED_OUTPUT_DIR, REMOTE_EXEC
":!testutils/datapathutils/data_path.go", // For TEST_UNDECLARED_OUTPUT_DIR, REMOTE_EXEC
":!testutils/backup.go", // For BACKUP_TESTING_BUCKET
":!compose/compose_test.go", // For PATH.
":!testutils/skip/skip.go", // For REMOTE_EXEC.
":!build/engflow/engflow.go", // For GITHUB_ACTIONS_BRANCH, etc.
":!acceptance/test_acceptance.go", // For COCKROACH_RUN_ACCEPTANCE
":!compose/compare/compare/compare_test.go", // For COCKROACH_RUN_COMPOSE_COMPARE
":!compose/compose_test.go", // For COCKROACH_RUN_COMPOSE
},
},
} {
cmd, stderr, filter, err := dirCmd(
pkgDir,
"git",
append([]string{
"grep",
"-nE",
tc.re,
"--",
"*.go",
}, tc.excludes...)...,
)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf("\n%s <- forbidden; use 'envutil' instead", s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
}
})
t.Run("TestSyncutil", func(t *testing.T) {
t.Parallel()
cmd, stderr, filter, err := dirCmd(
pkgDir,
"git",
"grep",
"-nE",
`\bsync\.((RW)?Mutex|Map)`,
"--",
"*.go",
":!*/doc.go",
":!raft/*.go",
":!util/syncutil/mutex_sync.go",
":!util/syncutil/mutex_sync_race.go",
":!testutils/lint/lint_test.go",
":!testutils/lint/passes/deferunlockcheck/testdata/src/github.com/cockroachdb/cockroach/pkg/util/syncutil/mutex_sync.go",
// Exception needed for goroutineStalledStates.
":!kv/kvserver/concurrency/concurrency_manager_test.go",
)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
var fix string
switch {
case strings.Contains(s, "sync.Mutex"):
fix = "syncutil.Mutex"
case strings.Contains(s, "sync.RWMutex"):
fix = "syncutil.RWMutex"
case strings.Contains(s, "sync.Map"):
fix = "syncutil.Map"
default:
t.Fatalf("unexpected sync reference: %s", s)
}
t.Errorf("\n%s <- forbidden; use '%s' instead", s, fix)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestStartServer", func(t *testing.T) {
t.Parallel()
cmd, stderr, filter, err := dirCmd(
pkgDir,
"git",
"grep",
"-nE",
`, _, _ :?= serverutils\.StartServer\(`,
"--",
"*_test.go",
)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf("\n%s <- forbidden; use 'serverutils.StartServerOnly' instead", s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestServerCast", func(t *testing.T) {
t.Parallel()
cmd, stderr, filter, err := dirCmd(
pkgDir,
"git",
"grep",
"-nE",
`\*(testServer|testTenant)`,
"--",
"server/*_test.go",
":!server/server_special_test.go",
":!server/server_controller_test.go",
":!server/settings_cache_test.go",
)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf("\n%s <- forbidden; use Go interfaces instead (see testutils/serverutils/api.go)", s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestSQLTelemetryDirectCount", func(t *testing.T) {
t.Parallel()
cmd, stderr, filter, err := dirCmd(
pkgDir,
"git",
"grep",
"-nE",
`[^[:alnum:]]telemetry\.Count\(`,
"--",
"sql",
":!sql/importer",
)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf("\n%s <- forbidden; use 'sqltelemetry.xxxCounter()' / `telemetry.Inc' instead", s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestSQLTelemetryGetCounter", func(t *testing.T) {
t.Parallel()
cmd, stderr, filter, err := dirCmd(
pkgDir,
"git",
"grep",
"-nE",
`[^[:alnum:]]telemetry\.GetCounter`,
"--",
"sql",
":!sql/sqltelemetry",
)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf("\n%s <- forbidden; use 'sqltelemetry.xxxCounter() instead", s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestCBOPanics", func(t *testing.T) {
t.Parallel()
cmd, stderr, filter, err := dirCmd(
pkgDir,
"git",
"grep",
"-nE",
fmt.Sprintf(`[^[:alnum:]]panic\((%s|"|[a-z]+Error\{errors\.(New|Errorf)|fmt\.Errorf)`, "`"),
"--",
"sql/opt",
":!sql/opt/optgen",
":!sql/opt/testutils",
":!*.pb.go",
)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf("\n%s <- forbidden; use panic(errors.AssertionFailedf()) instead", s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestInternalErrorCodes", func(t *testing.T) {
t.Parallel()
cmd, stderr, filter, err := dirCmd(
pkgDir,
"git",
"grep",
"-nE",
`[^[:alnum:]]pgerror\.(NewError|Wrap).*pgerror\.CodeInternalError`,
)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf("\n%s <- forbidden; use errors.AssertionFailedf() instead", s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestTodoStyle", func(t *testing.T) {
t.Parallel()
// TODO(tamird): enforce presence of name.
cmd, stderr, filter, err := dirCmd(pkgDir, "git", "grep", "-nE", `\sTODO\([^)]+\)[^:]`, "--",
"*.go",
":!raft/*.go",
)
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
if err := stream.ForEach(filter, func(s string) {
t.Errorf(`%s <- use 'TODO(...): ' instead`, s)
}); err != nil {
t.Error(err)
}
if err := cmd.Wait(); err != nil {
if out := stderr.String(); len(out) > 0 {
t.Fatalf("err=%s, stderr=%s", err, out)
}
}
})
t.Run("TestNonZeroOffsetInTests", func(t *testing.T) {
t.Parallel()
cmd, stderr, filter, err := dirCmd(pkgDir, "git", "grep", "-nE", `hlc\.NewClock\([^)]+, 0\)`, "--", "*_test.go")
if err != nil {
t.Fatal(err)
}