Skip to content
This repository has been archived by the owner on May 9, 2021. It is now read-only.

Commit

Permalink
lint: use the same *token.FileSet to parse and generate file
Browse files Browse the repository at this point in the history
If not, `format.Node()` outputs the source code that has
comments on an incorrect position.
  • Loading branch information
moznion committed Dec 12, 2019
1 parent 00dcd60 commit 9e3261b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
24 changes: 18 additions & 6 deletions golint/golint.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ func exists(filename string) bool {
return err == nil
}

type srcInfoForAutoFix struct {
astFile *ast.File
fileSet *token.FileSet
}

func lintFiles(filenames ...string) {
files := make(map[string][]byte)
for _, filename := range filenames {
Expand All @@ -121,15 +126,18 @@ func lintFiles(filenames ...string) {
return
}

filenameToReplacedFileAST := make(map[string]*ast.File)
filenameToSrcAutoFix := make(map[string]*srcInfoForAutoFix)

for _, p := range ps {
if p.Confidence >= *minConfidence {
autoFixedMarker := ""
if *shouldFix {
if replacer := p.Fixer; replacer != nil {
if fixer := p.Fixer; fixer != nil {
if filename := p.Position.Filename; filename != "" {
filenameToReplacedFileAST[filename] = replacer()
filenameToSrcAutoFix[filename] = &srcInfoForAutoFix{
astFile: fixer(),
fileSet: p.FileSet,
}
autoFixedMarker = "[fixed] "
}
}
Expand All @@ -139,14 +147,18 @@ func lintFiles(filenames ...string) {
}
}

for filename, astFile := range filenameToReplacedFileAST {
for filename, src := range filenameToSrcAutoFix {
func() {
file, err := os.Create(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
fmt.Fprintf(os.Stderr, "failed to create a file for auto-fix; %v\n", err)
return
}
err = format.Node(file, src.fileSet, src.astFile)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to generate code for auto-fix; %v\n", err)
return
}
format.Node(file, token.NewFileSet(), astFile)
}()
}
}
Expand Down
4 changes: 4 additions & 0 deletions lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ type Problem struct {
// Fixer fixes a warning automatically if it is possible and returns fixed file's AST.
// If this field is nil, it does nothing.
Fixer func() *ast.File

// FileSet is used to generate source code for fix mode.
FileSet *token.FileSet
}

func (p *Problem) String() string {
Expand Down Expand Up @@ -235,6 +238,7 @@ func (p *pkg) errorfAt(pos token.Position, confidence float64, fixer func() *ast
Position: pos,
Confidence: confidence,
Fixer: fixer,
FileSet: p.fset,
}
if pos.Filename != "" {
// The file might not exist in our mapping if a //line directive was encountered.
Expand Down

0 comments on commit 9e3261b

Please sign in to comment.