|
| 1 | +// Copyright 2022 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package checker_test |
| 6 | + |
| 7 | +import ( |
| 8 | + "go/ast" |
| 9 | + "io/ioutil" |
| 10 | + "path/filepath" |
| 11 | + "testing" |
| 12 | + |
| 13 | + "golang.org/x/tools/go/analysis" |
| 14 | + "golang.org/x/tools/go/analysis/analysistest" |
| 15 | + "golang.org/x/tools/go/analysis/internal/checker" |
| 16 | + "golang.org/x/tools/go/analysis/passes/inspect" |
| 17 | + "golang.org/x/tools/go/ast/inspector" |
| 18 | + "golang.org/x/tools/internal/testenv" |
| 19 | +) |
| 20 | + |
| 21 | +// TestStartFixes make sure modifying the first character |
| 22 | +// of the file takes effect. |
| 23 | +func TestStartFixes(t *testing.T) { |
| 24 | + testenv.NeedsGoPackages(t) |
| 25 | + |
| 26 | + files := map[string]string{ |
| 27 | + "comment/doc.go": `/* Package comment */ |
| 28 | +package comment |
| 29 | +`} |
| 30 | + |
| 31 | + want := `// Package comment |
| 32 | +package comment |
| 33 | +` |
| 34 | + |
| 35 | + testdata, cleanup, err := analysistest.WriteFiles(files) |
| 36 | + if err != nil { |
| 37 | + t.Fatal(err) |
| 38 | + } |
| 39 | + path := filepath.Join(testdata, "src/comment/doc.go") |
| 40 | + checker.Fix = true |
| 41 | + checker.Run([]string{"file=" + path}, []*analysis.Analyzer{commentAnalyzer}) |
| 42 | + |
| 43 | + contents, err := ioutil.ReadFile(path) |
| 44 | + if err != nil { |
| 45 | + t.Fatal(err) |
| 46 | + } |
| 47 | + |
| 48 | + got := string(contents) |
| 49 | + if got != want { |
| 50 | + t.Errorf("contents of rewritten file\ngot: %s\nwant: %s", got, want) |
| 51 | + } |
| 52 | + |
| 53 | + defer cleanup() |
| 54 | +} |
| 55 | + |
| 56 | +var commentAnalyzer = &analysis.Analyzer{ |
| 57 | + Name: "comment", |
| 58 | + Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 59 | + Run: commentRun, |
| 60 | +} |
| 61 | + |
| 62 | +func commentRun(pass *analysis.Pass) (interface{}, error) { |
| 63 | + const ( |
| 64 | + from = "/* Package comment */" |
| 65 | + to = "// Package comment" |
| 66 | + ) |
| 67 | + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 68 | + inspect.Preorder(nil, func(n ast.Node) { |
| 69 | + if n, ok := n.(*ast.Comment); ok && n.Text == from { |
| 70 | + pass.Report(analysis.Diagnostic{ |
| 71 | + Pos: n.Pos(), |
| 72 | + End: n.End(), |
| 73 | + SuggestedFixes: []analysis.SuggestedFix{{ |
| 74 | + TextEdits: []analysis.TextEdit{{ |
| 75 | + Pos: n.Pos(), |
| 76 | + End: n.End(), |
| 77 | + NewText: []byte(to), |
| 78 | + }}, |
| 79 | + }}, |
| 80 | + }) |
| 81 | + } |
| 82 | + }) |
| 83 | + |
| 84 | + return nil, nil |
| 85 | +} |
0 commit comments