From 21a9fe9db85b8a98f2b5e762e660969b98e2d8b8 Mon Sep 17 00:00:00 2001 From: zoumo Date: Thu, 5 Sep 2019 14:56:24 +0800 Subject: [PATCH] internal/imports: force to repair imports group regardless of how they were originally grouped --- cmd/goimports/goimports.go | 1 + internal/imports/fix.go | 1 + internal/imports/sortimports.go | 13 ++++++++----- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/cmd/goimports/goimports.go b/cmd/goimports/goimports.go index a476a7f3c30..d8b2d7b382d 100644 --- a/cmd/goimports/goimports.go +++ b/cmd/goimports/goimports.go @@ -54,6 +54,7 @@ var ( func init() { flag.BoolVar(&options.AllErrors, "e", false, "report all errors (not just the first 10 on different lines)") + flag.BoolVar(&options.Env.RepairGroup, "repair-group", false, "force to repair imports group regardless of how they were originally grouped") flag.StringVar(&options.Env.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list") 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.") } diff --git a/internal/imports/fix.go b/internal/imports/fix.go index bcfbb07ed87..3fd79b7d788 100644 --- a/internal/imports/fix.go +++ b/internal/imports/fix.go @@ -614,6 +614,7 @@ func getAllCandidates(filename string, env *ProcessEnv) ([]ImportFix, error) { type ProcessEnv struct { LocalPrefix string Debug bool + RepairGroup bool // If non-empty, these will be used instead of the // process-wide values. diff --git a/internal/imports/sortimports.go b/internal/imports/sortimports.go index 226279471d3..8922d3bcb8c 100644 --- a/internal/imports/sortimports.go +++ b/internal/imports/sortimports.go @@ -37,11 +37,14 @@ func sortImports(env *ProcessEnv, 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(env, fset, f, d.Specs[i:j])...) - i = j + // If repairGroup is true, treats all specs in the same import group. + if !env.RepairGroup { + 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(env, fset, f, d.Specs[i:j])...) + i = j + } } } specs = append(specs, sortSpecs(env, fset, f, d.Specs[i:])...)