diff --git a/go/ast/astutil/imports.go b/go/ast/astutil/imports.go index 3e4b195368..2087ceec9c 100644 --- a/go/ast/astutil/imports.go +++ b/go/ast/astutil/imports.go @@ -275,9 +275,10 @@ func DeleteNamedImport(fset *token.FileSet, f *ast.File, name, path string) (del // We deleted an entry but now there may be // a blank line-sized hole where the import was. - if line-lastLine > 1 { + if line-lastLine > 1 || !gen.Rparen.IsValid() { // There was a blank line immediately preceding the deleted import, - // so there's no need to close the hole. + // so there's no need to close the hole. The right parenthesis is + // invalid after AddImport to an import statement without parenthesis. // Do nothing. } else if line != fset.File(gen.Rparen).LineCount() { // There was no blank line. Close the hole. diff --git a/go/ast/astutil/imports_test.go b/go/ast/astutil/imports_test.go index 1d86e4773e..68f05ab6d9 100644 --- a/go/ast/astutil/imports_test.go +++ b/go/ast/astutil/imports_test.go @@ -1684,6 +1684,19 @@ func TestDeleteImport(t *testing.T) { } } +func TestDeleteImportAfterAddImport(t *testing.T) { + file := parse(t, "test", `package main + +import "os" +`) + if got, want := AddImport(fset, file, "fmt"), true; got != want { + t.Errorf("AddImport: got: %v, want: %v", got, want) + } + if got, want := DeleteImport(fset, file, "fmt"), true; got != want { + t.Errorf("DeleteImport: got: %v, want: %v", got, want) + } +} + type rewriteTest struct { name string srcPkg string