You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.3 KiB

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