Skip to content

Commit

Permalink
internal/imports: use first quote when matching import path
Browse files Browse the repository at this point in the history
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 <heschi@google.com>
Trust: Dmitri Shuralyov <dmitshur@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
  • Loading branch information
jhump authored and ianlancetaylor committed Mar 15, 2022
1 parent 40370f8 commit 54a569a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
31 changes: 31 additions & 0 deletions internal/imports/fix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,37 @@ var _, _, _, _, _ = fmt.Errorf, io.Copy, strings.Contains, renamed_packagea.A, B
`,
},

// Blank line can be added even when first import of group has comment with quote
{
name: "new_section_where_trailing_comment_has_quote",
in: `package main
import (
"context"
bar "local.com/bar"
baz "local.com/baz"
buzz "local.com/buzz"
"github.com/golang/snappy" // this is a "typical" import
)
var _, _, _, _, _ = context.Background, bar.B, baz.B, buzz.B, snappy.ErrCorrupt
`,
out: `package main
import (
"context"
"github.com/golang/snappy" // this is a "typical" import
bar "local.com/bar"
baz "local.com/baz"
buzz "local.com/buzz"
)
var _, _, _, _, _ = context.Background, bar.B, baz.B, buzz.B, snappy.ErrCorrupt
`,
},

// Non-idempotent comment formatting
// golang.org/issue/8035
{
Expand Down
2 changes: 1 addition & 1 deletion internal/imports/imports.go
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ func matchSpace(orig []byte, src []byte) []byte {
return b.Bytes()
}

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

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

0 comments on commit 54a569a

Please sign in to comment.