Skip to content

Commit 21563e4

Browse files
authored
nogo: enable strings modern analyzers (#11558)
This PR enable a few "strings*" analyzers in the new modern package of x/tools to help us migrate our code to newer+better Go syntax. It will also prevent future style violations by enforcing through rules_go's nogo The PR is split into 3 commits: - Enable the analyzers (rules/go/analyzer/def.bzl) - Apply all the style fixes - Manual fixes
1 parent 3fc9a7c commit 21563e4

File tree

70 files changed

+323
-293
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

70 files changed

+323
-293
lines changed

cli/arg/arg.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,8 @@ func Find(args []string, desiredArg string) (value string, index int, length int
5959
return args[i+1], i, 2
6060
}
6161
// Handle "--name=value" form
62-
if strings.HasPrefix(arg, prefix) {
63-
return strings.TrimPrefix(arg, prefix), i, 1
62+
if after, ok := strings.CutPrefix(arg, prefix); ok {
63+
return after, i, 1
6464
}
6565
}
6666
return "", -1, 0

cli/cmd/sidecar/sidecar.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -116,8 +116,8 @@ func initializeEnv() *real_environment.RealEnv {
116116
func initializeGRPCServer(env *real_environment.RealEnv) (*grpc.Server, net.Listener) {
117117
var lis net.Listener
118118
var err error
119-
if strings.HasPrefix(*listenAddr, "unix://") {
120-
sockPath := strings.TrimPrefix(*listenAddr, "unix://")
119+
if after, ok := strings.CutPrefix(*listenAddr, "unix://"); ok {
120+
sockPath := after
121121
lis, err = net.Listen("unix", sockPath)
122122
} else {
123123
lis, err = net.Listen("tcp", *listenAddr)
@@ -142,7 +142,7 @@ func initializeGRPCServer(env *real_environment.RealEnv) (*grpc.Server, net.List
142142
func registerBESProxy(env *real_environment.RealEnv, grpcServer *grpc.Server) {
143143
buildEventProxyClients := make([]pepb.PublishBuildEventClient, 0)
144144
targets := make([]string, 0)
145-
for _, besBE := range strings.Split(*besBackend, ",") {
145+
for besBE := range strings.SplitSeq(*besBackend, ",") {
146146
besTarget := normalizeGrpcTarget(besBE)
147147
targets = append(targets, besTarget)
148148
buildEventProxyClients = append(buildEventProxyClients, build_event_proxy.NewBuildEventProxyClient(env, besTarget, *besSynchronous))

cli/config/config.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,8 +142,8 @@ func ParseDiskCapacityBytes(size any, directory string) (int64, error) {
142142
case int64:
143143
return v, nil
144144
case string:
145-
if strings.HasSuffix(v, "%") {
146-
percentage, err := strconv.Atoi(strings.TrimSuffix(v, "%"))
145+
if before, ok := strings.CutSuffix(v, "%"); ok {
146+
percentage, err := strconv.Atoi(before)
147147
if err != nil {
148148
return 0, fmt.Errorf("parse percentage as int: %w", err)
149149
}

cli/explain/compactgraph/compactgraph.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,7 @@ func Diff(old, new *CompactGraph) (*spawn_diff.DiffResult, error) {
301301
invalidatedByPrimaryOutput[s.PrimaryOutputPath()] = struct{}{}
302302
}
303303
}
304-
for invalidatedBy, _ := range invalidatedByPrimaryOutput {
304+
for invalidatedBy := range invalidatedByPrimaryOutput {
305305
if invalidatingResultEntry, ok := diffResults.Load(invalidatedBy); ok {
306306
invalidatingResult := invalidatingResultEntry.(*diffResult)
307307
foundTransitiveCause = true
@@ -773,12 +773,12 @@ func diffRunfilesTrees(old, new *Spawn, oldResolveSymlinks, newResolveSymlinks f
773773
newMapping := newTree.ComputeMapping(workspaceRunfilesDirectory, hashFunction)
774774

775775
var oldOnly, newOnly []string
776-
for p, _ := range oldMapping {
776+
for p := range oldMapping {
777777
if _, ok := newMapping[p]; !ok {
778778
oldOnly = append(oldOnly, p)
779779
}
780780
}
781-
for p, _ := range newMapping {
781+
for p := range newMapping {
782782
if _, ok := oldMapping[p]; !ok {
783783
newOnly = append(newOnly, p)
784784
}

cli/fix/golang/golang.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,12 @@ func (g *Golang) ConsolidateDepFiles(deps map[string][]string) map[string][]stri
7272
return deps
7373
}
7474
if foundGoModFiles && len(goModFiles) > 1 {
75-
goWorkContents := "go " + defaultGoVersion + "\n"
75+
var goWorkContents strings.Builder
76+
goWorkContents.WriteString("go " + defaultGoVersion + "\n")
7677
for _, m := range goModFiles {
77-
goWorkContents += "use ./" + path.Dir(m) + "\n"
78+
goWorkContents.WriteString("use ./" + path.Dir(m) + "\n")
7879
}
79-
os.WriteFile(goWorkFileName, []byte(goWorkContents), 0777)
80+
os.WriteFile(goWorkFileName, []byte(goWorkContents.String()), 0777)
8081
delete(deps, goModFileName)
8182
}
8283
if foundGoWorkFiles && len(goWorkFiles) > 1 {

cli/help/help.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,8 @@ func HandleHelp(args parsed.Args) (exitCode int, err error) {
9494
// Match example "bazel help ..." commands in "Getting more help" section
9595
moreHelpPattern := regexp.MustCompile(`^(\s*)bazel( help\s+.*)$`)
9696
// Get help output lines with trailing newlines removed
97-
lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n")
98-
for _, line := range lines {
97+
lines := strings.SplitSeq(strings.TrimRight(buf.String(), "\n"), "\n")
98+
for line := range lines {
9999
line = strings.TrimRight(line, "\r")
100100

101101
if line == "Available commands:" {

cli/plugin/plugin.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,8 @@ func HandleInstall(args []string) (exitCode int, err error) {
145145

146146
func parsePluginSpec(spec, pathArg string) (*config.PluginConfig, error) {
147147
var repoSpec, versionSpec, pathSpec string
148-
if strings.HasPrefix(spec, ":") {
149-
pathSpec = strings.TrimPrefix(spec, ":")
148+
if after, ok := strings.CutPrefix(spec, ":"); ok {
149+
pathSpec = after
150150
} else {
151151
m := repoPattern.FindStringSubmatch(spec)
152152
if len(m) == 0 {

cli/record/record.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ func record(cmdArgs []string) (int, error) {
9292
log.Debugf("Starting recording session with invocation ID: %s", iid)
9393

9494
invocationURL := fmt.Sprintf("%s/invocation/%s", *resultsURL, iid)
95-
streamingLog := fmt.Sprintf(terminal.Esc(32) + "INFO:" + terminal.Esc() + fmt.Sprintf(" Streaming results to: %s", terminal.Esc(4, 34)+invocationURL+terminal.Esc()))
95+
streamingLog := terminal.Esc(32) + "INFO:" + terminal.Esc() + fmt.Sprintf(" Streaming results to: %s", terminal.Esc(4, 34)+invocationURL+terminal.Esc())
9696

9797
fmt.Fprintln(os.Stderr, streamingLog)
9898

cli/remotebazel/remotebazel.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ func determineRemote() (*gitRemote, error) {
168168
}
169169

170170
remotes := make([]*gitRemote, 0)
171-
for _, s := range strings.Split(remotesStr, "\n") {
171+
for s := range strings.SplitSeq(remotesStr, "\n") {
172172
s = strings.TrimSpace(s)
173173
if s == "" {
174174
continue
@@ -547,7 +547,7 @@ func generatePatches(baseCommit string) ([][]byte, error) {
547547
binaryFilesToExclude := make([]string, 0)
548548
binaryFiles := make([]string, 0)
549549
if modifiedFiles != "" {
550-
for _, mf := range strings.Split(modifiedFiles, "\n") {
550+
for mf := range strings.SplitSeq(modifiedFiles, "\n") {
551551
isBinary, err := isBinaryFile(mf)
552552
if err != nil {
553553
return nil, status.WrapError(err, "check binary file")
@@ -591,7 +591,7 @@ func generatePatches(baseCommit string) ([][]byte, error) {
591591
}
592592
untrackedFiles = strings.Trim(untrackedFiles, "\n")
593593
if untrackedFiles != "" {
594-
for _, uf := range strings.Split(untrackedFiles, "\n") {
594+
for uf := range strings.SplitSeq(untrackedFiles, "\n") {
595595
if strings.HasPrefix(uf, BuildBuddyArtifactDir+"/") {
596596
continue
597597
}
@@ -618,7 +618,7 @@ func splitLogBuffer(buf []byte) []string {
618618
var lines []string
619619

620620
termWidth := getTermWidth()
621-
for _, line := range strings.Split(string(buf), "\n") {
621+
for line := range strings.SplitSeq(string(buf), "\n") {
622622
for len(line) > termWidth {
623623
lines = append(lines, line[0:termWidth])
624624
line = line[termWidth:]

cli/sidecar/sidecar.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,8 +357,8 @@ func bytestreamURIPrefix(cacheTarget, instanceName string) string {
357357

358358
func stripProtocol(target string) string {
359359
for _, protocol := range []string{"grpc://", "grpcs://", "http://", "https://"} {
360-
if strings.HasPrefix(target, protocol) {
361-
return strings.TrimPrefix(target, protocol)
360+
if after, ok := strings.CutPrefix(target, protocol); ok {
361+
return after
362362
}
363363
}
364364
return target

0 commit comments

Comments
 (0)