From bc6db94186c03835daa5c1c679fba599dc1f3b79 Mon Sep 17 00:00:00 2001 From: Fatih Arslan Date: Mon, 29 May 2017 01:52:52 +0300 Subject: [PATCH] go/ast/astutil: do not merge if import path is last line DeleteNamedImport assumes the import declaration is in the form of: import ( "foo" ) If an import path is deleted there might be a blank line-sized hole: import ( ) It'll merge the black hole with the last line to change it to: import ( ) However the import declaration might be in the following form as well: import ( "foo") Whic means after deleting the import path, it changes to: import ( ) In this case it still tries to merge the line with a non existing line, causing token.File.MergeLine to panic. We fix the issue by checking that the import path line is not the last line to avoid panicing. Fixes golang/go#20229 Change-Id: I37537a4eaa83d14db59a2926d7bb14c27167a2e4 Reviewed-on: https://go-review.googlesource.com/44372 Reviewed-by: Josh Bleecher Snyder Run-TryBot: Josh Bleecher Snyder TryBot-Result: Gobot Gobot --- go/ast/astutil/imports.go | 2 +- go/ast/astutil/imports_test.go | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/go/ast/astutil/imports.go b/go/ast/astutil/imports.go index 36c536b5..4a77c782 100644 --- a/go/ast/astutil/imports.go +++ b/go/ast/astutil/imports.go @@ -262,7 +262,7 @@ func DeleteNamedImport(fset *token.FileSet, f *ast.File, name, path string) (del // There was a blank line immediately preceding the deleted import, // so there's no need to close the hole. // Do nothing. - } else { + } else if line != fset.File(gen.Rparen).LineCount() { // There was no blank line. Close the hole. fset.File(gen.Rparen).MergeLine(line) } diff --git a/go/ast/astutil/imports_test.go b/go/ast/astutil/imports_test.go index cb12a290..21682674 100644 --- a/go/ast/astutil/imports_test.go +++ b/go/ast/astutil/imports_test.go @@ -1297,6 +1297,21 @@ import ( /* comment 2 */ "io" ) +`, + }, + + // Issue 20229: MergeLine panic on weird input + { + name: "import.37", + pkg: "io", + in: `package main +import("_" +"io")`, + out: `package main + +import ( + "_" +) `, }, }