Source file src/cmd/fix/buildtag.go

     1  // Copyright 2020 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"go/ast"
     9  	"strings"
    10  )
    11  
    12  func init() {
    13  	register(buildtagFix)
    14  }
    15  
    16  const buildtagGoVersionCutoff = 1_18
    17  
    18  var buildtagFix = fix{
    19  	name: "buildtag",
    20  	date: "2021-08-25",
    21  	f:    buildtag,
    22  	desc: `Remove +build comments from modules using Go 1.18 or later`,
    23  }
    24  
    25  func buildtag(f *ast.File) bool {
    26  	if goVersion < buildtagGoVersionCutoff {
    27  		return false
    28  	}
    29  
    30  	// File is already gofmt-ed, so we know that if there are +build lines,
    31  	// they are in a comment group that starts with a //go:build line followed
    32  	// by a blank line. While we cannot delete comments from an AST and
    33  	// expect consistent output in general, this specific case - deleting only
    34  	// some lines from a comment block - does format correctly.
    35  	fixed := false
    36  	for _, g := range f.Comments {
    37  		sawGoBuild := false
    38  		for i, c := range g.List {
    39  			if strings.HasPrefix(c.Text, "//go:build ") {
    40  				sawGoBuild = true
    41  			}
    42  			if sawGoBuild && strings.HasPrefix(c.Text, "// +build ") {
    43  				g.List = g.List[:i]
    44  				fixed = true
    45  				break
    46  			}
    47  		}
    48  	}
    49  
    50  	return fixed
    51  }
    52  

View as plain text