github.com/daixiang0/gci@v0.13.0/internal/generate.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"go/format"
     6  	"os"
     7  	"runtime"
     8  	"strings"
     9  	"text/template"
    10  
    11  	"golang.org/x/tools/go/packages"
    12  )
    13  
    14  //go:generate go run .
    15  
    16  const outputFile = "../pkg/section/standard_list.go"
    17  
    18  const stdTemplate = `
    19  package section
    20  
    21  // Code generated based on {{ .Version }}. DO NOT EDIT.
    22  
    23  var standardPackages = map[string]struct{}{
    24  {{- range $pkg := .Packages }}
    25  		"{{ $pkg }}":  {},
    26  {{- end}}
    27  }
    28  
    29  `
    30  
    31  func main() {
    32  	err := generate()
    33  	if err != nil {
    34  		panic(err)
    35  	}
    36  }
    37  
    38  func generate() error {
    39  	all, err := packages.Load(nil, "std")
    40  	if err != nil {
    41  		return err
    42  	}
    43  
    44  	var pkgs []string
    45  
    46  	// go list std | grep -v vendor | grep -v internal
    47  	for _, pkg := range all {
    48  		if !strings.Contains(pkg.PkgPath, "internal") && !strings.Contains(pkg.PkgPath, "vendor") {
    49  			pkgs = append(pkgs, pkg.PkgPath)
    50  		}
    51  	}
    52  
    53  	file, err := os.Create(outputFile)
    54  	if err != nil {
    55  		return err
    56  	}
    57  
    58  	models := map[string]interface{}{
    59  		"Packages": pkgs,
    60  		"Version":  runtime.Version(),
    61  	}
    62  
    63  	tlt, err := template.New("std-packages").Parse(stdTemplate)
    64  	if err != nil {
    65  		return err
    66  	}
    67  
    68  	b := &bytes.Buffer{}
    69  
    70  	err = tlt.Execute(b, models)
    71  	if err != nil {
    72  		return err
    73  	}
    74  
    75  	// gofmt
    76  	source, err := format.Source(b.Bytes())
    77  	if err != nil {
    78  		return err
    79  	}
    80  
    81  	_, err = file.Write(source)
    82  	if err != nil {
    83  		return err
    84  	}
    85  
    86  	return nil
    87  }