-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport.go
More file actions
49 lines (46 loc) · 934 Bytes
/
import.go
File metadata and controls
49 lines (46 loc) · 934 Bytes
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
package main
import (
"bufio"
"go/ast"
"go/format"
goparser "go/parser"
"go/token"
"log"
"os"
"strconv"
)
func addimports(filename string, imports []string) {
ma := map[string]struct{}{}
for _, name := range imports {
ma[name] = struct{}{}
}
fset := token.NewFileSet()
f, err := goparser.ParseFile(fset, filename, nil, goparser.ParseComments)
if err != nil {
log.Fatal(err)
}
for _, imp := range f.Imports {
name, _ := strconv.Unquote(imp.Path.Value)
delete(ma, name)
}
dcl := &ast.GenDecl{Tok: token.IMPORT}
for name := range ma {
dcl.Specs = append(dcl.Specs, &ast.ImportSpec{
Path: &ast.BasicLit{
Value: strconv.Quote(name),
},
})
}
f.Decls = append([]ast.Decl{dcl}, f.Decls...)
fout, err := os.Create(filename)
if err != nil {
log.Fatal(err)
}
defer fout.Close()
w := bufio.NewWriter(fout)
defer w.Flush()
err = format.Node(w, fset, f)
if err != nil {
log.Fatal(err)
}
}