github.com/mweagle/Sparta@v1.15.0/cmd/insertTags/main.go (about)

     1  // Reading and writing files are basic tasks needed for
     2  // many Go programs. First we'll look at some examples of
     3  // reading files.
     4  
     5  package main
     6  
     7  import (
     8  	"fmt"
     9  	"io/ioutil"
    10  	"os"
    11  	"path/filepath"
    12  	"strings"
    13  )
    14  
    15  func main() {
    16  	targetFile := os.Args[1]
    17  	tags := os.Args[2:]
    18  
    19  	// go run tries to compile the targetfile if it has the .go extension, so
    20  	// we don't provide that on the command line and append it here.
    21  	targetFile = fmt.Sprintf("%s.go", targetFile)
    22  
    23  	absPath, err := filepath.Abs(targetFile)
    24  	if nil != err {
    25  		panic(err)
    26  	}
    27  	/* #nosec */
    28  	fileContents, err := ioutil.ReadFile(absPath)
    29  	if nil != err {
    30  		panic(err)
    31  	}
    32  	tagString := strings.Join(tags, " ")
    33  	fmt.Printf("Prepending tags: %s\n", tagString)
    34  
    35  	// Include the #nosec directive to have gas ignore
    36  	// the ignored error returns
    37  	// https://github.com/GoASTScanner/gas
    38  	updatedContents := fmt.Sprintf(`// +build %s
    39  
    40  //lint:file-ignore U1000,ST1018 Ignore all unused code, it's generated
    41  /* #nosec */
    42  %s`,
    43  		tagString,
    44  		fileContents)
    45  	err = ioutil.WriteFile(absPath, []byte(updatedContents), 0600)
    46  	if nil != err {
    47  		panic(err)
    48  	}
    49  }