diff --git a/cmd/goimports/goimports.go b/cmd/goimports/goimports.go index 0ce85c9c328..8ea2be92b8e 100644 --- a/cmd/goimports/goimports.go +++ b/cmd/goimports/goimports.go @@ -48,6 +48,7 @@ var ( func init() { flag.BoolVar(&options.AllErrors, "e", false, "report all errors (not just the first 10 on different lines)") flag.StringVar(&imports.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list") + flag.BoolVar(&options.IgnoreGrouping, "ungroup", false, "ignore user's custom import grouping") } func report(err error) { diff --git a/imports/imports.go b/imports/imports.go index 717a6f3aa0d..bbfa2bc6899 100644 --- a/imports/imports.go +++ b/imports/imports.go @@ -36,6 +36,8 @@ type Options struct { TabWidth int // Tab width (8 if nil *Options provided) FormatOnly bool // Disable the insertion and deletion of imports + + IgnoreGrouping bool // Ignore user's custom import grouping } // Process formats and adjusts imports for the provided file. @@ -68,7 +70,7 @@ func Process(filename string, src []byte, opt *Options) ([]byte, error) { } } - sortImports(fileSet, file) + sortImports(fileSet, file, opt.IgnoreGrouping) imps := astutil.Imports(fileSet, file) var spacesBefore []string // import paths we need spaces before for _, impSection := range imps { @@ -85,7 +87,6 @@ func Process(filename string, src []byte, opt *Options) ([]byte, error) { } lastGroup = groupNum } - } printerMode := printer.UseSpaces diff --git a/imports/sortimports.go b/imports/sortimports.go index f3dd56c7a6f..c8a958ed754 100644 --- a/imports/sortimports.go +++ b/imports/sortimports.go @@ -15,7 +15,7 @@ import ( // sortImports sorts runs of consecutive import lines in import blocks in f. // It also removes duplicate imports when it is possible to do so without data loss. -func sortImports(fset *token.FileSet, f *ast.File) { +func sortImports(fset *token.FileSet, f *ast.File, ignoreGroups bool) { for i, d := range f.Decls { d, ok := d.(*ast.GenDecl) if !ok || d.Tok != token.IMPORT { @@ -37,11 +37,13 @@ func sortImports(fset *token.FileSet, f *ast.File) { // Identify and sort runs of specs on successive lines. i := 0 specs := d.Specs[:0] - for j, s := range d.Specs { - if j > i && fset.Position(s.Pos()).Line > 1+fset.Position(d.Specs[j-1].End()).Line { - // j begins a new run. End this one. - specs = append(specs, sortSpecs(fset, f, d.Specs[i:j])...) - i = j + if !ignoreGroups { + for j, s := range d.Specs { + if j > i && fset.Position(s.Pos()).Line > 1+fset.Position(d.Specs[j-1].End()).Line { + // j begins a new run. End this one. + specs = append(specs, sortSpecs(fset, f, d.Specs[i:j])...) + i = j + } } } specs = append(specs, sortSpecs(fset, f, d.Specs[i:])...)