From af95c112ad356bcee7a61b6f494e8e47756b970f Mon Sep 17 00:00:00 2001 From: Rhys Hiltner Date: Fri, 23 Sep 2016 17:37:05 -0700 Subject: [PATCH] go/ast/astutil: do not remove imports in AddNamedImport When adding imports to an existing import declaration, ensure that the target declaration will be printed with parentheses. This allows all of the imported packages to be printed, not just the first one. Fixes golang/go#17212 Change-Id: Ie5de5ec9bca6169650336ee2ea98334817e64e48 Reviewed-on: https://go-review.googlesource.com/29688 Reviewed-by: Brad Fitzpatrick Run-TryBot: Brad Fitzpatrick TryBot-Result: Gobot Gobot --- go/ast/astutil/imports.go | 3 +++ go/ast/astutil/imports_test.go | 36 ++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/go/ast/astutil/imports.go b/go/ast/astutil/imports.go index 7d793ffa..2e81f4d3 100644 --- a/go/ast/astutil/imports.go +++ b/go/ast/astutil/imports.go @@ -160,6 +160,9 @@ func AddNamedImport(fset *token.FileSet, f *ast.File, name, ipath string) (added first = gen continue // Don't touch the first one. } + // We now know there is more than one package in this import + // declaration. Ensure that it ends up parenthesized. + first.Lparen = first.Pos() // Move the imports of the other import declaration to the first one. for _, spec := range gen.Specs { spec.(*ast.ImportSpec).Path.ValuePos = first.Pos() diff --git a/go/ast/astutil/imports_test.go b/go/ast/astutil/imports_test.go index c9f80df7..67dd5565 100644 --- a/go/ast/astutil/imports_test.go +++ b/go/ast/astutil/imports_test.go @@ -509,6 +509,42 @@ import "C" // Comment import "C" import "bufio" +`, + }, + { + name: `issue 17212 several single-import lines with shared prefix ending in a slash`, + pkg: "net/http", + in: `package main + +import "bufio" +import "net/url" +`, + out: `package main + +import ( + "bufio" + "net/http" + "net/url" +) +`, + }, + { + name: `issue 17212 block imports lines with shared prefix ending in a slash`, + pkg: "net/http", + in: `package main + +import ( + "bufio" + "net/url" +) +`, + out: `package main + +import ( + "bufio" + "net/http" + "net/url" +) `, }, {