fix
wangpengfei
2023-08-26 731ea35ad6ce787231dd8a796f653a6d882415cb
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
package ast
 
import (
    "fmt"
    "go/ast"
    "go/token"
)
 
// 增加 import 方法
func AddImport(astNode ast.Node, imp string) {
    impStr := fmt.Sprintf("\"%s\"", imp)
    ast.Inspect(astNode, func(node ast.Node) bool {
        if genDecl, ok := node.(*ast.GenDecl); ok {
            if genDecl.Tok == token.IMPORT {
                for i := range genDecl.Specs {
                    if impNode, ok := genDecl.Specs[i].(*ast.ImportSpec); ok {
                        if impNode.Path.Value == impStr {
                            return false
                        }
                    }
                }
                genDecl.Specs = append(genDecl.Specs, &ast.ImportSpec{
                    Path: &ast.BasicLit{
                        Kind:  token.STRING,
                        Value: impStr,
                    },
                })
            }
        }
        return true
    })
}
 
// 查询特定function方法
func FindFunction(astNode ast.Node, FunctionName string) *ast.FuncDecl {
    var funcDeclP *ast.FuncDecl
    ast.Inspect(astNode, func(node ast.Node) bool {
        if funcDecl, ok := node.(*ast.FuncDecl); ok {
            if funcDecl.Name.String() == FunctionName {
                funcDeclP = funcDecl
                return false
            }
        }
        return true
    })
    return funcDeclP
}