-
Notifications
You must be signed in to change notification settings - Fork 1
/
literal_string.go
80 lines (68 loc) · 1.9 KB
/
literal_string.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package canonicalheader
import (
"fmt"
"go/ast"
"go/token"
"strconv"
"unicode/utf8"
"unsafe"
"golang.org/x/tools/go/analysis"
)
type literalString struct {
originalValue string
quote byte
pos, end token.Pos
}
func newLiteralString(basicList *ast.BasicLit) (literalString, error) {
if basicList.Kind != token.STRING {
return literalString{}, fmt.Errorf("%#v is not a string", basicList)
}
if len(basicList.Value) < 2 {
return literalString{}, fmt.Errorf("%#v has a strange value length %q", basicList, basicList.Value)
}
quote := basicList.Value[0]
switch quote {
case '`', '"':
default:
return literalString{}, fmt.Errorf("%q is a strange quote", quote)
}
originalValue, err := strconv.Unquote(basicList.Value)
if err != nil {
return literalString{}, fmt.Errorf("unquote %q: %w", basicList.Value, err)
}
if !utf8.ValidString(originalValue) {
return literalString{}, fmt.Errorf("%#v is not a valid utf8 string", basicList.Value)
}
return literalString{
originalValue: originalValue,
quote: quote,
pos: basicList.Pos(),
end: basicList.End(),
}, nil
}
func (l literalString) diagnostic(canonicalHeader string) analysis.Diagnostic {
newText := make([]byte, 0, len(canonicalHeader)+2)
newText = append(newText, l.quote)
newText = append(newText, unsafe.Slice(unsafe.StringData(canonicalHeader), len(canonicalHeader))...)
newText = append(newText, l.quote)
return analysis.Diagnostic{
Pos: l.pos,
End: l.end,
Message: fmt.Sprintf("use %q instead of %q", canonicalHeader, l.originalValue),
SuggestedFixes: []analysis.SuggestedFix{
{
Message: fmt.Sprintf("should be replaced %q with %q", l.originalValue, canonicalHeader),
TextEdits: []analysis.TextEdit{
{
Pos: l.pos,
End: l.end,
NewText: newText,
},
},
},
},
}
}
func (l literalString) value() string {
return l.originalValue
}