Skip to content

Commit fed8cc8

Browse files
committed
internal/refactor: keep comments with same import
When adding a new import spec, set its position to just after the comment on the last existing spec. This maintains comments on existing specs. Change-Id: I24e5d3b9277f5ab3cc585f27f2bf269fea5eb18e Reviewed-on: https://go-review.googlesource.com/c/tools/+/677518 LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Reviewed-by: Alan Donovan <adonovan@google.com>
1 parent c7873a3 commit fed8cc8

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

internal/refactor/inline/inline.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -330,20 +330,35 @@ func (st *state) inline() (*Result, error) {
330330
}
331331
}
332332
// Add new imports.
333+
// Set their position to after the last position of the old imports, to keep
334+
// comments on the old imports from moving.
335+
lastPos := token.NoPos
336+
if lastSpec := last(importDecl.Specs); lastSpec != nil {
337+
lastPos = lastSpec.Pos()
338+
if c := lastSpec.(*ast.ImportSpec).Comment; c != nil {
339+
lastPos = c.Pos()
340+
}
341+
}
333342
for _, imp := range newImports {
334343
// Check that the new imports are accessible.
335344
path, _ := strconv.Unquote(imp.spec.Path.Value)
336345
if !analysisinternal.CanImport(caller.Types.Path(), path) {
337346
return nil, fmt.Errorf("can't inline function %v as its body refers to inaccessible package %q", callee, path)
338347
}
348+
if lastPos.IsValid() {
349+
lastPos++
350+
imp.spec.Path.ValuePos = lastPos
351+
}
339352
importDecl.Specs = append(importDecl.Specs, imp.spec)
340353
}
354+
341355
var out bytes.Buffer
342356
out.Write(before)
343357
commented := &printer.CommentedNode{
344358
Node: importDecl,
345359
Comments: comments,
346360
}
361+
347362
if err := format.Node(&out, fset, commented); err != nil {
348363
logf("failed to format new importDecl: %v", err) // debugging
349364
return nil, err
@@ -354,7 +369,6 @@ func (st *state) inline() (*Result, error) {
354369
return nil, err
355370
}
356371
}
357-
358372
// Delete imports referenced only by caller.Call.Fun.
359373
for _, oldImport := range res.oldImports {
360374
specToDelete := oldImport.spec

internal/refactor/inline/testdata/import-comments.txtar

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import (
2828
"io"
2929

3030
// This is an import of c.
31-
"testdata/c"
31+
"testdata/c" // yes, of c
3232
)
3333

3434
var (
@@ -52,7 +52,7 @@ import (
5252

5353
// This is an import of c.
5454
"testdata/b"
55-
"testdata/c"
55+
"testdata/c" // yes, of c
5656
)
5757

5858
var (

0 commit comments

Comments
 (0)