Skip to content

Commit f7937d7

Browse files
committed
Add goimports option to simplify code like gofmt -s does
1 parent 9bbf122 commit f7937d7

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

cmd/goimports/goimports.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ func init() {
5454
flag.StringVar(&options.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
5555
flag.BoolVar(&options.FormatOnly, "format-only", false, "if true, don't fix imports and only format. In this mode, goimports is effectively gofmt, with the addition that imports are grouped into sections.")
5656
flag.BoolVar(&options.MergeAll, "merge-all", false, "if true, merge all imports into a single group")
57+
flag.BoolVar(&options.Simplify, "s", false, "if true, simplify code like gofmt -s does")
5758
}
5859

5960
func report(err error) {

internal/imports/fix_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2999,6 +2999,26 @@ import (
29992999
}.processTest(t, "golang.org/fake", "x.go", nil, &Options{MergeAll: true}, want)
30003000
}
30013001

3002+
func TestSimplify(t *testing.T) {
3003+
const input = `package main
3004+
3005+
var a = []foo{foo{}}
3006+
`
3007+
const want = `package main
3008+
3009+
var a = []foo{{}}
3010+
`
3011+
3012+
testConfig{
3013+
modules: []packagestest.Module{
3014+
{
3015+
Name: "golang.org/fake",
3016+
Files: fm{"x.go": input},
3017+
},
3018+
},
3019+
}.processTest(t, "golang.org/fake", "x.go", nil, &Options{Simplify: true}, want)
3020+
}
3021+
30023022
func TestSymbolSearchStarvation(t *testing.T) {
30033023
// This test verifies the fix for golang/go#67923: searching through
30043024
// candidates should not starve when the context is cancelled.

internal/imports/imports.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ type Options struct {
3636

3737
MergeAll bool // Merge all imports into a single group
3838

39+
Simplify bool // Simplify code like gofmt -s
40+
3941
Fragment bool // Accept fragment of a source file (no package statement)
4042
AllErrors bool // Report all errors (not just the first 10 on different lines)
4143

@@ -135,6 +137,10 @@ func formatFile(fset *token.FileSet, file *ast.File, src []byte, adjust func(ori
135137

136138
}
137139

140+
if opt.Simplify {
141+
simplify(file)
142+
}
143+
138144
printerMode := printer.UseSpaces
139145
if opt.TabIndent {
140146
printerMode |= printer.TabIndent

0 commit comments

Comments
 (0)