1
0
mirror of https://github.com/golang/go synced 2024-11-18 22:04:43 -07:00

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 <josharian@gmail.com>
Run-TryBot: Josh Bleecher Snyder <josharian@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
Fatih Arslan 2017-05-29 01:52:52 +03:00 committed by Josh Bleecher Snyder
parent bf4b54dc68
commit bc6db94186
2 changed files with 16 additions and 1 deletions

View File

@ -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)
}

View File

@ -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 (
"_"
)
`,
},
}