blob: dbe5b49a9f34fa81906578c7be8333a74bb8cec6 [file] [log] [blame]
Heschi Kreinick757ca712019-05-06 15:37:46 -04001// Package imports implements a Go pretty-printer (like package "go/format")
2// that also adds or removes import statements as necessary.
3package imports // import "golang.org/x/tools/imports"
4
5import (
6 "go/build"
Heschi Kreinick5bcca832020-02-28 17:03:27 -05007 "log"
Heschi Kreinick621d4ee2019-12-16 18:04:38 -05008 "os"
Heschi Kreinick757ca712019-05-06 15:37:46 -04009
10 intimp "golang.org/x/tools/internal/imports"
11)
12
13// Options specifies options for processing files.
14type Options struct {
15 Fragment bool // Accept fragment of a source file (no package statement)
16 AllErrors bool // Report all errors (not just the first 10 on different lines)
17
18 Comments bool // Print comments (true if nil *Options provided)
19 TabIndent bool // Use tabs for indent (true if nil *Options provided)
20 TabWidth int // Tab width (8 if nil *Options provided)
21
22 FormatOnly bool // Disable the insertion and deletion of imports
23}
24
25// Debug controls verbose logging.
26var Debug = false
27
28// LocalPrefix is a comma-separated string of import path prefixes, which, if
29// set, instructs Process to sort the import paths with the given prefixes
30// into another group after 3rd-party packages.
31var LocalPrefix string
32
33// Process formats and adjusts imports for the provided file.
34// If opt is nil the defaults are used.
35//
36// Note that filename's directory influences which imports can be chosen,
37// so it is important that filename be accurate.
38// To process data ``as if'' it were in filename, pass the data as a non-nil src.
39func Process(filename string, src []byte, opt *Options) ([]byte, error) {
Heschi Kreinick26647e32019-05-20 18:00:48 -040040 if opt == nil {
41 opt = &Options{Comments: true, TabIndent: true, TabWidth: 8}
42 }
Heschi Kreinick757ca712019-05-06 15:37:46 -040043 intopt := &intimp.Options{
44 Env: &intimp.ProcessEnv{
45 GOPATH: build.Default.GOPATH,
46 GOROOT: build.Default.GOROOT,
Heschi Kreinick621d4ee2019-12-16 18:04:38 -050047 GOFLAGS: os.Getenv("GOFLAGS"),
48 GO111MODULE: os.Getenv("GO111MODULE"),
49 GOPROXY: os.Getenv("GOPROXY"),
50 GOSUMDB: os.Getenv("GOSUMDB"),
Heschi Kreinick757ca712019-05-06 15:37:46 -040051 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 }
Heschi Kreinick5bcca832020-02-28 17:03:27 -050060 if Debug {
61 intopt.Env.Logf = log.Printf
62 }
Heschi Kreinick757ca712019-05-06 15:37:46 -040063 return intimp.Process(filename, src, intopt)
64}
65
66// VendorlessPath returns the devendorized version of the import path ipath.
67// For example, VendorlessPath("foo/bar/vendor/a/b") returns "a/b".
68func VendorlessPath(ipath string) string {
69 return intimp.VendorlessPath(ipath)
70}