-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport.go
More file actions
67 lines (60 loc) · 1.48 KB
/
import.go
File metadata and controls
67 lines (60 loc) · 1.48 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
package gcode
import (
"bytes"
"fmt"
"go/parser"
"go/token"
)
func AddImport(code []byte, name, path string) ([]byte, error) {
path = fmt.Sprintf("%q", path)
//bs := file.Bytes()
var fset = &token.FileSet{}
var importStart, importEnd int
var importBuf = &bytes.Buffer{}
importBuf.WriteString("import(")
if f, err := parser.ParseFile(fset, "", code, parser.ImportsOnly); err == nil {
if len(f.Imports) < 1 {
//create
if f.Name == nil || f.Name.End() == 0 {
return nil, ErrNoPackage
}
importStart = int(f.Name.End())
importEnd = int(f.Name.End())
} else {
importStart = int(f.Decls[0].Pos())
importEnd = int(f.Decls[0].End())
}
for _, item := range f.Imports {
itemName := ""
if item.Name != nil {
itemName = item.Name.String()
}
itemPath := item.Path.Value
if itemName == name && itemPath == path {
return code, nil // no need change
}
if itemName == "" {
importBuf.WriteString(fmt.Sprintf("\n %s", itemPath))
} else {
importBuf.WriteString(fmt.Sprintf("\n %s %s", itemName, itemPath))
}
}
}
if name == "" {
importBuf.WriteString(fmt.Sprintf("\n %s", path))
} else {
importBuf.WriteString(fmt.Sprintf("\n %s %s", name, path))
}
importBuf.WriteString("\n)")
w := &bytes.Buffer{}
w.Write(code[0:importStart])
if importStart == importEnd {
w.WriteString("\n")
}
w.Write(importBuf.Bytes())
if importStart == importEnd {
w.WriteString("\n")
}
w.Write(code[importEnd:])
return w.Bytes(), nil
}