diff --git a/cmd/autogazelle/client_unix.go b/cmd/autogazelle/client_unix.go index 2c38c7682..32666d4a6 100644 --- a/cmd/autogazelle/client_unix.go +++ b/cmd/autogazelle/client_unix.go @@ -1,3 +1,4 @@ +//go:build darwin || dragonfly || freebsd || linux || nacl || netbsd || openbsd || solaris || windows // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris windows /* Copyright 2018 The Bazel Authors. All rights reserved. diff --git a/cmd/autogazelle/server_unix.go b/cmd/autogazelle/server_unix.go index 0bade572d..e094a3b3c 100644 --- a/cmd/autogazelle/server_unix.go +++ b/cmd/autogazelle/server_unix.go @@ -1,3 +1,4 @@ +//go:build darwin || dragonfly || freebsd || linux || nacl || netbsd || openbsd || solaris || windows // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris windows /* Copyright 2018 The Bazel Authors. All rights reserved. @@ -66,7 +67,7 @@ func startServer() error { // with SIGINT or SIGTERM. func runServer() error { // Begin logging to the log file. - logFile, err := os.OpenFile(*logPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) + logFile, err := os.OpenFile(*logPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o666) if err != nil { return err } diff --git a/cmd/fetch_repo/fetch_repo_test.go b/cmd/fetch_repo/fetch_repo_test.go index 47aca9985..6e948bd3e 100644 --- a/cmd/fetch_repo/fetch_repo_test.go +++ b/cmd/fetch_repo/fetch_repo_test.go @@ -23,13 +23,11 @@ import ( "golang.org/x/tools/go/vcs" ) -var ( - root = &vcs.RepoRoot{ - VCS: vcs.ByCmd("git"), - Repo: "https://github.com/bazeltest/rules_go", - Root: "github.com/bazeltest/rules_go", - } -) +var root = &vcs.RepoRoot{ + VCS: vcs.ByCmd("git"), + Repo: "https://github.com/bazeltest/rules_go", + Root: "github.com/bazeltest/rules_go", +} func TestMain(m *testing.M) { // Replace vcs.RepoRootForImportPath to disable any network calls. diff --git a/cmd/fetch_repo/module.go b/cmd/fetch_repo/module.go index 5e5d9c01b..123db3610 100644 --- a/cmd/fetch_repo/module.go +++ b/cmd/fetch_repo/module.go @@ -60,7 +60,7 @@ func fetchModule(dest, importpath, version, sum string) error { // Download the module. In Go 1.11, this command must be run in a module, // so we create a dummy module in the current directory (which should be // empty). - w, err := os.OpenFile("go.mod", os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666) + w, err := os.OpenFile("go.mod", os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o666) if err != nil { return fmt.Errorf("error creating temporary go.mod: %v", err) } @@ -132,7 +132,7 @@ func copyTree(destRoot, srcRoot string) error { dest := filepath.Join(destRoot, rel) if info.IsDir() { - return os.Mkdir(dest, 0777) + return os.Mkdir(dest, 0o777) } else { r, err := os.Open(src) if err != nil { diff --git a/cmd/gazelle/diff.go b/cmd/gazelle/diff.go index 63ddb6569..8b57d30c1 100644 --- a/cmd/gazelle/diff.go +++ b/cmd/gazelle/diff.go @@ -27,7 +27,7 @@ import ( "github.com/pmezard/go-difflib/difflib" ) -var exitError = fmt.Errorf("encountered changes while running diff") +var errExit = fmt.Errorf("encountered changes while running diff") func diffFile(c *config.Config, f *rule.File) error { rel, err := filepath.Rel(c.RepoRoot, f.Path) @@ -60,7 +60,7 @@ func diffFile(c *config.Config, f *rule.File) error { } if len(f.Content) != 0 { - diff.A = difflib.SplitLines(string(f.Content)) + diff.A = difflib.SplitLines(string(f.Content)) } diff.B = difflib.SplitLines(string(newContent)) @@ -80,7 +80,7 @@ func diffFile(c *config.Config, f *rule.File) error { return fmt.Errorf("error diffing %s: %v", f.Path, err) } if ds, _ := difflib.GetUnifiedDiffString(diff); ds != "" { - return exitError + return errExit } return nil diff --git a/cmd/gazelle/diff_test.go b/cmd/gazelle/diff_test.go index e3703da14..a1862c1e6 100644 --- a/cmd/gazelle/diff_test.go +++ b/cmd/gazelle/diff_test.go @@ -31,7 +31,8 @@ func TestDiffExisting(t *testing.T) { Content: ` # gazelle:prefix example.com/hello `, - }, { + }, + { Path: "hello.go", Content: `package hello`, }, diff --git a/cmd/gazelle/fix-update.go b/cmd/gazelle/fix-update.go index 54904a9e1..1f26c4ef0 100644 --- a/cmd/gazelle/fix-update.go +++ b/cmd/gazelle/fix-update.go @@ -227,12 +227,6 @@ type visitRecord struct { mappedKindInfo map[string]rule.KindInfo } -type byPkgRel []visitRecord - -func (vs byPkgRel) Len() int { return len(vs) } -func (vs byPkgRel) Less(i, j int) bool { return vs[i].pkgRel < vs[j].pkgRel } -func (vs byPkgRel) Swap(i, j int) { vs[i], vs[j] = vs[j], vs[i] } - var genericLoads = []rule.LoadInfo{ { Name: "@bazel_gazelle//:def.bzl", @@ -306,7 +300,8 @@ func runFixUpdate(wd string, cmd command, args []string) (err error) { RegularFiles: regularFiles, GenFiles: genFiles, OtherEmpty: empty, - OtherGen: gen}) + OtherGen: gen, + }) if len(res.Gen) != len(res.Imports) { log.Panicf("%s: language %s generated %d rules but returned %d imports", rel, l.Name(), len(res.Gen), len(res.Imports)) } @@ -387,7 +382,7 @@ func runFixUpdate(wd string, cmd command, args []string) (err error) { for _, v := range visits { merger.FixLoads(v.file, applyKindMappings(v.mappedKinds, loads)) if err := uc.emit(v.c, v.file); err != nil { - if err == exitError { + if err == errExit { exit = err } else { log.Print(err) @@ -395,7 +390,7 @@ func runFixUpdate(wd string, cmd command, args []string) (err error) { } } if uc.patchPath != "" { - if err := ioutil.WriteFile(uc.patchPath, uc.patchBuffer.Bytes(), 0666); err != nil { + if err := ioutil.WriteFile(uc.patchPath, uc.patchBuffer.Bytes(), 0o666); err != nil { return err } } diff --git a/cmd/gazelle/fix.go b/cmd/gazelle/fix.go index 6b79506f5..77384becb 100644 --- a/cmd/gazelle/fix.go +++ b/cmd/gazelle/fix.go @@ -32,10 +32,10 @@ func fixFile(c *config.Config, f *rule.File) error { return nil } outPath := findOutputPath(c, f) - if err := os.MkdirAll(filepath.Dir(outPath), 0777); err != nil { + if err := os.MkdirAll(filepath.Dir(outPath), 0o777); err != nil { return err } - if err := ioutil.WriteFile(outPath, newContent, 0666); err != nil { + if err := ioutil.WriteFile(outPath, newContent, 0o666); err != nil { return err } f.Content = newContent diff --git a/cmd/gazelle/fix_test.go b/cmd/gazelle/fix_test.go index 7d677aba0..4bff171f6 100644 --- a/cmd/gazelle/fix_test.go +++ b/cmd/gazelle/fix_test.go @@ -50,12 +50,12 @@ func TestMain(m *testing.M) { // to any files that don't have it. Files and directories in the module cache // are read-only, and on Windows, the read-only bit prevents deletion and // prevents Bazel from cleaning up the source tree. - filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error { + _ = filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } - if mode := info.Mode(); mode&0200 == 0 { - err = os.Chmod(path, mode|0200) + if mode := info.Mode(); mode&0o200 == 0 { + err = os.Chmod(path, mode|0o200) } return err }) @@ -112,12 +112,14 @@ func TestCreateFile(t *testing.T) { defer os.RemoveAll(dir) goFile := filepath.Join(dir, "main.go") - if err = ioutil.WriteFile(goFile, []byte("package main"), 0600); err != nil { + if err = ioutil.WriteFile(goFile, []byte("package main"), 0o600); err != nil { t.Fatalf("error writing file %q: %v", goFile, err) } // Check that Gazelle creates a new file named "BUILD.bazel". - run(dir, defaultArgs(dir)) + if err = run(dir, defaultArgs(dir)); err != nil { + t.Fatalf("run failed: %v", err) + } buildFile := filepath.Join(dir, "BUILD.bazel") if _, err = os.Stat(buildFile); err != nil { @@ -135,17 +137,20 @@ func TestUpdateFile(t *testing.T) { defer os.RemoveAll(dir) goFile := filepath.Join(dir, "main.go") - if err = ioutil.WriteFile(goFile, []byte("package main"), 0600); err != nil { + if err = ioutil.WriteFile(goFile, []byte("package main"), 0o600); err != nil { t.Fatalf("error writing file %q: %v", goFile, err) } buildFile := filepath.Join(dir, "BUILD") - if err = ioutil.WriteFile(buildFile, nil, 0600); err != nil { + if err = ioutil.WriteFile(buildFile, nil, 0o600); err != nil { t.Fatalf("error writing file %q: %v", buildFile, err) } // Check that Gazelle updates the BUILD file in place. - run(dir, defaultArgs(dir)) + if err = run(dir, defaultArgs(dir)); err != nil { + t.Fatalf("run failed: %v", err) + } + if st, err := os.Stat(buildFile); err != nil { t.Errorf("could not stat BUILD: %v", err) } else if st.Size() == 0 { @@ -167,7 +172,7 @@ func TestNoChanges(t *testing.T) { defer os.RemoveAll(dir) goFile := filepath.Join(dir, "main.go") - if err = ioutil.WriteFile(goFile, []byte("package main"), 0600); err != nil { + if err = ioutil.WriteFile(goFile, []byte("package main"), 0o600); err != nil { t.Fatalf("error writing file %q: %v", goFile, err) } @@ -186,7 +191,7 @@ go_binary( embed = [":go_default_library"], visibility = ["//visibility:public"], ) -`), 0600); err != nil { +`), 0o600); err != nil { t.Fatalf("error writing file %q: %v", buildFile, err) } st, err := os.Stat(buildFile) @@ -196,7 +201,10 @@ go_binary( modTime := st.ModTime() // Ensure that Gazelle does not write to the BUILD file. - run(dir, defaultArgs(dir)) + if err = run(dir, defaultArgs(dir)); err != nil { + t.Fatalf("run failed: %v", err) + } + if st, err := os.Stat(buildFile); err != nil { t.Errorf("could not stat BUILD: %v", err) } else if !modTime.Equal(st.ModTime()) { @@ -228,7 +236,8 @@ package main func main() {} `, - }, { + }, + { Path: "out/BUILD", Content: `this should get replaced`, }, @@ -388,12 +397,14 @@ go_library( defer cleanup() // Check that Gazelle does not update the BUILD file, due to lang filter. - run(dir, []string{ + if err := run(dir, []string{ "-repo_root", dir, "-go_prefix", "example.com/repo", "-lang=proto", dir, - }) + }); err != nil { + t.Fatalf("run failed: %v", err) + } testtools.CheckFiles(t, dir, fixture) } diff --git a/cmd/gazelle/gazelle.go b/cmd/gazelle/gazelle.go index 5ee70bbd0..2ff57dbc6 100644 --- a/cmd/gazelle/gazelle.go +++ b/cmd/gazelle/gazelle.go @@ -70,7 +70,7 @@ func main() { } if err := run(wd, os.Args[1:]); err != nil && err != flag.ErrHelp { - if err == exitError { + if err == errExit { os.Exit(1) } else { log.Fatal(err) diff --git a/cmd/gazelle/integration_test.go b/cmd/gazelle/integration_test.go index cd66b2afc..3c9d9ba87 100644 --- a/cmd/gazelle/integration_test.go +++ b/cmd/gazelle/integration_test.go @@ -337,7 +337,8 @@ go_library( visibility = ["//visibility:public"], ) `, - }, { + }, + { Path: "pure.go", Content: "package foo", }, @@ -381,10 +382,12 @@ go_library( importpath = "example.com/foo/x", ) `, - }, { + }, + { Path: "a/a.go", Content: "package a", - }, { + }, + { Path: "b/b.go", Content: ` package b @@ -462,7 +465,8 @@ func TestBuildFileNameIgnoresBuild(t *testing.T) { { Path: "a/BUILD", Content: "!!! parse error", - }, { + }, + { Path: "a.go", Content: "package a", }, @@ -558,13 +562,15 @@ go_proto_library( srcs = [":go_default_library_protos"], ) `, - }, { + }, + { Path: "foo.proto", Content: `syntax = "proto3"; option go_package = "example.com/repo"; `, - }, { + }, + { Path: "foo.pb.go", Content: `package repo`, }, @@ -672,7 +678,8 @@ go_library( visibility = ["//visibility:public"], ) `, - }, { + }, + { Path: "extra.go", Content: `package repo`, }, @@ -730,7 +737,8 @@ go_library( visibility = ["//visibility:public"], ) `, - }, { + }, + { Path: "foo.proto", Content: `syntax = "proto3"; @@ -810,7 +818,8 @@ go_library( visibility = ["//visibility:public"], ) `, - }, { + }, + { Path: "foo.proto", Content: `syntax = "proto3";`, }, @@ -819,8 +828,10 @@ go_library( dir, cleanup := testtools.CreateFiles(t, files) defer cleanup() - args := []string{"update", "-go_prefix", "example.com/repo", - "-proto_import_prefix", "/bar"} + args := []string{ + "update", "-go_prefix", "example.com/repo", + "-proto_import_prefix", "/bar", + } if err := runGazelle(dir, args); err != nil { t.Fatal(err) } @@ -862,7 +873,8 @@ func TestEmptyGoPrefix(t *testing.T) { { Path: "foo/foo.go", Content: "package foo", - }, { + }, + { Path: "bar/bar.go", Content: ` package bar @@ -912,7 +924,8 @@ package foo import _ "example.com/alt/baz" `, - }, { + }, + { Path: "bar/BUILD.bazel", Content: `load("@io_bazel_rules_go//go:def.bzl", "go_library") @@ -923,7 +936,8 @@ go_library( visibility = ["//visibility:public"], ) `, - }, { + }, + { Path: "bar/bar.go", Content: "package bar", }, @@ -974,7 +988,8 @@ func TestResolveVendorSubdirectory(t *testing.T) { { Path: "sub/vendor/example.com/foo/foo.go", Content: "package foo", - }, { + }, + { Path: "sub/bar/bar.go", Content: ` package bar @@ -1057,10 +1072,12 @@ go_proto_library( deps = ["//foo/bar:go_default_library"], ) `, - }, { + }, + { Path: "foo/extra.go", Content: "package foo", - }, { + }, + { Path: "foo/bar/bar.proto", Content: ` syntax = "proto3"; @@ -1290,7 +1307,8 @@ go_repository( gazelle_dependencies() `, - }}) + }, + }) } func TestImportReposFromDepToWorkspace(t *testing.T) { @@ -1433,7 +1451,8 @@ http_archive( urls = ["https://example.com/yaml.tar.gz"], ) `, - }}) + }, + }) } func TestImportReposFromDepToWorkspaceWithMacro(t *testing.T) { @@ -1888,7 +1907,8 @@ def go_repositories(): importpath = "golang.org/x/sys", ) `, - }}) + }, + }) } func TestPruneRepoRules(t *testing.T) { @@ -2272,13 +2292,16 @@ package foo import _ "example.com/bar" `, - }, { + }, + { Path: "third_party/example.com/bar/bar.go", Content: "package bar", - }, { + }, + { Path: "third_party/BUILD.bazel", Content: "# gazelle:prefix", - }, { + }, + { Path: "third_party/example.com/bar/BUILD.bazel", Content: ` load("@io_bazel_rules_go//go:def.bzl", "go_library") @@ -2343,7 +2366,8 @@ import ( { Path: "foo/bar/bar.go", Content: "package bar", - }, { + }, + { Path: "third_party/baz/BUILD.bazel", Content: `load("@io_bazel_rules_go//go:def.bzl", "go_library") @@ -2355,7 +2379,8 @@ go_library( visibility = ["//visibility:public"], ) `, - }, { + }, + { Path: "third_party/baz/baz.go", Content: "package baz", }, @@ -2463,7 +2488,8 @@ go_library( visibility = ["//visibility:public"], ) `, - }}) + }, + }) } // TestSubdirectoryPrefixExternal checks that directives set in subdirectories @@ -2675,27 +2701,34 @@ func TestMapKind(t *testing.T) { files := []testtools.FileSpec{ { Path: "WORKSPACE", - }, { + }, + { Path: "BUILD.bazel", Content: ` # gazelle:prefix example.com/mapkind # gazelle:go_naming_convention go_default_library `, - }, { + }, + { Path: "root_lib.go", Content: `package mapkind`, - }, { + }, + { Path: "enabled/BUILD.bazel", Content: "# gazelle:map_kind go_library my_library //tools/go:def.bzl", - }, { + }, + { Path: "enabled/enabled_lib.go", Content: `package enabled`, - }, { + }, + { Path: "enabled/inherited/BUILD.bazel", - }, { + }, + { Path: "enabled/inherited/inherited_lib.go", Content: `package inherited`, - }, { + }, + { Path: "enabled/existing_rules/mapped/BUILD.bazel", Content: ` load("//tools/go:def.bzl", "my_library") @@ -2708,13 +2741,16 @@ my_library( visibility = ["//visibility:public"], ) `, - }, { + }, + { Path: "enabled/existing_rules/mapped/mapped_lib.go", Content: `package mapped`, - }, { + }, + { Path: "enabled/existing_rules/mapped/mapped_lib2.go", Content: `package mapped`, - }, { + }, + { Path: "enabled/existing_rules/unmapped/BUILD.bazel", Content: ` load("@io_bazel_rules_go//go:def.bzl", "go_library") @@ -2727,30 +2763,38 @@ go_library( visibility = ["//visibility:public"], ) `, - }, { + }, + { Path: "enabled/existing_rules/unmapped/unmapped_lib.go", Content: `package unmapped`, - }, { + }, + { Path: "enabled/existing_rules/nobuild/nobuild_lib.go", Content: `package nobuild`, - }, { + }, + { Path: "enabled/overridden/BUILD.bazel", Content: "# gazelle:map_kind go_library overridden_library //tools/overridden:def.bzl", - }, { + }, + { Path: "enabled/overridden/overridden_lib.go", Content: `package overridden`, - }, { + }, + { Path: "disabled/BUILD.bazel", - }, { + }, + { Path: "disabled/disabled_lib.go", Content: `package disabled`, - }, { + }, + { Path: "enabled/multiple_mappings/BUILD.bazel", Content: ` # gazelle:map_kind go_binary go_binary //tools/go:def.bzl # gazelle:map_kind go_library go_library //tools/go:def.bzl `, - }, { + }, + { Path: "enabled/multiple_mappings/multiple_mappings.go", Content: `package main`, }, @@ -3525,12 +3569,14 @@ import ( t.Fatal(err) } - testtools.CheckFiles(t, dir, []testtools.FileSpec{{ - Path: filepath.Join("foo", "BUILD.bazel"), - NotExist: true, - }, { - Path: filepath.Join("pb", "BUILD.bazel"), - Content: ` + testtools.CheckFiles(t, dir, []testtools.FileSpec{ + { + Path: filepath.Join("foo", "BUILD.bazel"), + NotExist: true, + }, + { + Path: filepath.Join("pb", "BUILD.bazel"), + Content: ` load("@rules_proto//proto:defs.bzl", "proto_library") proto_library( @@ -3538,7 +3584,7 @@ proto_library( srcs = ["pb.proto"], visibility = ["//visibility:public"], )`, - }, + }, { Path: filepath.Join("bar", "BUILD.bazel"), Content: ` diff --git a/cmd/generate_repo_config/generate_repo_config.go b/cmd/generate_repo_config/generate_repo_config.go index 6489fc631..bf2f16da6 100644 --- a/cmd/generate_repo_config/generate_repo_config.go +++ b/cmd/generate_repo_config/generate_repo_config.go @@ -40,8 +40,6 @@ import ( ) const ( - repositoryMacroKey = "repository_macro" - repositoryKey = "repository" goRepoRuleKind = "go_repository" httpArchiveRuleKind = "http_archive" ) @@ -129,7 +127,7 @@ func generateRepoConfig(configDest, configSource string) ([]string, error) { buf.WriteString("\n") buf.Write(destFile.Format()) - if err := ioutil.WriteFile(configDest, buf.Bytes(), 0666); err != nil { + if err := ioutil.WriteFile(configDest, buf.Bytes(), 0o666); err != nil { return nil, err } diff --git a/cmd/move_labels/move_labels.go b/cmd/move_labels/move_labels.go index 1dd522874..33a02e0fc 100644 --- a/cmd/move_labels/move_labels.go +++ b/cmd/move_labels/move_labels.go @@ -64,7 +64,7 @@ func run(args []string) error { var errs errorList for _, file := range files { content := build.Format(file) - if err := ioutil.WriteFile(file.Path, content, 0666); err != nil { + if err := ioutil.WriteFile(file.Path, content, 0o666); err != nil { errs = append(errs, err) } } @@ -166,10 +166,6 @@ func moveLocations(from, to, str string) string { return buf.String() } -func isBuiltinLabel(label string) bool { - return strings.HasPrefix(label, "//visibility:") || strings.HasPrefix(label, "//conditions:") -} - type configuration struct { // repoRoot is the repository root directory, formatted as an absolute // file system path. diff --git a/config/config_test.go b/config/config_test.go index f2864ced5..b2432560b 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -36,7 +36,7 @@ func TestCommonConfigurerFlags(t *testing.T) { if err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(filepath.Join(dir, "WORKSPACE"), nil, 0666); err != nil { + if err := ioutil.WriteFile(filepath.Join(dir, "WORKSPACE"), nil, 0o666); err != nil { t.Fatal(err) } diff --git a/flag/flag.go b/flag/flag.go index be5be2451..1989d26eb 100644 --- a/flag/flag.go +++ b/flag/flag.go @@ -70,18 +70,18 @@ func (f *ExplicitFlag) String() string { var _ stdflag.Value = (*AllowedStringFlag)(nil) type AllowedStringFlag struct { - Allowed []string - Value *string + Allowed []string + Value *string } func (f *AllowedStringFlag) Set(v string) error { - for _, a := range f.Allowed { - if v == a { - *f.Value = v - return nil - } - } - return fmt.Errorf("Invalid argument %q. Possible values are: %s", v, strings.Join(f.Allowed, ", ")) + for _, a := range f.Allowed { + if v == a { + *f.Value = v + return nil + } + } + return fmt.Errorf("Invalid argument %q. Possible values are: %s", v, strings.Join(f.Allowed, ", ")) } func (f *AllowedStringFlag) String() string { diff --git a/internal/go_repository_test.go b/internal/go_repository_test.go index 696d25b89..2583e02f3 100644 --- a/internal/go_repository_test.go +++ b/internal/go_repository_test.go @@ -174,7 +174,7 @@ func TestModcacheRW(t *testing.T) { if err != nil { t.Fatal(err) } - if info.Mode()&0200 == 0 { + if info.Mode()&0o200 == 0 { t.Fatal("module cache is read-only") } } diff --git a/internal/language/test_filegroup/lang.go b/internal/language/test_filegroup/lang.go index fab7a47c4..2c2ce7375 100644 --- a/internal/language/test_filegroup/lang.go +++ b/internal/language/test_filegroup/lang.go @@ -80,9 +80,7 @@ var kinds = map[string]rule.KindInfo{ func (*testFilegroupLang) GenerateRules(args language.GenerateArgs) language.GenerateResult { r := rule.NewRule("filegroup", "all_files") srcs := make([]string, 0, len(args.Subdirs)+len(args.RegularFiles)) - for _, f := range args.RegularFiles { - srcs = append(srcs, f) - } + srcs = append(srcs, args.RegularFiles...) for _, f := range args.Subdirs { pkg := path.Join(args.Rel, f) srcs = append(srcs, "//"+pkg+":all_files") diff --git a/internal/list_repository_tools_srcs.go b/internal/list_repository_tools_srcs.go index ca67f8512..b3dc25db9 100644 --- a/internal/list_repository_tools_srcs.go +++ b/internal/list_repository_tools_srcs.go @@ -1,3 +1,4 @@ +//go:build ignore // +build ignore // Copyright 2014 The Bazel Authors. All rights reserved. @@ -97,7 +98,7 @@ func main() { fmt.Fprintln(buf, "]") if *generate != "" { - if err := ioutil.WriteFile(*generate, buf.Bytes(), 0666); err != nil { + if err := ioutil.WriteFile(*generate, buf.Bytes(), 0o666); err != nil { log.Fatal(err) } } else { diff --git a/internal/runner_test.go b/internal/runner_test.go index 1f8923830..b15733867 100644 --- a/internal/runner_test.go +++ b/internal/runner_test.go @@ -29,7 +29,7 @@ func TestRunner(t *testing.T) { t.Fatal(err) } defer func() { - if err := ioutil.WriteFile("BUILD.bazel", origBuildData, 0666); err != nil { + if err := ioutil.WriteFile("BUILD.bazel", origBuildData, 0o666); err != nil { t.Fatalf("restoring build file: %v", err) } }() @@ -59,7 +59,7 @@ func TestRunnerUpdateReposFromGoMod(t *testing.T) { t.Fatal(err) } defer func() { - if err := ioutil.WriteFile("WORKSPACE", origWorkspaceData, 0666); err != nil { + if err := ioutil.WriteFile("WORKSPACE", origWorkspaceData, 0o666); err != nil { t.Fatalf("restoring WORKSPACE: %v", err) } }() @@ -75,7 +75,7 @@ func TestRunnerUpdateReposCommand(t *testing.T) { t.Fatal(err) } defer func() { - if err := ioutil.WriteFile("WORKSPACE", origWorkspaceData, 0666); err != nil { + if err := ioutil.WriteFile("WORKSPACE", origWorkspaceData, 0o666); err != nil { t.Fatalf("restoring WORKSPACE: %v", err) } }() diff --git a/internal/wspace/finder_test.go b/internal/wspace/finder_test.go index 09ceb5734..62d56e6c2 100644 --- a/internal/wspace/finder_test.go +++ b/internal/wspace/finder_test.go @@ -48,11 +48,11 @@ func TestFind(t *testing.T) { if tc.file != "" { // Create a WORKSPACE file - if err := os.MkdirAll(filepath.Dir(tc.file), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(tc.file), 0o755); err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(tc.file, nil, 0755); err != nil { + if err := ioutil.WriteFile(tc.file, nil, 0o755); err != nil { t.Fatal(err) } } diff --git a/label/label.go b/label/label.go index 93c4dfd66..08355e77d 100644 --- a/label/label.go +++ b/label/label.go @@ -83,8 +83,8 @@ func Parse(s string) (Label, error) { if endRepo > len("@") { repo = s[len("@"):endRepo] s = s[endRepo:] - // If the label begins with "@//...", set repo = "@" - // to remain distinct from "//...", where repo = "" + // If the label begins with "@//...", set repo = "@" + // to remain distinct from "//...", where repo = "" } else if endRepo == len("@") { repo = s[:len("@")] s = s[len("@"):] diff --git a/language/go/config.go b/language/go/config.go index a10e5dbb3..f46a60f5f 100644 --- a/language/go/config.go +++ b/language/go/config.go @@ -331,9 +331,11 @@ type moduleRepo struct { repoName, modulePath string } -var validBuildExternalAttr = []string{"external", "vendored"} -var validBuildFileGenerationAttr = []string{"auto", "on", "off"} -var validBuildFileProtoModeAttr = []string{"default", "legacy", "disable", "disable_global", "package"} +var ( + validBuildExternalAttr = []string{"external", "vendored"} + validBuildFileGenerationAttr = []string{"auto", "on", "off"} + validBuildFileProtoModeAttr = []string{"default", "legacy", "disable", "disable_global", "package"} +) func (*goLang) KnownDirectives() []string { return []string{ @@ -529,7 +531,9 @@ Update io_bazel_rules_go to a newer version in your WORKSPACE file.` continue } gc.preprocessTags() - gc.setBuildTags(d.Value) + if err := gc.setBuildTags(d.Value); err != nil { + log.Print(err) + } case "go_generate_proto": if goGenerateProto, err := strconv.ParseBool(d.Value); err == nil { diff --git a/language/go/constants.go b/language/go/constants.go index 14a343c26..5b15c0f3a 100644 --- a/language/go/constants.go +++ b/language/go/constants.go @@ -34,11 +34,4 @@ const ( // grpcCompilerLabel is the label for the gRPC compiler plugin, used in the // "compilers" attribute of go_proto_library rules. grpcCompilerLabel = "@io_bazel_rules_go//proto:go_grpc" - - // wellKnownTypesGoPrefix is the import path for the Go repository containing - // pre-generated code for the Well Known Types. - wellKnownTypesGoPrefix = "github.com/golang/protobuf" - - // wellKnownTypesPkg is the package name for the predefined WKTs in rules_go. - wellKnownTypesPkg = "proto/wkt" ) diff --git a/language/go/fileinfo.go b/language/go/fileinfo.go index 0ac43bee5..7f6671d67 100644 --- a/language/go/fileinfo.go +++ b/language/go/fileinfo.go @@ -34,7 +34,6 @@ import ( "github.com/bazelbuild/bazel-gazelle/config" "github.com/bazelbuild/bazel-gazelle/internal/version" - "github.com/bazelbuild/bazel-gazelle/language/proto" "github.com/bazelbuild/bazel-gazelle/rule" ) @@ -52,12 +51,6 @@ type fileInfo struct { // "_test" suffix if it was present. It is empty for non-Go files. packageName string - // importPath is the canonical import path for this file's package. - // This may be read from a package comment (in Go) or a go_package - // option (in proto). This field is empty for files that don't specify - // an import path. - importPath string - // isTest is true if the file stem (the part before the extension) // ends with "_test.go". This is never true for non-Go files. isTest bool @@ -542,8 +535,10 @@ func expandSrcDir(str string, srcdir string) (string, bool) { // See golang.org/issue/6038. // The @ is for OS X. See golang.org/issue/13720. // The % is for Jenkins. See golang.org/issue/16959. -const safeString = "+-.,/0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz:$@%" -const safeSpaces = " " +const ( + safeString = "+-.,/0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz:$@%" + safeSpaces = " " +) var safeBytes = []byte(safeSpaces + safeString) @@ -631,9 +626,7 @@ func isOSArchSpecific(info fileInfo, cgoTags tagLine) (osSpecific, archSpecific for _, line := range lines { for _, group := range line { for _, tag := range group { - if strings.HasPrefix(tag, "!") { - tag = tag[1:] - } + tag = strings.TrimPrefix(tag, "!") _, osOk := rule.KnownOSSet[tag] if osOk { osSpecific = true @@ -760,42 +753,6 @@ func isIgnoredTag(tag string) bool { return true } -// protoFileInfo extracts metadata from a proto file. The proto extension -// already "parses" these and stores metadata in proto.FileInfo, so this is -// just processing relevant options. -func protoFileInfo(path_ string, protoInfo proto.FileInfo) fileInfo { - info := fileNameInfo(path_) - - // Look for "option go_package". If there's no / in the package option, then - // it's just a simple package name, not a full import path. - for _, opt := range protoInfo.Options { - if opt.Key != "go_package" { - continue - } - if strings.LastIndexByte(opt.Value, '/') == -1 { - info.packageName = opt.Value - } else { - if i := strings.LastIndexByte(opt.Value, ';'); i != -1 { - info.importPath = opt.Value[:i] - info.packageName = opt.Value[i+1:] - } else { - info.importPath = opt.Value - info.packageName = path.Base(opt.Value) - } - } - } - - // Set the Go package name from the proto package name if there was no - // option go_package. - if info.packageName == "" && protoInfo.PackageName != "" { - info.packageName = strings.Replace(protoInfo.PackageName, ".", "_", -1) - } - - info.imports = protoInfo.Imports - info.hasServices = protoInfo.HasServices - return info -} - // parseGoEmbed parses the text following "//go:embed" to extract the glob patterns. // It accepts unquoted space-separated patterns as well as double-quoted and back-quoted Go strings. // This is based on a similar function in cmd/compile/internal/gc/noder.go; diff --git a/language/go/fileinfo_go_test.go b/language/go/fileinfo_go_test.go index 81856cc96..e9a468fda 100644 --- a/language/go/fileinfo_go_test.go +++ b/language/go/fileinfo_go_test.go @@ -160,7 +160,7 @@ var src string } defer os.RemoveAll(dir) path := filepath.Join(dir, tc.name) - if err := ioutil.WriteFile(path, []byte(tc.source), 0600); err != nil { + if err := ioutil.WriteFile(path, []byte(tc.source), 0o600); err != nil { t.Fatal(err) } @@ -193,7 +193,7 @@ func TestGoFileInfoFailure(t *testing.T) { defer os.RemoveAll(dir) name := "foo_linux_amd64.go" path := filepath.Join(dir, name) - if err := ioutil.WriteFile(path, []byte("pakcage foo"), 0600); err != nil { + if err := ioutil.WriteFile(path, []byte("pakcage foo"), 0o600); err != nil { t.Fatal(err) } @@ -316,7 +316,7 @@ import ("C") defer os.RemoveAll(dir) name := "TestCgo.go" path := filepath.Join(dir, name) - if err := ioutil.WriteFile(path, []byte(tc.source), 0600); err != nil { + if err := ioutil.WriteFile(path, []byte(tc.source), 0o600); err != nil { t.Fatal(err) } @@ -377,7 +377,7 @@ func TestExpandSrcDirRepoRelative(t *testing.T) { t.Fatal(err) } sub := filepath.Join(repo, "sub") - if err := os.Mkdir(sub, 0755); err != nil { + if err := os.Mkdir(sub, 0o755); err != nil { t.Fatal(err) } goFile := filepath.Join(sub, "sub.go") @@ -388,7 +388,7 @@ func TestExpandSrcDirRepoRelative(t *testing.T) { */ import "C" `) - if err := ioutil.WriteFile(goFile, content, 0644); err != nil { + if err := ioutil.WriteFile(goFile, content, 0o644); err != nil { t.Fatal(err) } c, _, _ := testConfig( diff --git a/language/go/fileinfo_test.go b/language/go/fileinfo_test.go index 348cd2492..241ca058e 100644 --- a/language/go/fileinfo_test.go +++ b/language/go/fileinfo_test.go @@ -46,7 +46,7 @@ func TestOtherFileInfo(t *testing.T) { }, } { t.Run(tc.desc, func(t *testing.T) { - if err := ioutil.WriteFile(tc.name, []byte(tc.source), 0600); err != nil { + if err := ioutil.WriteFile(tc.name, []byte(tc.source), 0o600); err != nil { t.Fatal(err) } defer os.Remove(tc.name) @@ -240,7 +240,8 @@ func TestFileNameInfo(t *testing.T) { fileInfo{ ext: unknownExt, }, - }, { + }, + { "hidden file", ".foo.go", fileInfo{ @@ -324,7 +325,7 @@ package main`, if err = f.Close(); err != nil { t.Fatal(err) } - if err = ioutil.WriteFile(path, []byte(tc.source), 0600); err != nil { + if err = ioutil.WriteFile(path, []byte(tc.source), 0o600); err != nil { t.Fatal(err) } @@ -519,7 +520,7 @@ import "C" } path := filepath.Join(dir, filename) - if err := ioutil.WriteFile(path, []byte(content), 0666); err != nil { + if err := ioutil.WriteFile(path, []byte(content), 0o666); err != nil { t.Fatal(err) } diff --git a/language/go/fix.go b/language/go/fix.go index 0cadfdc5a..2407c1942 100644 --- a/language/go/fix.go +++ b/language/go/fix.go @@ -24,7 +24,7 @@ import ( bzl "github.com/bazelbuild/buildtools/build" ) -func (_ *goLang) Fix(c *config.Config, f *rule.File) { +func (*goLang) Fix(c *config.Config, f *rule.File) { migrateLibraryEmbed(c, f) migrateGrpcCompilers(c, f) flattenSrcs(c, f) diff --git a/language/go/fix_test.go b/language/go/fix_test.go index 24e4ce981..a0bd4f7e2 100644 --- a/language/go/fix_test.go +++ b/language/go/fix_test.go @@ -62,7 +62,8 @@ go_test( embed = [":foo"], ) `, - }, { + }, + { desc: "go_naming_convention=go_default_library -> import for bin", namingConvention: importNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -103,7 +104,8 @@ go_test( embed = [":foo_lib"], ) `, - }, { + }, + { desc: "go_naming_convention=go_default_library -> import conflict", namingConvention: importNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -146,7 +148,8 @@ go_test( embed = [":go_default_library"], ) `, - }, { + }, + { desc: "go_naming_convention=import -> go_default_library for lib", namingConvention: goDefaultLibraryNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -177,7 +180,8 @@ go_test( embed = [":go_default_library"], ) `, - }, { + }, + { desc: "go_naming_convention=import -> go_default_library for bin", namingConvention: goDefaultLibraryNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -218,7 +222,8 @@ go_test( embed = [":go_default_library"], ) `, - }, { + }, + { desc: "go_naming_convention=go_default_library -> import_alias for lib", namingConvention: importAliasNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -251,7 +256,8 @@ go_test( embed = [":foo"], ) `, - }, { + }, + { desc: "go_naming_convention=import_alias -> go_default_library for lib", namingConvention: goDefaultLibraryNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -282,7 +288,8 @@ go_test( embed = [":go_default_library"], ) `, - }, { + }, + { desc: "go_naming_convention=go_default_library -> import_alias for bin", namingConvention: importAliasNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -323,7 +330,8 @@ go_test( embed = [":foo_lib"], ) `, - }, { + }, + { desc: "go_naming_convention=import -> import_alias for lib", namingConvention: importAliasNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -354,7 +362,8 @@ go_test( embed = [":foo"], ) `, - }, { + }, + { desc: "go_naming_convention import_alias -> import for lib", namingConvention: importNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -385,7 +394,8 @@ go_test( embed = [":foo"], ) `, - }, { + }, + { desc: "go_naming_convention=import -> import for lib", namingConvention: importNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -416,7 +426,8 @@ go_test( embed = [":foo"], ) `, - }, { + }, + { desc: "go_naming_convention go_default_library -> go_default_library for lib", namingConvention: goDefaultLibraryNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -449,7 +460,8 @@ go_test( embed = [":go_default_library"], ) `, - }, { + }, + { desc: "go_naming_convention=import_alias -> import_alias for lib", namingConvention: importAliasNamingConvention, old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -480,7 +492,8 @@ go_test( embed = [":foo"], ) `, - }, { + }, + { // migrateLibraryEmbed tests desc: "library migrated to embed", old: `load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") @@ -509,7 +522,8 @@ go_test( embed = [":go_default_library"], ) `, - }, { + }, + { // verifies #211 desc: "other library not migrated", old: ` @@ -699,7 +713,8 @@ go_library( ) # after comment `, - }, { + }, + { desc: "cgo_library merged with go_library", old: `load("@io_bazel_rules_go//go:def.bzl", "go_library") @@ -773,7 +788,8 @@ go_test( srcs = ["x_test.go"], ) `, - }, { + }, + { desc: "squash xtest", old: `load("@io_bazel_rules_go//go:def.bzl", "go_test") diff --git a/language/go/generate.go b/language/go/generate.go index 0b578e6f7..ac389e64e 100644 --- a/language/go/generate.go +++ b/language/go/generate.go @@ -404,7 +404,10 @@ func emptyPackage(c *config.Config, dir, rel string, f *rule.File) *goPackage { dir: dir, rel: rel, } - pkg.inferImportPath(c) + if err := pkg.inferImportPath(c); err != nil { + log.Printf("could not infer import path: %v", err) + } + return pkg } diff --git a/language/go/generate_test.go b/language/go/generate_test.go index 0581ba318..ea447eac9 100644 --- a/language/go/generate_test.go +++ b/language/go/generate_test.go @@ -65,7 +65,8 @@ func TestGenerateRules(t *testing.T) { RegularFiles: regularFiles, GenFiles: genFiles, OtherEmpty: empty, - OtherGen: gen}) + OtherGen: gen, + }) empty = append(empty, res.Empty...) gen = append(gen, res.Gen...) } @@ -110,7 +111,8 @@ func TestGenerateRulesEmpty(t *testing.T) { res := goLang.GenerateRules(language.GenerateArgs{ Config: c, Dir: "./foo", - Rel: "foo"}) + Rel: "foo", + }) if len(res.Gen) > 0 { t.Errorf("got %d generated rules; want 0", len(res.Gen)) } @@ -142,7 +144,8 @@ func TestGenerateRulesEmptyLegacyProto(t *testing.T) { res := goLang.GenerateRules(language.GenerateArgs{ Config: c, Dir: "./foo", - Rel: "foo"}) + Rel: "foo", + }) for _, e := range res.Empty { if kind := e.Kind(); kind == "proto_library" || kind == "go_proto_library" || kind == "go_grpc_library" { t.Errorf("deleted rule %s ; should not delete in legacy proto mode", kind) @@ -169,7 +172,8 @@ proto_library( Dir: "./foo", Rel: "foo", File: old, - OtherEmpty: empty}) + OtherEmpty: empty, + }) empty = append(empty, res.Empty...) } f := rule.EmptyFile("test", "") diff --git a/language/go/kinds.go b/language/go/kinds.go index 11a72a0b0..2dc6519f7 100644 --- a/language/go/kinds.go +++ b/language/go/kinds.go @@ -190,5 +190,5 @@ var goLoads = []rule.LoadInfo{ }, } -func (_ *goLang) Kinds() map[string]rule.KindInfo { return goKinds } -func (_ *goLang) Loads() []rule.LoadInfo { return goLoads } +func (*goLang) Kinds() map[string]rule.KindInfo { return goKinds } +func (*goLang) Loads() []rule.LoadInfo { return goLoads } diff --git a/language/go/lang.go b/language/go/lang.go index 7542f2191..23e845f58 100644 --- a/language/go/lang.go +++ b/language/go/lang.go @@ -59,12 +59,12 @@ const goName = "go" type goLang struct { // goPkgDirs is a set of relative paths to directories containing buildable - // Go code. If the value is false, it means the directory does not contain + // Go code. If the value is false, it means the directory does not contain // buildable Go code, but it has a subdir which does. goPkgRels map[string]bool } -func (_ *goLang) Name() string { return goName } +func (*goLang) Name() string { return goName } func NewLanguage() language.Language { return &goLang{goPkgRels: make(map[string]bool)} diff --git a/language/go/modules.go b/language/go/modules.go index 643a1da36..2aa1eae66 100644 --- a/language/go/modules.go +++ b/language/go/modules.go @@ -42,8 +42,8 @@ func importReposFromModules(args language.ImportReposArgs) language.ImportReposR // dependencies. type module struct { Path, Version, Sum, Error string - Main bool - Replace *struct { + Main bool + Replace *struct { Path, Version string } } diff --git a/language/go/resolve.go b/language/go/resolve.go index c6d3393f7..afa66fe9d 100644 --- a/language/go/resolve.go +++ b/language/go/resolve.go @@ -21,7 +21,6 @@ import ( "go/build" "log" "path" - "regexp" "strings" "github.com/bazelbuild/bazel-gazelle/config" @@ -32,7 +31,7 @@ import ( "github.com/bazelbuild/bazel-gazelle/rule" ) -func (_ *goLang) Imports(_ *config.Config, r *rule.Rule, f *rule.File) []resolve.ImportSpec { +func (*goLang) Imports(_ *config.Config, r *rule.Rule, f *rule.File) []resolve.ImportSpec { if !isGoLibrary(r.Kind()) || isExtraLibrary(r) { return nil } @@ -46,7 +45,7 @@ func (_ *goLang) Imports(_ *config.Config, r *rule.Rule, f *rule.File) []resolve } } -func (_ *goLang) Embeds(r *rule.Rule, from label.Label) []label.Label { +func (*goLang) Embeds(r *rule.Rule, from label.Label) []label.Label { embedStrings := r.AttrStrings("embed") if isGoProtoLibrary(r.Kind()) { embedStrings = append(embedStrings, r.AttrString("proto")) @@ -79,7 +78,7 @@ func (gl *goLang) Resolve(c *config.Config, ix *resolve.RuleIndex, rc *repo.Remo } deps, errs := imports.Map(func(imp string) (string, error) { l, err := resolve(c, ix, rc, imp, from) - if err == skipImportError { + if err == errSkipImport { return "", nil } else if err != nil { return "", err @@ -108,8 +107,8 @@ func (gl *goLang) Resolve(c *config.Config, ix *resolve.RuleIndex, rc *repo.Remo } var ( - skipImportError = errors.New("std or self import") - notFoundError = errors.New("rule not found") + errSkipImport = errors.New("std or self import") + errNotFound = errors.New("rule not found") ) // ResolveGo resolves a Go import path to a Bazel label, possibly using the @@ -129,16 +128,16 @@ func ResolveGo(c *config.Config, ix *resolve.RuleIndex, rc *repo.RemoteCache, im } if IsStandard(imp) { - return label.NoLabel, skipImportError + return label.NoLabel, errSkipImport } if l, ok := resolve.FindRuleWithOverride(c, resolve.ImportSpec{Lang: "go", Imp: imp}, "go"); ok { return l, nil } - if l, err := resolveWithIndexGo(c, ix, imp, from); err == nil || err == skipImportError { + if l, err := resolveWithIndexGo(c, ix, imp, from); err == nil || err == errSkipImport { return l, err - } else if err != notFoundError { + } else if err != errNotFound { return label.NoLabel, err } @@ -167,7 +166,7 @@ func ResolveGo(c *config.Config, ix *resolve.RuleIndex, rc *repo.RemoteCache, im if gc.depMode == vendorMode { return resolveVendored(gc, imp) } - var resolveFn func (string) (string, string, error) + var resolveFn func(string) (string, string, error) if gc.depMode == staticMode { resolveFn = rc.RootStatic } else if gc.moduleMode || pathWithoutSemver(imp) != "" { @@ -205,8 +204,6 @@ func resolveWithIndexGo(c *config.Config, ix *resolve.RuleIndex, imp string, fro break } } - if isVendored { - } if isVendored && !label.New(m.Label.Repo, vendorRoot, "").Contains(from) { // vendor directory not visible continue @@ -229,22 +226,20 @@ func resolveWithIndexGo(c *config.Config, ix *resolve.RuleIndex, imp string, fro return label.NoLabel, matchError } if bestMatch.Label.Equal(label.NoLabel) { - return label.NoLabel, notFoundError + return label.NoLabel, errNotFound } if bestMatch.IsSelfImport(from) { - return label.NoLabel, skipImportError + return label.NoLabel, errSkipImport } return bestMatch.Label, nil } -var modMajorRex = regexp.MustCompile(`/v\d+(?:/|$)`) - func resolveToExternalLabel(c *config.Config, resolveFn func(string) (string, string, error), imp string) (label.Label, error) { prefix, repo, err := resolveFn(imp) if err != nil { return label.NoLabel, err } else if prefix == "" && repo == "" { - return label.NoLabel, skipImportError + return label.NoLabel, errSkipImport } var pkg string @@ -290,16 +285,16 @@ func resolveVendored(gc *goConfig, imp string) (label.Label, error) { func resolveProto(c *config.Config, ix *resolve.RuleIndex, rc *repo.RemoteCache, imp string, from label.Label) (label.Label, error) { if wellKnownProtos[imp] { - return label.NoLabel, skipImportError + return label.NoLabel, errSkipImport } if l, ok := resolve.FindRuleWithOverride(c, resolve.ImportSpec{Lang: "proto", Imp: imp}, "go"); ok { return l, nil } - if l, err := resolveWithIndexProto(c, ix, imp, from); err == nil || err == skipImportError { + if l, err := resolveWithIndexProto(c, ix, imp, from); err == nil || err == errSkipImport { return l, err - } else if err != notFoundError { + } else if err != errNotFound { return label.NoLabel, err } @@ -340,13 +335,13 @@ var wellKnownProtos = map[string]bool{ func resolveWithIndexProto(c *config.Config, ix *resolve.RuleIndex, imp string, from label.Label) (label.Label, error) { matches := ix.FindRulesByImportWithConfig(c, resolve.ImportSpec{Lang: "proto", Imp: imp}, "go") if len(matches) == 0 { - return label.NoLabel, notFoundError + return label.NoLabel, errNotFound } if len(matches) > 1 { return label.NoLabel, fmt.Errorf("multiple rules (%s and %s) may be imported with %q from %s", matches[0].Label, matches[1].Label, imp, from) } if matches[0].IsSelfImport(from) { - return label.NoLabel, skipImportError + return label.NoLabel, errSkipImport } return matches[0].Label, nil } diff --git a/language/go/resolve_test.go b/language/go/resolve_test.go index 0b8042564..c17657e1a 100644 --- a/language/go/resolve_test.go +++ b/language/go/resolve_test.go @@ -199,7 +199,8 @@ go_library( ) `, }}, - old: buildFile{content: ` + old: buildFile{ + content: ` go_binary( name = "bin", _imports = ["example.com/foo"], @@ -354,7 +355,8 @@ go_binary( `, }, { desc: "skip_self_embed", - old: buildFile{content: ` + old: buildFile{ + content: ` go_library( name = "go_default_library", srcs = ["lib.go"], @@ -1222,14 +1224,14 @@ func TestResolveExternal(t *testing.T) { Name: "custom_repo", GoPrefix: "example.com/repo", }}, - depMode: staticMode, - want: "@custom_repo//v2/foo:go_default_library", + depMode: staticMode, + want: "@custom_repo//v2/foo:go_default_library", }, { desc: "static_mode_unknown", importpath: "example.com/repo/v2/foo", depMode: staticMode, want: "", - }, + }, } { t.Run(tc.desc, func(t *testing.T) { gc.depMode = tc.depMode diff --git a/language/go/testdata/cgolib_with_build_tags/pure_linux.go b/language/go/testdata/cgolib_with_build_tags/pure_linux.go index b7b54bfd1..6da909163 100644 --- a/language/go/testdata/cgolib_with_build_tags/pure_linux.go +++ b/language/go/testdata/cgolib_with_build_tags/pure_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux /* Copyright 2016 The Bazel Authors. All rights reserved. diff --git a/language/go/testdata/cgolib_with_build_tags/pure_other.go b/language/go/testdata/cgolib_with_build_tags/pure_other.go index df84717bc..bf799e4ea 100644 --- a/language/go/testdata/cgolib_with_build_tags/pure_other.go +++ b/language/go/testdata/cgolib_with_build_tags/pure_other.go @@ -1,3 +1,4 @@ +//go:build !linux // +build !linux /* Copyright 2016 The Bazel Authors. All rights reserved. diff --git a/language/go/testdata/gen_and_exclude/gen_static_ignore.go b/language/go/testdata/gen_and_exclude/gen_static_ignore.go index 59b37a566..304a6eebc 100644 --- a/language/go/testdata/gen_and_exclude/gen_static_ignore.go +++ b/language/go/testdata/gen_and_exclude/gen_static_ignore.go @@ -1,3 +1,4 @@ +//go:build ignore // +build ignore package gen_and_exclude diff --git a/language/go/testdata/lib/relativeimporter/importer.go b/language/go/testdata/lib/relativeimporter/importer.go index 5463d9794..2046843ab 100644 --- a/language/go/testdata/lib/relativeimporter/importer.go +++ b/language/go/testdata/lib/relativeimporter/importer.go @@ -13,9 +13,8 @@ limitations under the License. package relativeimporter import ( - "log" - "../internal/deep" + "log" ) func think() { diff --git a/language/go/testdata/naming_convention/import/bin/main.go b/language/go/testdata/naming_convention/import/bin/main.go index a535e5a57..34c06efac 100644 --- a/language/go/testdata/naming_convention/import/bin/main.go +++ b/language/go/testdata/naming_convention/import/bin/main.go @@ -17,6 +17,7 @@ package main import ( "fmt" + "example.com/repo/naming_convention/import/bin" ) diff --git a/language/go/testdata/naming_convention/import_alias/bin/main.go b/language/go/testdata/naming_convention/import_alias/bin/main.go index d1f370bb3..9d096c120 100644 --- a/language/go/testdata/naming_convention/import_alias/bin/main.go +++ b/language/go/testdata/naming_convention/import_alias/bin/main.go @@ -17,6 +17,7 @@ package main import ( "fmt" + "example.com/repo/naming_convention/import_alias/bin" ) diff --git a/language/go/testdata/platforms/generic_test.go b/language/go/testdata/platforms/generic_test.go index 13eef5ed0..62e3e7c12 100644 --- a/language/go/testdata/platforms/generic_test.go +++ b/language/go/testdata/platforms/generic_test.go @@ -1,3 +1,3 @@ package platforms_test -import _ "example.com/repo/platforms" \ No newline at end of file +import _ "example.com/repo/platforms" diff --git a/language/go/testdata/platforms/ignored.go b/language/go/testdata/platforms/ignored.go index 432038c61..7b26df180 100644 --- a/language/go/testdata/platforms/ignored.go +++ b/language/go/testdata/platforms/ignored.go @@ -1,3 +1,4 @@ +//go:build ignore // +build ignore package platforms diff --git a/language/go/testdata/platforms/no_cgo.go b/language/go/testdata/platforms/no_cgo.go index 766d870c0..4b62955c3 100644 --- a/language/go/testdata/platforms/no_cgo.go +++ b/language/go/testdata/platforms/no_cgo.go @@ -1,3 +1,4 @@ +//go:build !cgo // +build !cgo package platforms diff --git a/language/go/testdata/platforms/release.go b/language/go/testdata/platforms/release.go index 8c70fd698..0fc4220c5 100644 --- a/language/go/testdata/platforms/release.go +++ b/language/go/testdata/platforms/release.go @@ -1,3 +1,4 @@ +//go:build go1.7 || !go1.8 // +build go1.7 !go1.8 package platforms diff --git a/language/go/testdata/platforms/suffix_linux_test.go b/language/go/testdata/platforms/suffix_linux_test.go index 13eef5ed0..62e3e7c12 100644 --- a/language/go/testdata/platforms/suffix_linux_test.go +++ b/language/go/testdata/platforms/suffix_linux_test.go @@ -1,3 +1,3 @@ package platforms_test -import _ "example.com/repo/platforms" \ No newline at end of file +import _ "example.com/repo/platforms" diff --git a/language/go/testdata/platforms/tag_a.go b/language/go/testdata/platforms/tag_a.go index aac0f22ec..67d447ba1 100644 --- a/language/go/testdata/platforms/tag_a.go +++ b/language/go/testdata/platforms/tag_a.go @@ -1,3 +1,4 @@ -//+build amd64 +//go:build amd64 +// +build amd64 package platforms diff --git a/language/go/testdata/platforms/tag_d.go b/language/go/testdata/platforms/tag_d.go index 9dfe3ac17..c8f8f97f7 100644 --- a/language/go/testdata/platforms/tag_d.go +++ b/language/go/testdata/platforms/tag_d.go @@ -1,4 +1,5 @@ -//+build darwin +//go:build darwin +// +build darwin package platforms diff --git a/language/go/testdata/platforms/tag_l.go b/language/go/testdata/platforms/tag_l.go index b4da61190..a7266fede 100644 --- a/language/go/testdata/platforms/tag_l.go +++ b/language/go/testdata/platforms/tag_l.go @@ -1,4 +1,5 @@ -//+build linux +//go:build linux +// +build linux package platforms diff --git a/language/go/update_import_test.go b/language/go/update_import_test.go index bc620094c..69769fcbd 100644 --- a/language/go/update_import_test.go +++ b/language/go/update_import_test.go @@ -30,10 +30,10 @@ import ( func TestImports(t *testing.T) { for _, tc := range []struct { - desc, want string - wantErr string + desc, want string + wantErr string stubGoModDownload func(string, []string) ([]byte, error) - files []testtools.FileSpec + files []testtools.FileSpec }{ { desc: "dep", @@ -103,7 +103,7 @@ go_repository( importpath = "golang.org/x/net", ) `, - wantErr: "", + wantErr: "", stubGoModDownload: nil, }, { desc: "modules", @@ -225,7 +225,7 @@ go_repository( version = "v0.0.0-20190122202912-9c309ee22fab", ) `, - wantErr: "", + wantErr: "", stubGoModDownload: nil, }, { desc: "modules-with-error", @@ -246,7 +246,7 @@ require ( `, }, }, - want: "", + want: "", wantErr: "failed to download\nError downloading definitely.doesnotexist/ever: Did not exist", stubGoModDownload: func(dir string, args []string) ([]byte, error) { return []byte(`{ @@ -339,7 +339,7 @@ go_repository( importpath = "github.com/golang/protobuf", ) `, - wantErr: "", + wantErr: "", stubGoModDownload: nil, }, } { diff --git a/language/proto/config.go b/language/proto/config.go index c86eddd41..62b768890 100644 --- a/language/proto/config.go +++ b/language/proto/config.go @@ -184,7 +184,7 @@ func (f *modeFlag) String() string { return mode.String() } -func (_ *protoLang) RegisterFlags(fs *flag.FlagSet, cmd string, c *config.Config) { +func (*protoLang) RegisterFlags(fs *flag.FlagSet, cmd string, c *config.Config) { pc := &ProtoConfig{} c.Exts[protoName] = pc @@ -196,15 +196,15 @@ func (_ *protoLang) RegisterFlags(fs *flag.FlagSet, cmd string, c *config.Config fs.StringVar(&pc.ImportPrefix, "proto_import_prefix", "", "When set, .proto source files in the srcs attribute of the rule are accessible at their path with this prefix appended on.") } -func (_ *protoLang) CheckFlags(fs *flag.FlagSet, c *config.Config) error { +func (*protoLang) CheckFlags(fs *flag.FlagSet, c *config.Config) error { return nil } -func (_ *protoLang) KnownDirectives() []string { +func (*protoLang) KnownDirectives() []string { return []string{"proto", "proto_group", "proto_strip_import_prefix", "proto_import_prefix"} } -func (_ *protoLang) Configure(c *config.Config, rel string, f *rule.File) { +func (*protoLang) Configure(c *config.Config, rel string, f *rule.File) { pc := &ProtoConfig{} *pc = *GetProtoConfig(c) c.Exts[protoName] = pc diff --git a/language/proto/config_test.go b/language/proto/config_test.go index 158dbea37..783f4d58c 100644 --- a/language/proto/config_test.go +++ b/language/proto/config_test.go @@ -18,17 +18,17 @@ package proto import "testing" func TestCheckStripImportPrefix(t *testing.T) { - testCases := []struct{ + testCases := []struct { name, prefix, rel, wantErr string }{ { - name: "not in directory", - prefix: "/example.com/idl", - rel: "example.com", + name: "not in directory", + prefix: "/example.com/idl", + rel: "example.com", wantErr: `proto_strip_import_prefix "/example.com/idl" not in directory example.com`, }, { - name: "strip prefix at root", + name: "strip prefix at root", prefix: "/include", }, } diff --git a/language/proto/fileinfo.go b/language/proto/fileinfo.go index ee4eab0a8..a76d642e8 100644 --- a/language/proto/fileinfo.go +++ b/language/proto/fileinfo.go @@ -106,7 +106,7 @@ func buildProtoRegexp() *regexp.Regexp { importStmt := `\bimport\s*(?:public|weak)?\s*(?P` + strLit + `)\s*;` packageStmt := `\bpackage\s*(?P` + fullIdent + `)\s*;` optionStmt := `\boption\s*(?P` + fullIdent + `)\s*=\s*(?P` + strLit + `)\s*;` - serviceStmt := `(?Pservice\s*`+ ident +`\s*{)` + serviceStmt := `(?Pservice\s*` + ident + `\s*{)` comment := `//[^\n]*` protoReSrc := strings.Join([]string{importStmt, packageStmt, optionStmt, serviceStmt, comment}, "|") return regexp.MustCompile(protoReSrc) diff --git a/language/proto/fileinfo_test.go b/language/proto/fileinfo_test.go index 61d2137e9..6065cd0d3 100644 --- a/language/proto/fileinfo_test.go +++ b/language/proto/fileinfo_test.go @@ -112,8 +112,8 @@ import "second.proto";`, HasServices: true, }, }, { - desc: "service as name", - name: "service.proto", + desc: "service as name", + name: "service.proto", proto: `message ServiceAccount { string service = 1; }`, want: FileInfo{ HasServices: false, @@ -126,7 +126,7 @@ import "second.proto";`, t.Fatal(err) } defer os.RemoveAll(dir) - if err := ioutil.WriteFile(filepath.Join(dir, tc.name), []byte(tc.proto), 0600); err != nil { + if err := ioutil.WriteFile(filepath.Join(dir, tc.name), []byte(tc.proto), 0o600); err != nil { t.Fatal(err) } diff --git a/language/proto/fix.go b/language/proto/fix.go index c8e67bf8f..0a5be372b 100644 --- a/language/proto/fix.go +++ b/language/proto/fix.go @@ -20,5 +20,5 @@ import ( "github.com/bazelbuild/bazel-gazelle/rule" ) -func (_ *protoLang) Fix(c *config.Config, f *rule.File) { +func (*protoLang) Fix(c *config.Config, f *rule.File) { } diff --git a/language/proto/gen/gen_known_imports.go b/language/proto/gen/gen_known_imports.go index 2004af5bf..843d48357 100644 --- a/language/proto/gen/gen_known_imports.go +++ b/language/proto/gen/gen_known_imports.go @@ -80,7 +80,9 @@ func run(args []string) (err error) { fs.StringVar(&var_, "var", "", "var name in generated file") fs.IntVar(&keyColumn, "key", 0, "key column number") fs.IntVar(&valueColumn, "value", 1, "value column number") - fs.Parse(args) + if err = fs.Parse(args); err != nil { + return fmt.Errorf("invalid flag: %v", err) + } if protoCsvPath == "" { return fmt.Errorf("-proto_csv not set") } @@ -136,7 +138,7 @@ func run(args []string) (err error) { if err != nil { return err } - if err := ioutil.WriteFile(knownImportsPath, knownImportsData, 0666); err != nil { + if err := ioutil.WriteFile(knownImportsPath, knownImportsData, 0o666); err != nil { return err } diff --git a/language/proto/gen/update_proto_csv.go b/language/proto/gen/update_proto_csv.go index 79636c8bf..4e82d67c6 100644 --- a/language/proto/gen/update_proto_csv.go +++ b/language/proto/gen/update_proto_csv.go @@ -1,3 +1,4 @@ +//go:build ignore // +build ignore /* Copyright 2018 The Bazel Authors. All rights reserved. @@ -90,7 +91,7 @@ func main() { log.Fatal("either -com_google_googleapis or -go_googleapis must be set") } - if err := ioutil.WriteFile(*protoCsvPath, protoContent.Bytes(), 0666); err != nil { + if err := ioutil.WriteFile(*protoCsvPath, protoContent.Bytes(), 0o666); err != nil { log.Fatal(err) } } diff --git a/language/proto/generate.go b/language/proto/generate.go index afa0cbec3..74dfb8a7c 100644 --- a/language/proto/generate.go +++ b/language/proto/generate.go @@ -28,7 +28,7 @@ import ( "github.com/bazelbuild/bazel-gazelle/rule" ) -func (_ *protoLang) GenerateRules(args language.GenerateArgs) language.GenerateResult { +func (*protoLang) GenerateRules(args language.GenerateArgs) language.GenerateResult { c := args.Config pc := GetProtoConfig(c) if !pc.Mode.ShouldGenerateRules() { diff --git a/language/proto/generate_test.go b/language/proto/generate_test.go index 7798c0b3f..c4fdfe398 100644 --- a/language/proto/generate_test.go +++ b/language/proto/generate_test.go @@ -66,7 +66,8 @@ func TestGenerateRules(t *testing.T) { File: oldFile, Subdirs: subdirs, RegularFiles: regularFiles, - GenFiles: genFiles}) + GenFiles: genFiles, + }) if len(res.Empty) > 0 { t.Errorf("got %d empty rules; want 0", len(res.Empty)) } @@ -123,7 +124,8 @@ proto_library( Config: c, Rel: "foo", File: old, - GenFiles: genFiles}) + GenFiles: genFiles, + }) if len(res.Gen) > 0 { t.Errorf("got %d generated rules; want 0", len(res.Gen)) } @@ -156,7 +158,8 @@ func TestGeneratePackage(t *testing.T) { Config: c, Dir: dir, Rel: "protos", - RegularFiles: []string{"foo.proto"}}) + RegularFiles: []string{"foo.proto"}, + }) r := res.Gen[0] got := r.PrivateAttr(PackageKey).(Package) want := Package{ @@ -209,7 +212,8 @@ func TestFileModeImports(t *testing.T) { Config: c, Dir: dir, Rel: "file_mode", - RegularFiles: []string{"foo.proto", "bar.proto"}}) + RegularFiles: []string{"foo.proto", "bar.proto"}, + }) if len(res.Gen) != 2 { t.Error("expected 2 generated packages") diff --git a/language/proto/kinds.go b/language/proto/kinds.go index 319f5ffcb..f9e5db09d 100644 --- a/language/proto/kinds.go +++ b/language/proto/kinds.go @@ -39,5 +39,5 @@ var protoLoads = []rule.LoadInfo{ }, } -func (_ *protoLang) Kinds() map[string]rule.KindInfo { return protoKinds } -func (_ *protoLang) Loads() []rule.LoadInfo { return protoLoads } +func (*protoLang) Kinds() map[string]rule.KindInfo { return protoKinds } +func (*protoLang) Loads() []rule.LoadInfo { return protoLoads } diff --git a/language/proto/known_go_imports.go b/language/proto/known_go_imports.go index 21a472cc0..82f1007fb 100644 --- a/language/proto/known_go_imports.go +++ b/language/proto/known_go_imports.go @@ -6,7 +6,6 @@ package proto import "github.com/bazelbuild/bazel-gazelle/label" var knownGoProtoImports = map[string]label.Label{ - "github.com/golang/protobuf/ptypes/any": label.New("io_bazel_rules_go", "proto/wkt", "any_go_proto"), "google.golang.org/genproto/protobuf/api": label.New("io_bazel_rules_go", "proto/wkt", "api_go_proto"), "github.com/golang/protobuf/protoc-gen-go/plugin": label.New("io_bazel_rules_go", "proto/wkt", "compiler_plugin_go_proto"), diff --git a/language/proto/known_imports.go b/language/proto/known_imports.go index 2abc06ebb..2bc26dbe5 100644 --- a/language/proto/known_imports.go +++ b/language/proto/known_imports.go @@ -6,7 +6,6 @@ package proto import "github.com/bazelbuild/bazel-gazelle/label" var knownImports = map[string]label.Label{ - "google/protobuf/any.proto": label.New("com_google_protobuf", "", "any_proto"), "google/protobuf/api.proto": label.New("com_google_protobuf", "", "api_proto"), "google/protobuf/compiler/plugin.proto": label.New("com_google_protobuf", "", "compiler_plugin_proto"), diff --git a/language/proto/known_proto_imports.go b/language/proto/known_proto_imports.go index 7f41af1b8..f4d78a081 100644 --- a/language/proto/known_proto_imports.go +++ b/language/proto/known_proto_imports.go @@ -6,7 +6,6 @@ package proto import "github.com/bazelbuild/bazel-gazelle/label" var knownProtoImports = map[string]label.Label{ - "google/protobuf/any.proto": label.New("io_bazel_rules_go", "proto/wkt", "any_go_proto"), "google/protobuf/api.proto": label.New("io_bazel_rules_go", "proto/wkt", "api_go_proto"), "google/protobuf/compiler/plugin.proto": label.New("io_bazel_rules_go", "proto/wkt", "compiler_plugin_go_proto"), diff --git a/language/proto/lang.go b/language/proto/lang.go index fe009df88..df0358b55 100644 --- a/language/proto/lang.go +++ b/language/proto/lang.go @@ -65,7 +65,7 @@ const protoName = "proto" type protoLang struct{} -func (_ *protoLang) Name() string { return protoName } +func (*protoLang) Name() string { return protoName } func NewLanguage() language.Language { return &protoLang{} diff --git a/language/proto/resolve.go b/language/proto/resolve.go index abc99ee33..6458a5638 100644 --- a/language/proto/resolve.go +++ b/language/proto/resolve.go @@ -31,7 +31,7 @@ import ( "github.com/bazelbuild/bazel-gazelle/rule" ) -func (_ *protoLang) Imports(c *config.Config, r *rule.Rule, f *rule.File) []resolve.ImportSpec { +func (*protoLang) Imports(c *config.Config, r *rule.Rule, f *rule.File) []resolve.ImportSpec { rel := f.Pkg srcs := r.AttrStrings("srcs") imports := make([]resolve.ImportSpec, len(srcs)) @@ -70,11 +70,11 @@ func (_ *protoLang) Imports(c *config.Config, r *rule.Rule, f *rule.File) []reso return imports } -func (_ *protoLang) Embeds(r *rule.Rule, from label.Label) []label.Label { +func (*protoLang) Embeds(r *rule.Rule, from label.Label) []label.Label { return nil } -func (_ *protoLang) Resolve(c *config.Config, ix *resolve.RuleIndex, rc *repo.RemoteCache, r *rule.Rule, importsRaw interface{}, from label.Label) { +func (*protoLang) Resolve(c *config.Config, ix *resolve.RuleIndex, rc *repo.RemoteCache, r *rule.Rule, importsRaw interface{}, from label.Label) { if importsRaw == nil { // may not be set in tests. return @@ -84,7 +84,7 @@ func (_ *protoLang) Resolve(c *config.Config, ix *resolve.RuleIndex, rc *repo.Re depSet := make(map[string]bool) for _, imp := range imports { l, err := resolveProto(c, ix, r, imp, from) - if err == skipImportError { + if err == errSkipImport { continue } else if err != nil { log.Print(err) @@ -104,8 +104,8 @@ func (_ *protoLang) Resolve(c *config.Config, ix *resolve.RuleIndex, rc *repo.Re } var ( - skipImportError = errors.New("std import") - notFoundError = errors.New("not found") + errSkipImport = errors.New("std import") + errNotFound = errors.New("not found") ) func resolveProto(c *config.Config, ix *resolve.RuleIndex, r *rule.Rule, imp string, from label.Label) (label.Label, error) { @@ -120,15 +120,15 @@ func resolveProto(c *config.Config, ix *resolve.RuleIndex, r *rule.Rule, imp str if l, ok := knownImports[imp]; ok && pc.Mode.ShouldUseKnownImports() { if l.Equal(from) { - return label.NoLabel, skipImportError + return label.NoLabel, errSkipImport } else { return l, nil } } - if l, err := resolveWithIndex(c, ix, imp, from); err == nil || err == skipImportError { + if l, err := resolveWithIndex(c, ix, imp, from); err == nil || err == errSkipImport { return l, err - } else if err != notFoundError { + } else if err != errNotFound { return label.NoLabel, err } @@ -143,19 +143,19 @@ func resolveProto(c *config.Config, ix *resolve.RuleIndex, r *rule.Rule, imp str func resolveWithIndex(c *config.Config, ix *resolve.RuleIndex, imp string, from label.Label) (label.Label, error) { matches := ix.FindRulesByImportWithConfig(c, resolve.ImportSpec{Lang: "proto", Imp: imp}, "proto") if len(matches) == 0 { - return label.NoLabel, notFoundError + return label.NoLabel, errNotFound } if len(matches) > 1 { return label.NoLabel, fmt.Errorf("multiple rules (%s and %s) may be imported with %q from %s", matches[0].Label, matches[1].Label, imp, from) } if matches[0].IsSelfImport(from) { - return label.NoLabel, skipImportError + return label.NoLabel, errSkipImport } return matches[0].Label, nil } // CrossResolve provides dependency resolution logic for the go language extension. -func (_ *protoLang) CrossResolve(c *config.Config, ix *resolve.RuleIndex, imp resolve.ImportSpec, lang string) []resolve.FindResult { +func (*protoLang) CrossResolve(c *config.Config, ix *resolve.RuleIndex, imp resolve.ImportSpec, lang string) []resolve.FindResult { if lang != "go" { return nil } diff --git a/merger/fix.go b/merger/fix.go index bb54b0344..128050c73 100644 --- a/merger/fix.go +++ b/merger/fix.go @@ -60,26 +60,26 @@ func FixLoads(f *rule.File, knownLoads []rule.LoadInfo) { // Make a map of all the symbols from known files used in this file. usedSymbols := make(map[string]map[string]bool) bzl.Walk(f.File, func(x bzl.Expr, stk []bzl.Expr) { - ce, ok := x.(*bzl.CallExpr) - if !ok { - return - } - - id, ok := ce.X.(*bzl.Ident) - if !ok { - return - } - - file, ok := knownSymbols[id.Name] - if !ok || otherLoadedKinds[id.Name] { - return - } - - if usedSymbols[file] == nil { - usedSymbols[file] = make(map[string]bool) - } - usedSymbols[file][id.Name] = true - }) + ce, ok := x.(*bzl.CallExpr) + if !ok { + return + } + + id, ok := ce.X.(*bzl.Ident) + if !ok { + return + } + + file, ok := knownSymbols[id.Name] + if !ok || otherLoadedKinds[id.Name] { + return + } + + if usedSymbols[file] == nil { + usedSymbols[file] = make(map[string]bool) + } + usedSymbols[file][id.Name] = true + }) // Fix the load statements. The order is important, so we iterate over // knownLoads instead of knownFiles. diff --git a/merger/merger_test.go b/merger/merger_test.go index a665db785..3988b8bd0 100644 --- a/merger/merger_test.go +++ b/merger/merger_test.go @@ -109,7 +109,8 @@ go_test( data = glob(["testdata/*"]), embed = [":go_default_library"], ) -`}, { +`, + }, { desc: "merge dicts", previous: ` load("@io_bazel_rules_go//go:def.bzl", "go_library") diff --git a/repo/remote.go b/repo/remote.go index 5bb142622..d44b566b8 100644 --- a/repo/remote.go +++ b/repo/remote.go @@ -108,7 +108,7 @@ type modValue struct { } type modVersionValue struct { - path, name, version, sum string + path, version, sum string } // Repo describes details of a Go repository known in advance. It is used to @@ -200,7 +200,7 @@ func (r *RemoteCache) cleanup() error { return os.RemoveAll(r.tmpDir) } -var gopkginPattern = regexp.MustCompile("^(gopkg.in/(?:[^/]+/)?[^/]+\\.v\\d+)(?:/|$)") +var gopkginPattern = regexp.MustCompile(`^(gopkg.in/(?:[^/]+/)?[^/]+\.v\d+)(?:/|$)`) var knownPrefixes = []struct { prefix string @@ -563,7 +563,7 @@ func (rc *RemoteCache) initTmp() { if rc.tmpErr != nil { return } - rc.tmpErr = ioutil.WriteFile(filepath.Join(rc.tmpDir, "go.mod"), []byte("module gazelle_remote_cache\ngo 1.15\n"), 0666) + rc.tmpErr = ioutil.WriteFile(filepath.Join(rc.tmpDir, "go.mod"), []byte("module gazelle_remote_cache\ngo 1.15\n"), 0o666) }) } diff --git a/repo/repo.go b/repo/repo.go index 9efa2315c..4c9843de1 100644 --- a/repo/repo.go +++ b/repo/repo.go @@ -35,12 +35,6 @@ import ( const gazelleFromDirectiveKey = "_gazelle_from_directive" -type byRuleName []*rule.Rule - -func (s byRuleName) Len() int { return len(s) } -func (s byRuleName) Less(i, j int) bool { return s[i].Name() < s[j].Name() } -func (s byRuleName) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - // FindExternalRepo attempts to locate the directory where Bazel has fetched // the external repository with the given name. An error is returned if the // repository directory cannot be located. diff --git a/repo/repo_test.go b/repo/repo_test.go index 332d63730..837ddc6f2 100644 --- a/repo/repo_test.go +++ b/repo/repo_test.go @@ -46,17 +46,17 @@ func TestFindExternalRepo(t *testing.T) { name := "foo" externalPath := filepath.Join(dir, "bazel", "output-base", "external", name) - if err := os.MkdirAll(externalPath, 0777); err != nil { + if err := os.MkdirAll(externalPath, 0o777); err != nil { t.Fatal(err) } bazelOutPath := filepath.Join(dir, "bazel", "output-base", "execroot", "test", "bazel-out") - if err := os.MkdirAll(bazelOutPath, 0777); err != nil { + if err := os.MkdirAll(bazelOutPath, 0o777); err != nil { t.Fatal(err) } workspacePath := filepath.Join(dir, "workspace") - if err := os.MkdirAll(workspacePath, 0777); err != nil { + if err := os.MkdirAll(workspacePath, 0o777); err != nil { t.Fatal(err) } if err := os.Symlink(bazelOutPath, filepath.Join(workspacePath, "bazel-out")); err != nil { @@ -175,7 +175,8 @@ def foo_repositories(): remote = "https://example.com/foo", importpath = "example.com/foo", ) -`}, { +`, + }, { Path: "repos2.bzl", Content: ` def bar_repositories(): @@ -195,7 +196,8 @@ def baz_repositories(): remote = "https://example.com/ignored", importpath = "example.com/ignored", ) -`}} +`, + }} dir, cleanup := testtools.CreateFiles(t, files) defer cleanup() workspaceString := ` @@ -238,7 +240,8 @@ def go_repositories(): importpath = "example.com/go", ) -`}, { +`, + }, { Path: "repos2.bzl", Content: ` def bar_repositories(): @@ -256,7 +259,8 @@ def alias_repositories(): remote = "https://example.com/alias", importpath = "example.com/alias", ) -`}} +`, + }} dir, cleanup := testtools.CreateFiles(t, files) defer cleanup() workspaceString := ` diff --git a/resolve/config.go b/resolve/config.go index 8b34e99aa..98b738f1f 100644 --- a/resolve/config.go +++ b/resolve/config.go @@ -64,17 +64,17 @@ func getResolveConfig(c *config.Config) *resolveConfig { type Configurer struct{} -func (_ *Configurer) RegisterFlags(fs *flag.FlagSet, cmd string, c *config.Config) { +func (*Configurer) RegisterFlags(fs *flag.FlagSet, cmd string, c *config.Config) { c.Exts[resolveName] = &resolveConfig{} } -func (_ *Configurer) CheckFlags(fs *flag.FlagSet, c *config.Config) error { return nil } +func (*Configurer) CheckFlags(fs *flag.FlagSet, c *config.Config) error { return nil } -func (_ *Configurer) KnownDirectives() []string { +func (*Configurer) KnownDirectives() []string { return []string{"resolve"} } -func (_ *Configurer) Configure(c *config.Config, rel string, f *rule.File) { +func (*Configurer) Configure(c *config.Config, rel string, f *rule.File) { rc := getResolveConfig(c) rcCopy := &resolveConfig{ overrides: rc.overrides[:len(rc.overrides):len(rc.overrides)], diff --git a/rule/platform.go b/rule/platform.go index d402953fb..18275d306 100644 --- a/rule/platform.go +++ b/rule/platform.go @@ -97,8 +97,8 @@ var KnownPlatforms = []Platform{ } var OSAliases = map[string][]string{ - "android": []string{"linux"}, - "ios": []string{"darwin"}, + "android": {"linux"}, + "ios": {"darwin"}, } var ( diff --git a/rule/rule.go b/rule/rule.go index 644c6b7d1..9678bd3fc 100644 --- a/rule/rule.go +++ b/rule/rule.go @@ -406,7 +406,7 @@ func (f *File) SortMacro() { func (f *File) Save(path string) error { f.Sync() f.Content = bzl.Format(f.File) - return ioutil.WriteFile(path, f.Content, 0666) + return ioutil.WriteFile(path, f.Content, 0o666) } // HasDefaultVisibility returns whether the File contains a "package" rule with diff --git a/rule/rule_test.go b/rule/rule_test.go index 6a788baab..9c84c3ddf 100644 --- a/rule/rule_test.go +++ b/rule/rule_test.go @@ -363,7 +363,7 @@ func TestShouldKeepExpr(t *testing.T) { } func TestInternalVisibility(t *testing.T) { - var tests = []struct { + tests := []struct { rel string expected string }{ diff --git a/testtools/files.go b/testtools/files.go index eb9c6315d..df650f80e 100644 --- a/testtools/files.go +++ b/testtools/files.go @@ -76,13 +76,13 @@ func CreateFiles(t *testing.T, files []FileSpec) (dir string, cleanup func()) { } path := filepath.Join(dir, filepath.FromSlash(f.Path)) if strings.HasSuffix(f.Path, "/") { - if err := os.MkdirAll(path, 0700); err != nil { + if err := os.MkdirAll(path, 0o700); err != nil { os.RemoveAll(dir) t.Fatal(err) } continue } - if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { os.RemoveAll(dir) t.Fatal(err) } @@ -92,7 +92,7 @@ func CreateFiles(t *testing.T, files []FileSpec) (dir string, cleanup func()) { } continue } - if err := ioutil.WriteFile(path, []byte(f.Content), 0600); err != nil { + if err := ioutil.WriteFile(path, []byte(f.Content), 0o600); err != nil { os.RemoveAll(dir) t.Fatal(err) } @@ -196,7 +196,11 @@ func TestGazelleGenerationOnPath(t *testing.T, args *TestGazelleGenerationArgs) var goldens []FileSpec config := &testConfig{} - filepath.WalkDir(args.TestDataPathAbsolute, func(path string, d fs.DirEntry, err error) error { + f := func(path string, d fs.DirEntry, err error) error { + if err != nil { + t.Fatalf("File walk error on path %q. Error: %v", path, err) + } + shortPath := strings.TrimPrefix(path, args.TestDataPathAbsolute) info, err := d.Info() @@ -257,7 +261,10 @@ func TestGazelleGenerationOnPath(t *testing.T, args *TestGazelleGenerationArgs) }) } return nil - }) + } + if err := filepath.WalkDir(args.TestDataPathAbsolute, f); err != nil { + t.Fatal(err) + } testdataDir, cleanup := CreateFiles(t, inputs) workspaceRoot := filepath.Join(testdataDir, args.Name) @@ -278,7 +285,7 @@ func TestGazelleGenerationOnPath(t *testing.T, args *TestGazelleGenerationArgs) updateExpectedConfig(t, config.Stderr, redactWorkspacePath(stderr.String(), workspaceRoot), srcTestDirectory, expectedStderrFilename) updateExpectedConfig(t, fmt.Sprintf("%d", config.ExitCode), fmt.Sprintf("%d", actualExitCode), srcTestDirectory, expectedExitCodeFilename) - filepath.Walk(testdataDir, func(walkedPath string, info os.FileInfo, err error) error { + err := filepath.Walk(testdataDir, func(walkedPath string, info os.FileInfo, err error) error { if err != nil { return err } @@ -301,6 +308,9 @@ func TestGazelleGenerationOnPath(t *testing.T, args *TestGazelleGenerationArgs) t.Logf("%q exists in %v", relativePath, testdataDir) return nil }) + if err != nil { + t.Fatalf("Failed to walk file: %v", err) + } } else { t.Logf(` @@ -392,7 +402,7 @@ func updateExpectedConfig(t *testing.T, expected string, actual string, srcTestD if expected != actual { destFile := path.Join(srcTestDirectory, expectedFilename) - err := os.WriteFile(destFile, []byte(actual), 0644) + err := os.WriteFile(destFile, []byte(actual), 0o644) if err != nil { t.Fatalf("Failed to write file %v. Error: %v\n", destFile, err) } diff --git a/walk/config.go b/walk/config.go index 72945acaa..bd59cb688 100644 --- a/walk/config.go +++ b/walk/config.go @@ -66,15 +66,15 @@ func (wc *walkConfig) isExcluded(rel, base string) bool { type Configurer struct{} -func (_ *Configurer) RegisterFlags(fs *flag.FlagSet, cmd string, c *config.Config) { +func (*Configurer) RegisterFlags(fs *flag.FlagSet, cmd string, c *config.Config) { wc := &walkConfig{} c.Exts[walkName] = wc fs.Var(&gzflag.MultiFlag{Values: &wc.excludes}, "exclude", "pattern that should be ignored (may be repeated)") } -func (_ *Configurer) CheckFlags(fs *flag.FlagSet, c *config.Config) error { return nil } +func (*Configurer) CheckFlags(fs *flag.FlagSet, c *config.Config) error { return nil } -func (_ *Configurer) KnownDirectives() []string { +func (*Configurer) KnownDirectives() []string { return []string{"exclude", "follow", "ignore"} } diff --git a/walk/config_test.go b/walk/config_test.go index bc3bedaa2..fbe343a6b 100644 --- a/walk/config_test.go +++ b/walk/config_test.go @@ -11,7 +11,6 @@ func TestCheckPathMatchPattern(t *testing.T) { pattern string err error }{ - {pattern: "*.pb.go", err: nil}, {pattern: "**/*.pb.go", err: nil}, {pattern: "**/*.pb.go", err: nil}, diff --git a/walk/walk_test.go b/walk/walk_test.go index c102ec5ad..1cb38b083 100644 --- a/walk/walk_test.go +++ b/walk/walk_test.go @@ -474,11 +474,11 @@ type testConfigurer struct { configure func(c *config.Config, rel string, f *rule.File) } -func (_ *testConfigurer) RegisterFlags(_ *flag.FlagSet, _ string, _ *config.Config) {} +func (*testConfigurer) RegisterFlags(_ *flag.FlagSet, _ string, _ *config.Config) {} -func (_ *testConfigurer) CheckFlags(_ *flag.FlagSet, _ *config.Config) error { return nil } +func (*testConfigurer) CheckFlags(_ *flag.FlagSet, _ *config.Config) error { return nil } -func (_ *testConfigurer) KnownDirectives() []string { return nil } +func (*testConfigurer) KnownDirectives() []string { return nil } func (tc *testConfigurer) Configure(c *config.Config, rel string, f *rule.File) { tc.configure(c, rel, f)