diff --git a/go/ast/astutil/imports.go b/go/ast/astutil/imports.go index c371bc16..cfaa864a 100644 --- a/go/ast/astutil/imports.go +++ b/go/ast/astutil/imports.go @@ -143,6 +143,30 @@ func AddNamedImport(fset *token.FileSet, f *ast.File, name, ipath string) (added } f.Imports = append(f.Imports, newImport) + + if len(f.Decls) <= 1 { + return true + } + + // Merge all the import declarations into the first one. + var first *ast.GenDecl + for i, decl := range f.Decls { + gen, ok := decl.(*ast.GenDecl) + if !ok || gen.Tok != token.IMPORT || declImports(gen, "C") { + continue + } + if first == nil { + first = gen + continue // Don't touch the first one. + } + // Move the imports of the other import declaration to the first one. + for _, spec := range gen.Specs { + spec.(*ast.ImportSpec).Path.ValuePos = first.Pos() + first.Specs = append(first.Specs, spec) + } + f.Decls = append(f.Decls[:i], f.Decls[i+1:]...) + } + return true } diff --git a/go/ast/astutil/imports_test.go b/go/ast/astutil/imports_test.go index 589a0289..f727f5d1 100644 --- a/go/ast/astutil/imports_test.go +++ b/go/ast/astutil/imports_test.go @@ -396,6 +396,119 @@ import ( "fmt" // b "log" ) +`, + }, + // Issue 14075: Merge import declarations + { + name: "issue 14075", + pkg: "bufio", + in: `package main + +import "bytes" +import "fmt" +`, + out: `package main + +import ( + "bufio" + "bytes" + "fmt" +) +`, + }, + { + name: "issue 14075 update position", + pkg: "bufio", + in: `package main + +import "bytes" +import ( + "fmt" +) +`, + out: `package main + +import ( + "bufio" + "bytes" + "fmt" +) +`, + }, + { + name: `issue 14075 ignore import "C"`, + pkg: "bufio", + in: `package main + +// Comment +import "C" + +import "bytes" +import "fmt" +`, + out: `package main + +// Comment +import "C" + +import ( + "bufio" + "bytes" + "fmt" +) +`, + }, + { + name: `issue 14075 ignore adjacent import "C"`, + pkg: "bufio", + in: `package main + +// Comment +import "C" +import "fmt" +`, + out: `package main + +// Comment +import "C" +import ( + "bufio" + "fmt" +) +`, + }, + { + name: `issue 14075 ignore adjacent import "C" (without factored import)`, + pkg: "bufio", + in: `package main + +// Comment +import "C" +import "fmt" +`, + out: `package main + +// Comment +import "C" +import ( + "bufio" + "fmt" +) +`, + }, + { + name: `issue 14075 ignore single import "C"`, + pkg: "bufio", + in: `package main + +// Comment +import "C" +`, + out: `package main + +// Comment +import "C" +import "bufio" `, }, }