Skip to content

Commit 54a569a

Browse files
jhumpianlancetaylor
authored andcommitted
internal/imports: use first quote when matching import path
This fixes the regexp used to extract the import path from a line of code when inserting newlines to split a sequence of imports into groups. By using a non-greedy match, the regexp now functions correctly in the face of an extra quote after the import path (such as when there is a trailing comment that includes a quote). Fixes golang/go#51671 Change-Id: Id7fd0b1d794f989d8f3d47336c5b5454cddd6237 GitHub-Last-Rev: b934371 GitHub-Pull-Request: #365 Reviewed-on: https://go-review.googlesource.com/c/tools/+/386914 Reviewed-by: Heschi Kreinick <[email protected]> Trust: Dmitri Shuralyov <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> gopls-CI: kokoro <[email protected]> TryBot-Result: Gopher Robot <[email protected]>
1 parent 40370f8 commit 54a569a

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

internal/imports/fix_test.go

+31
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,37 @@ var _, _, _, _, _ = fmt.Errorf, io.Copy, strings.Contains, renamed_packagea.A, B
659659
`,
660660
},
661661

662+
// Blank line can be added even when first import of group has comment with quote
663+
{
664+
name: "new_section_where_trailing_comment_has_quote",
665+
in: `package main
666+
667+
import (
668+
"context"
669+
bar "local.com/bar"
670+
baz "local.com/baz"
671+
buzz "local.com/buzz"
672+
"github.com/golang/snappy" // this is a "typical" import
673+
)
674+
675+
var _, _, _, _, _ = context.Background, bar.B, baz.B, buzz.B, snappy.ErrCorrupt
676+
`,
677+
out: `package main
678+
679+
import (
680+
"context"
681+
682+
"github.com/golang/snappy" // this is a "typical" import
683+
684+
bar "local.com/bar"
685+
baz "local.com/baz"
686+
buzz "local.com/buzz"
687+
)
688+
689+
var _, _, _, _, _ = context.Background, bar.B, baz.B, buzz.B, snappy.ErrCorrupt
690+
`,
691+
},
692+
662693
// Non-idempotent comment formatting
663694
// golang.org/issue/8035
664695
{

internal/imports/imports.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ func matchSpace(orig []byte, src []byte) []byte {
306306
return b.Bytes()
307307
}
308308

309-
var impLine = regexp.MustCompile(`^\s+(?:[\w\.]+\s+)?"(.+)"`)
309+
var impLine = regexp.MustCompile(`^\s+(?:[\w\.]+\s+)?"(.+?)"`)
310310

311311
func addImportSpaces(r io.Reader, breaks []string) ([]byte, error) {
312312
var out bytes.Buffer

0 commit comments

Comments
 (0)