/
import.go
161 lines (141 loc) · 3.7 KB
/
import.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package xast
import (
"bytes"
"go/ast"
"go/format"
"go/parser"
"go/token"
"strconv"
"github.com/ignite/cli/v29/ignite/pkg/errors"
)
type (
// importOpts represent the options for imp.
importOpts struct {
imports []imp
}
// ImportOptions configures code generation.
ImportOptions func(*importOpts)
imp struct {
repo string
name string
index int
}
)
// WithLastImport add a new import int the end.
func WithLastImport(repo string) ImportOptions {
return func(c *importOpts) {
c.imports = append(c.imports, imp{
repo: repo,
name: "",
index: -1,
})
}
}
// WithImport add a new import. If the index is -1 will append in the end of the imports.
func WithImport(repo string, index int) ImportOptions {
return func(c *importOpts) {
c.imports = append(c.imports, imp{
repo: repo,
name: "",
index: index,
})
}
}
// WithNamedImport add a new import with name. If the index is -1 will append in the end of the imports.
func WithNamedImport(name, repo string, index int) ImportOptions {
return func(c *importOpts) {
c.imports = append(c.imports, imp{
name: name,
repo: repo,
index: index,
})
}
}
// WithLastNamedImport add a new import with name in the end of the imports.
func WithLastNamedImport(name, repo string) ImportOptions {
return func(c *importOpts) {
c.imports = append(c.imports, imp{
name: name,
repo: repo,
index: -1,
})
}
}
func newImportOptions() importOpts {
return importOpts{
imports: make([]imp, 0),
}
}
// AppendImports appends import statements to the existing import block in Go source code content.
func AppendImports(fileContent string, imports ...ImportOptions) (string, error) {
// apply global options.
opts := newImportOptions()
for _, o := range imports {
o(&opts)
}
fileSet := token.NewFileSet()
// Parse the Go source code content.
f, err := parser.ParseFile(fileSet, "", fileContent, parser.ParseComments)
if err != nil {
return "", err
}
// Find the existing import declaration.
var importDecl *ast.GenDecl
for _, decl := range f.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok || genDecl.Tok != token.IMPORT || len(genDecl.Specs) == 0 {
continue
}
importDecl = genDecl
break
}
if importDecl == nil {
// If no existing import declaration found, create a new one.
importDecl = &ast.GenDecl{
Tok: token.IMPORT,
Specs: make([]ast.Spec, 0),
}
f.Decls = append([]ast.Decl{importDecl}, f.Decls...)
}
// Check existing imports to avoid duplicates.
existImports := make(map[string]struct{})
for _, spec := range importDecl.Specs {
importSpec, ok := spec.(*ast.ImportSpec)
if !ok {
continue
}
existImports[importSpec.Path.Value] = struct{}{}
}
// Add new import statements.
for _, importStmt := range opts.imports {
// Check if the import already exists.
path := strconv.Quote(importStmt.repo)
if _, ok := existImports[path]; ok {
continue
}
// Create a new import spec.
spec := &ast.ImportSpec{
Name: ast.NewIdent(importStmt.name),
Path: &ast.BasicLit{
Kind: token.STRING,
Value: path,
},
}
switch {
case importStmt.index == -1:
// Append the new argument to the end
importDecl.Specs = append(importDecl.Specs, spec)
case importStmt.index >= 0 && importStmt.index <= len(importDecl.Specs):
// Insert the new argument at the specified index
importDecl.Specs = append(importDecl.Specs[:importStmt.index], append([]ast.Spec{spec}, importDecl.Specs[importStmt.index:]...)...)
default:
return "", errors.Errorf("index out of range") // Stop the inspection, an error occurred
}
}
// Format the modified AST.
var buf bytes.Buffer
if err := format.Node(&buf, fileSet, f); err != nil {
return "", err
}
return buf.String(), nil
}