github.com/jackie-feng/tools@v0.0.0-20191231093943-4ebd680984ae/imports/forward.go (about)

     1  // Package imports implements a Go pretty-printer (like package "go/format")
     2  // that also adds or removes import statements as necessary.
     3  package imports // import "github.com/jackie-feng/tools/imports"
     4  
     5  import (
     6  	"go/build"
     7  	"os"
     8  
     9  	intimp "github.com/jackie-feng/tools/internal/imports"
    10  )
    11  
    12  // Options specifies options for processing files.
    13  type Options struct {
    14  	Fragment  bool // Accept fragment of a source file (no package statement)
    15  	AllErrors bool // Report all errors (not just the first 10 on different lines)
    16  
    17  	Comments  bool // Print comments (true if nil *Options provided)
    18  	TabIndent bool // Use tabs for indent (true if nil *Options provided)
    19  	TabWidth  int  // Tab width (8 if nil *Options provided)
    20  
    21  	FormatOnly bool // Disable the insertion and deletion of imports
    22  }
    23  
    24  // Debug controls verbose logging.
    25  var Debug = false
    26  
    27  // LocalPrefix is a comma-separated string of import path prefixes, which, if
    28  // set, instructs Process to sort the import paths with the given prefixes
    29  // into another group after 3rd-party packages.
    30  var LocalPrefix string
    31  
    32  // Process formats and adjusts imports for the provided file.
    33  // If opt is nil the defaults are used.
    34  //
    35  // Note that filename's directory influences which imports can be chosen,
    36  // so it is important that filename be accurate.
    37  // To process data ``as if'' it were in filename, pass the data as a non-nil src.
    38  func Process(filename string, src []byte, opt *Options) ([]byte, error) {
    39  	if opt == nil {
    40  		opt = &Options{Comments: true, TabIndent: true, TabWidth: 8}
    41  	}
    42  	intopt := &intimp.Options{
    43  		Env: &intimp.ProcessEnv{
    44  			GOPATH:      build.Default.GOPATH,
    45  			GOROOT:      build.Default.GOROOT,
    46  			GOFLAGS:     os.Getenv("GOFLAGS"),
    47  			GO111MODULE: os.Getenv("GO111MODULE"),
    48  			GOPROXY:     os.Getenv("GOPROXY"),
    49  			GOSUMDB:     os.Getenv("GOSUMDB"),
    50  			Debug:       Debug,
    51  			LocalPrefix: LocalPrefix,
    52  		},
    53  		AllErrors:  opt.AllErrors,
    54  		Comments:   opt.Comments,
    55  		FormatOnly: opt.FormatOnly,
    56  		Fragment:   opt.Fragment,
    57  		TabIndent:  opt.TabIndent,
    58  		TabWidth:   opt.TabWidth,
    59  	}
    60  	return intimp.Process(filename, src, intopt)
    61  }
    62  
    63  // VendorlessPath returns the devendorized version of the import path ipath.
    64  // For example, VendorlessPath("foo/bar/vendor/a/b") returns "a/b".
    65  func VendorlessPath(ipath string) string {
    66  	return intimp.VendorlessPath(ipath)
    67  }