1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package imports implements a Go pretty-printer (like package "go/format")
6 // that also adds or removes import statements as necessary.
7 package imports // import "golang.org/x/tools/imports"
13 "golang.org/x/tools/internal/gocommand"
14 intimp "golang.org/x/tools/internal/imports"
17 // Options specifies options for processing files.
19 Fragment bool // Accept fragment of a source file (no package statement)
20 AllErrors bool // Report all errors (not just the first 10 on different lines)
22 Comments bool // Print comments (true if nil *Options provided)
23 TabIndent bool // Use tabs for indent (true if nil *Options provided)
24 TabWidth int // Tab width (8 if nil *Options provided)
26 FormatOnly bool // Disable the insertion and deletion of imports
29 // Debug controls verbose logging.
32 // LocalPrefix is a comma-separated string of import path prefixes, which, if
33 // set, instructs Process to sort the import paths with the given prefixes
34 // into another group after 3rd-party packages.
35 var LocalPrefix string
37 // Process formats and adjusts imports for the provided file.
38 // If opt is nil the defaults are used, and if src is nil the source
39 // is read from the filesystem.
41 // Note that filename's directory influences which imports can be chosen,
42 // so it is important that filename be accurate.
43 // To process data ``as if'' it were in filename, pass the data as a non-nil src.
44 func Process(filename string, src []byte, opt *Options) ([]byte, error) {
47 src, err = ioutil.ReadFile(filename)
53 opt = &Options{Comments: true, TabIndent: true, TabWidth: 8}
55 intopt := &intimp.Options{
56 Env: &intimp.ProcessEnv{
57 GocmdRunner: &gocommand.Runner{},
59 LocalPrefix: LocalPrefix,
60 AllErrors: opt.AllErrors,
61 Comments: opt.Comments,
62 FormatOnly: opt.FormatOnly,
63 Fragment: opt.Fragment,
64 TabIndent: opt.TabIndent,
65 TabWidth: opt.TabWidth,
68 intopt.Env.Logf = log.Printf
70 return intimp.Process(filename, src, intopt)
73 // VendorlessPath returns the devendorized version of the import path ipath.
74 // For example, VendorlessPath("foo/bar/vendor/a/b") returns "a/b".
75 func VendorlessPath(ipath string) string {
76 return intimp.VendorlessPath(ipath)