imports: add Options.FormatOnly

Fixes golang/go#14500

Change-Id: Ied9d772e5f606ce6716193faa2c1a285f0ab00b9
Reviewed-on: https://go-review.googlesource.com/21532
Reviewed-by: Robert Griesemer <gri@golang.org>
This commit is contained in:
Brad Fitzpatrick 2016-04-05 16:10:15 +00:00
parent f2e4f834ec
commit 02e8ee6893
2 changed files with 36 additions and 5 deletions

View File

@ -19,8 +19,9 @@ import (
var only = flag.String("only", "", "If non-empty, the fix test to run") var only = flag.String("only", "", "If non-empty, the fix test to run")
var tests = []struct { var tests = []struct {
name string name string
in, out string formatOnly bool
in, out string
}{ }{
// Adding an import to an existing parenthesized import // Adding an import to an existing parenthesized import
{ {
@ -748,6 +749,31 @@ func main() { fmt.Println() }
import "fmt" import "fmt"
func main() { fmt.Println() } func main() { fmt.Println() }
`,
},
// FormatOnly
{
name: "format only",
formatOnly: true,
in: `package main
import (
"fmt"
"golang.org/x/foo"
)
func main() {}
`,
out: `package main
import (
"fmt"
"golang.org/x/foo"
)
func main() {}
`, `,
}, },
} }
@ -782,6 +808,7 @@ func TestFixImports(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
options.FormatOnly = tt.formatOnly
if *only != "" && tt.name != *only { if *only != "" && tt.name != *only {
continue continue
} }

View File

@ -31,6 +31,8 @@ type Options struct {
Comments bool // Print comments (true if nil *Options provided) Comments bool // Print comments (true if nil *Options provided)
TabIndent bool // Use tabs for indent (true if nil *Options provided) TabIndent bool // Use tabs for indent (true if nil *Options provided)
TabWidth int // Tab width (8 if nil *Options provided) TabWidth int // Tab width (8 if nil *Options provided)
FormatOnly bool // Disable the insertion and deletion of imports
} }
// Process formats and adjusts imports for the provided file. // Process formats and adjusts imports for the provided file.
@ -50,9 +52,11 @@ func Process(filename string, src []byte, opt *Options) ([]byte, error) {
return nil, err return nil, err
} }
_, err = fixImports(fileSet, file, filename) if !opt.FormatOnly {
if err != nil { _, err = fixImports(fileSet, file, filename)
return nil, err if err != nil {
return nil, err
}
} }
sortImports(fileSet, file) sortImports(fileSet, file)