-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract.go
More file actions
78 lines (67 loc) · 1.75 KB
/
Copy pathextract.go
File metadata and controls
78 lines (67 loc) · 1.75 KB
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
package logmsglint
import (
"go/ast"
"go/constant"
"go/token"
"golang.org/x/tools/go/analysis"
"strconv"
"strings"
)
type extractedMessage struct {
text string
dynamic bool
literal *ast.BasicLit // sets when msgExpr is string literal
}
func extractMessage(pass *analysis.Pass, exp ast.Expr) extractedMessage {
if lit, ok := exp.(*ast.BasicLit); ok && lit.Kind == token.STRING {
if s, err := strconv.Unquote(lit.Value); err == nil {
return extractedMessage{text: s, literal: lit}
}
}
if tv, ok := pass.TypesInfo.Types[exp]; ok && tv.Value != nil && tv.Value.Kind() == constant.String {
return extractedMessage{text: constant.StringVal(tv.Value)}
}
text, dynamic := collectStaticText(pass, exp)
return extractedMessage{text: text, dynamic: dynamic}
}
func collectStaticText(pass *analysis.Pass, e ast.Expr) (string, bool) {
switch x := e.(type) {
case *ast.BasicLit:
if x.Kind == token.STRING {
s, err := strconv.Unquote(x.Value)
return s, err != nil
}
return "", true
case *ast.BinaryExpr:
if x.Op != token.ADD {
return "", true
}
ls, ld := collectStaticText(pass, x.X)
rs, rd := collectStaticText(pass, x.Y)
return ls + rs, ld || rd
case *ast.CallExpr:
if isFmtSprintf(pass, x) && len(x.Args) > 0 {
m := extractMessage(pass, x.Args[0])
if m.text != "" {
return m.text, true
}
}
return "", true
default:
return "", true
}
}
func isFmtSprintf(pass *analysis.Pass, call *ast.CallExpr) bool {
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return false
}
obj := pass.TypesInfo.Uses[sel.Sel]
if obj == nil || obj.Pkg() == nil {
return false
}
return obj.Pkg().Path() == "fmt" && obj.Name() == "Sprintf"
}
func normalizeSpaces(s string) string {
return strings.Join(strings.Fields(s), " ")
}