Skip to content

Commit 0acc998

Browse files
committed
feat: add GetFilePositionFor
1 parent 89dc119 commit 0acc998

File tree

2 files changed

+48
-10
lines changed

2 files changed

+48
-10
lines changed

pkg/goanalysis/position.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package goanalysis
2+
3+
import (
4+
"go/ast"
5+
"go/token"
6+
"path/filepath"
7+
8+
"golang.org/x/tools/go/analysis"
9+
)
10+
11+
func GetFilePosition(pass *analysis.Pass, f *ast.File) token.Position {
12+
return GetFilePositionFor(pass.Fset, f.Pos())
13+
}
14+
15+
func GetFilePositionFor(fset *token.FileSet, p token.Pos) token.Position {
16+
pos := fset.PositionFor(p, true)
17+
18+
ext := filepath.Ext(pos.Filename)
19+
if ext != ".go" {
20+
// position has been adjusted to a non-go file, revert to original file
21+
return fset.PositionFor(p, false)
22+
}
23+
24+
return pos
25+
}
26+
27+
func EndOfLinePos(f *token.File, line int) token.Pos {
28+
var end token.Pos
29+
30+
if line == f.LineCount() {
31+
// missing newline at the end of the file
32+
end = f.Pos(f.Size())
33+
} else {
34+
end = f.LineStart(line+1) - token.Pos(1)
35+
}
36+
37+
return end
38+
}
39+
40+
// AdjustPos is a hack to get the right line to display.
41+
// It should not be used outside some specific cases.
42+
func AdjustPos(line, nonAdjLine, adjLine int) int {
43+
return line + nonAdjLine - adjLine
44+
}

pkg/golinters/internal/util.go

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@ package internal
22

33
import (
44
"fmt"
5-
"path/filepath"
65
"strings"
76

87
"golang.org/x/tools/go/analysis"
98

109
"github.com/golangci/golangci-lint/pkg/config"
10+
"github.com/golangci/golangci-lint/pkg/goanalysis"
1111
)
1212

1313
func FormatCode(code string, _ *config.Config) string {
@@ -19,15 +19,9 @@ func FormatCode(code string, _ *config.Config) string {
1919
}
2020

2121
func GetFileNames(pass *analysis.Pass) []string {
22-
var fileNames []string
22+
var filenames []string
2323
for _, f := range pass.Files {
24-
fileName := pass.Fset.PositionFor(f.Pos(), true).Filename
25-
ext := filepath.Ext(fileName)
26-
if ext != "" && ext != ".go" {
27-
// position has been adjusted to a non-go file, revert to original file
28-
fileName = pass.Fset.PositionFor(f.Pos(), false).Filename
29-
}
30-
fileNames = append(fileNames, fileName)
24+
filenames = append(filenames, goanalysis.GetFilePosition(pass, f).Filename)
3125
}
32-
return fileNames
26+
return filenames
3327
}

0 commit comments

Comments
 (0)