-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
259 lines (235 loc) · 5.34 KB
/
config.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/sirkon/goproxy/gomod"
"golang.org/x/tools/go/packages"
)
type Package struct {
Import string `hcl:"import,label"`
FileName string `hcl:"filename,optional"`
}
type Use struct {
Import string `hcl:"import,label"`
Alias string `hcl:"alias,optional"`
}
type Convert struct {
Type string `hcl:"type,attr"`
To string `hcl:"to,attr"`
Using string `hcl:"using,optional"`
}
type Field struct {
Name string `hcl:"name,label"`
To string `hcl:"to,optional"`
Using string `hcl:"using,optional"`
}
type Struct struct {
Name string `hcl:"name,label"`
Ignore []string `hcl:"ignore,optional"`
}
type Map struct {
From *Struct `hcl:"from,block"`
To *Struct `hcl:"to,block"`
Fields []*Field `hcl:"field,block"`
}
type File struct {
Package *Package `hcl:"package,block"`
Uses []*Use `hcl:"use,block"`
Maps []*Map `hcl:"map,block"`
Converts []*Convert `hcl:"convert,block"`
}
type sdcgContext struct {
dir string
currentModule string
// should not modify
files []*contextFile
}
// If dir is not set, it defaults to the current working directory
func newCtx(dir string) (*sdcgContext, error) {
var err error
if dir == "" {
dir, err = os.Getwd()
if err != nil {
return nil, fmt.Errorf("unable to get working directory: %w", err)
}
}
modFile, err := findGoModFile(dir)
if err != nil {
return nil, err
}
mod, err := gomod.Parse("go.mod", modFile)
if err != nil {
return nil, err
}
return &sdcgContext{
dir: dir,
currentModule: mod.Name,
}, nil
}
func (ctx *sdcgContext) hasErrors() bool {
for _, file := range ctx.files {
if file.hasErrors() {
return true
}
}
return false
}
type contextFile struct {
*File
info os.FileInfo
errs []error
genPkg *packages.Package
pkgs map[string]*packages.Package
}
func (cf *contextFile) addErr(err error) {
cf.errs = append(cf.errs, err)
}
func (cf *contextFile) hasErrors() bool {
return len(cf.errs) != 0
}
func load(ctx *sdcgContext) error {
err := parseHCLFiles(ctx)
if err != nil {
return err
}
loadPackages(ctx)
// TODO: load converts
// TODO: load maps
return nil
}
func parseHCLFiles(ctx *sdcgContext) error {
files, err := ioutil.ReadDir(ctx.dir)
if err != nil {
return fmt.Errorf("unable to read directory: %w", err)
}
parser := hclparse.NewParser()
for _, f := range files {
ctxFile := &contextFile{
info: f,
}
if f.IsDir() {
continue
}
if path.Ext(f.Name()) != ".hcl" {
continue
}
hcl, diag := parser.ParseHCLFile(path.Join(dir, f.Name()))
if diag.HasErrors() {
ctxFile.addErr(fmt.Errorf("unable to parse: %w", diag))
ctx.files = append(ctx.files, ctxFile)
continue
}
var config File
diag = gohcl.DecodeBody(hcl.Body, hclCtx, &config)
if diag.HasErrors() {
ctxFile.addErr(fmt.Errorf("unable to decode into go struct: %w", diag))
ctx.files = append(ctx.files, ctxFile)
continue
}
ctxFile.File = &config
ctx.files = append(ctx.files, ctxFile)
}
return nil
}
func loadPackages(ctx *sdcgContext) {
for _, file := range ctx.files {
if file.hasErrors() {
continue
}
file.loadPackages(ctx)
}
}
func (cf *contextFile) loadPackages(ctx *sdcgContext) {
if cf.hasErrors() {
cf.addErr(fmt.Errorf("cannot load packages from file with errors"))
}
cfg := &packages.Config{
Mode: packages.NeedName | packages.NeedTypes,
Dir: dir,
}
// Load the package statement
if cf.Package == nil {
cf.addErr(fmt.Errorf("invalid file: must have package block"))
return
}
if !strings.HasPrefix(cf.Package.Import, ctx.currentModule) {
cf.addErr(fmt.Errorf("can only have a package statement apart of current module"))
return
}
pkgImport, err := packages.Load(cfg, cf.Package.Import)
if err != nil {
cf.addErr(err)
return
}
if len(pkgImport) != 1 {
cf.addErr(fmt.Errorf("unexpected number of imported packages for package block"))
return
}
if len(pkgImport[0].Errors) > 0 {
for _, err := range pkgImport[0].Errors {
if strings.Contains(err.Error(), "no matching versions for query") {
// Package doesn't exist so we can create it
continue
}
cf.addErr(fmt.Errorf("issues loading %s: %w", cf.Package.Import, err))
}
if cf.hasErrors() {
return
}
} else {
cf.genPkg = pkgImport[0]
}
// Load the Uses statements
var pkgImports []string
for _, u := range cf.Uses {
pkgImports = append(pkgImports, u.Import)
}
loadedPkgs, err := packages.Load(cfg, pkgImports...)
if err != nil {
cf.addErr(err)
return
}
for i, lp := range loadedPkgs {
u := cf.Uses[i]
if len(lp.Errors) != 0 {
for _, err = range lp.Errors {
cf.addErr(fmt.Errorf("issues loading %s: %w", u.Import, err))
}
continue
}
imp := lp.Name
if u.Alias != "" {
imp = u.Alias
}
if cf.pkgs == nil {
cf.pkgs = make(map[string]*packages.Package)
}
cf.pkgs[imp] = lp
}
return
}
func findGoModFile(startingDir string) ([]byte, error) {
dir, err := filepath.Abs(startingDir)
if err != nil {
return nil, err
}
for {
if dir == string(filepath.Separator) {
break
}
f, err := ioutil.ReadFile(path.Join(dir, "go.mod"))
if errors.Is(err, os.ErrNotExist) {
dir = path.Dir(dir)
continue
}
return f, nil
}
return nil, fmt.Errorf("could not find go.mod file")
}