GoPLS Viewer

Home|gopls/go/analysis/internal/checker/start_test.go
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
5package checker_test
6
7import (
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.
23func TestStartFixes(t *testing.T) {
24    testenv.NeedsGoPackages(t)
25
26    files := map[string]string{
27        "comment/doc.go"`/* Package comment */
28package comment
29`}
30
31    want := `// Package comment
32package comment
33`
34
35    testdatacleanuperr := 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    contentserr := 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"gotwant)
51    }
52
53    defer cleanup()
54}
55
56var commentAnalyzer = &analysis.Analyzer{
57    Name:     "comment",
58    Requires: []*analysis.Analyzer{inspect.Analyzer},
59    Run:      commentRun,
60}
61
62func 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 nok := n.(*ast.Comment); ok && n.Text == from {
70            pass.Report(analysis.Diagnostic{
71                Posn.Pos(),
72                Endn.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 nilnil
85}
86
MembersX
TestStartFixes.cleanup
commentRun.from
TestStartFixes.files
TestStartFixes.want
TestStartFixes.testdata
TestStartFixes.got
commentRun.pass
TestStartFixes.t
commentRun
commentRun.to
TestStartFixes
TestStartFixes.err
TestStartFixes.path
TestStartFixes.contents
Members
X