1package edit
2
3import (
4	"bytes"
5	"go/ast"
6	"go/format"
7	"go/token"
8
9	"golang.org/x/tools/go/analysis"
10	"honnef.co/go/tools/pattern"
11)
12
13type Ranger interface {
14	Pos() token.Pos
15	End() token.Pos
16}
17
18type Range [2]token.Pos
19
20func (r Range) Pos() token.Pos { return r[0] }
21func (r Range) End() token.Pos { return r[1] }
22
23func ReplaceWithString(fset *token.FileSet, old Ranger, new string) analysis.TextEdit {
24	return analysis.TextEdit{
25		Pos:     old.Pos(),
26		End:     old.End(),
27		NewText: []byte(new),
28	}
29}
30
31func ReplaceWithNode(fset *token.FileSet, old Ranger, new ast.Node) analysis.TextEdit {
32	buf := &bytes.Buffer{}
33	if err := format.Node(buf, fset, new); err != nil {
34		panic("internal error: " + err.Error())
35	}
36	return analysis.TextEdit{
37		Pos:     old.Pos(),
38		End:     old.End(),
39		NewText: buf.Bytes(),
40	}
41}
42
43func ReplaceWithPattern(pass *analysis.Pass, after pattern.Pattern, state pattern.State, node Ranger) analysis.TextEdit {
44	r := pattern.NodeToAST(after.Root, state)
45	buf := &bytes.Buffer{}
46	format.Node(buf, pass.Fset, r)
47	return analysis.TextEdit{
48		Pos:     node.Pos(),
49		End:     node.End(),
50		NewText: buf.Bytes(),
51	}
52}
53
54func Delete(old Ranger) analysis.TextEdit {
55	return analysis.TextEdit{
56		Pos:     old.Pos(),
57		End:     old.End(),
58		NewText: nil,
59	}
60}
61
62func Fix(msg string, edits ...analysis.TextEdit) analysis.SuggestedFix {
63	return analysis.SuggestedFix{
64		Message:   msg,
65		TextEdits: edits,
66	}
67}
68