-
Notifications
You must be signed in to change notification settings - Fork 546
/
load.go
421 lines (380 loc) · 9.81 KB
/
load.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/*
* Copyright (c) 2022 The GoPlus Authors (goplus.org). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gop
import (
"fmt"
"io/fs"
"os"
"path"
"strings"
"github.com/goplus/gogen"
"github.com/goplus/gop/ast"
"github.com/goplus/gop/cl"
"github.com/goplus/gop/parser"
"github.com/goplus/gop/token"
"github.com/goplus/gop/x/gocmd"
"github.com/goplus/gop/x/gopenv"
"github.com/goplus/mod/env"
"github.com/goplus/mod/gopmod"
"github.com/qiniu/x/errors"
)
var (
ErrNotFound = gopmod.ErrNotFound
ErrIgnoreNotated = errors.New("notated error ignored")
)
// NotFound returns if cause err is ErrNotFound or not
func NotFound(err error) bool {
return gopmod.IsNotFound(err)
}
// IgnoreNotated returns if cause err is ErrIgnoreNotated or not.
func IgnoreNotated(err error) bool {
return errors.Err(err) == ErrIgnoreNotated
}
// ErrorPos returns where the error occurs.
func ErrorPos(err error) token.Pos {
switch v := err.(type) {
case *gogen.CodeError:
return v.Pos
case *gogen.MatchError:
return v.Pos()
case *gogen.ImportError:
return v.Pos
}
return token.NoPos
}
func ignNotatedErrs(err error, pkg *ast.Package, fset *token.FileSet) error {
switch v := err.(type) {
case errors.List:
var ret errors.List
for _, e := range v {
if isNotatedErr(e, pkg, fset) {
continue
}
ret = append(ret, e)
}
if len(ret) == 0 {
return ErrIgnoreNotated
}
return ret
default:
if isNotatedErr(err, pkg, fset) {
return ErrIgnoreNotated
}
return err
}
}
func isNotatedErr(err error, pkg *ast.Package, fset *token.FileSet) (notatedErr bool) {
pos := ErrorPos(err)
f := fset.File(pos)
if f == nil {
return
}
gopf, ok := pkg.Files[f.Name()]
if !ok {
return
}
lines := token.Lines(f)
i := f.Line(pos) - 1 // base 0
start := lines[i]
var end int
if i+1 < len(lines) {
end = lines[i+1]
} else {
end = f.Size()
}
text := string(gopf.Code[start:end])
commentOff := strings.Index(text, "//")
if commentOff < 0 {
return
}
return strings.Contains(text[commentOff+2:], "compile error:")
}
// -----------------------------------------------------------------------------
// Config represents a configuration for loading Go+ packages.
type Config struct {
Gop *env.Gop
Fset *token.FileSet
Mod *gopmod.Module
Importer *Importer
Filter func(fs.FileInfo) bool
// If not nil, it is used for returning result of checks Go+ dependencies.
// see https://pkg.go.dev/github.com/goplus/gogen#File.CheckGopDeps
GopDeps *int
// CacheFile specifies the file path of the cache.
CacheFile string
IgnoreNotatedError bool
DontUpdateGoMod bool
}
// ConfFlags represents configuration flags.
type ConfFlags int
const (
ConfFlagIgnoreNotatedError ConfFlags = 1 << iota
ConfFlagDontUpdateGoMod
ConfFlagNoTestFiles
ConfFlagNoCacheFile
)
// NewDefaultConf creates a dfault configuration for common cases.
func NewDefaultConf(dir string, flags ConfFlags) (conf *Config, err error) {
mod, err := LoadMod(dir)
if err != nil {
return
}
gop := gopenv.Get()
fset := token.NewFileSet()
imp := NewImporter(mod, gop, fset)
conf = &Config{
Gop: gop, Fset: fset, Mod: mod, Importer: imp,
IgnoreNotatedError: flags&ConfFlagIgnoreNotatedError != 0,
DontUpdateGoMod: flags&ConfFlagDontUpdateGoMod != 0,
}
if flags&ConfFlagNoCacheFile == 0 {
conf.CacheFile = imp.CacheFile()
imp.Cache().Load(conf.CacheFile)
}
if flags&ConfFlagNoTestFiles != 0 {
conf.Filter = FilterNoTestFiles
}
return
}
func (conf *Config) NewGoCmdConf() *gocmd.Config {
if cl := conf.Mod.Opt.Compiler; cl != nil {
if os.Getenv("GOP_GOCMD") == "" {
os.Setenv("GOP_GOCMD", cl.Name)
}
}
return &gocmd.Config{
Gop: conf.Gop,
}
}
// UpdateCache updates the cache.
func (conf *Config) UpdateCache(verbose ...bool) {
if conf.CacheFile != "" {
c := conf.Importer.Cache()
c.Save(conf.CacheFile)
if verbose != nil && verbose[0] {
fmt.Println("Times of calling go list:", c.ListTimes())
}
}
}
// LoadMod loads a Go+ module from a specified directory.
func LoadMod(dir string) (mod *gopmod.Module, err error) {
mod, err = gopmod.Load(dir)
if err != nil && !gopmod.IsNotFound(err) {
err = errors.NewWith(err, `gopmod.Load(dir, 0)`, -2, "gopmod.Load", dir, 0)
return
}
if mod == nil {
mod = gopmod.Default
}
err = mod.ImportClasses()
if err != nil {
err = errors.NewWith(err, `mod.ImportClasses()`, -2, "(*gopmod.Module).ImportClasses", mod)
}
return
}
// FilterNoTestFiles filters to skip all testing files.
func FilterNoTestFiles(fi fs.FileInfo) bool {
fname := fi.Name()
suffix := ""
switch path.Ext(fname) {
case ".gox":
suffix = "test.gox"
case ".gop":
suffix = "_test.gop"
case ".go":
suffix = "_test.go"
default:
return true
}
return !strings.HasSuffix(fname, suffix)
}
// -----------------------------------------------------------------------------
// LoadDir loads Go+ packages from a specified directory.
func LoadDir(dir string, conf *Config, genTestPkg bool, promptGenGo ...bool) (out, test *gogen.Package, err error) {
if conf == nil {
conf = new(Config)
}
mod := conf.Mod
if mod == nil {
if mod, err = LoadMod(dir); err != nil {
err = errors.NewWith(err, `LoadMod(dir)`, -2, "gop.LoadMod", dir)
return
}
}
fset := conf.Fset
if fset == nil {
fset = token.NewFileSet()
}
pkgs, err := parser.ParseDirEx(fset, dir, parser.Config{
ClassKind: mod.ClassKind,
Filter: conf.Filter,
Mode: parser.ParseComments | parser.SaveAbsFile,
})
if err != nil {
return
}
if len(pkgs) == 0 {
return nil, nil, ErrNotFound
}
gop := conf.Gop
if gop == nil {
gop = gopenv.Get()
}
imp := conf.Importer
if imp == nil {
imp = NewImporter(mod, gop, fset)
}
var pkgTest *ast.Package
var clConf = &cl.Config{
Fset: fset,
RelativeBase: relativeBaseOf(mod),
Importer: imp,
LookupClass: mod.LookupClass,
}
for name, pkg := range pkgs {
if strings.HasSuffix(name, "_test") {
if pkgTest != nil {
return nil, nil, ErrMultiTestPackges
}
pkgTest = pkg
continue
}
if out != nil {
return nil, nil, ErrMultiPackges
}
if len(pkg.Files) == 0 { // no Go+ source files
continue
}
if promptGenGo != nil && promptGenGo[0] {
fmt.Fprintln(os.Stderr, "GenGo", dir, "...")
}
out, err = cl.NewPackage("", pkg, clConf)
if err != nil {
if conf.IgnoreNotatedError {
err = ignNotatedErrs(err, pkg, fset)
}
return
}
}
if out == nil {
return nil, nil, ErrNotFound
}
if genTestPkg && pkgTest != nil {
test, err = cl.NewPackage("", pkgTest, clConf)
}
afterLoad(mod, gop, out, test, conf)
return
}
func afterLoad(mod *gopmod.Module, gop *env.Gop, out, test *gogen.Package, conf *Config) {
if mod.Path() == gopMod { // nothing to do for Go+ itself
return
}
updateMod := !conf.DontUpdateGoMod && mod.HasModfile()
if updateMod || conf.GopDeps != nil {
flags := checkGopDeps(out)
if conf.GopDeps != nil { // for `gop run`
*conf.GopDeps = flags
}
if updateMod {
if test != nil {
flags |= checkGopDeps(test)
}
if flags != 0 {
mod.SaveWithGopMod(gop, flags)
}
}
}
}
func checkGopDeps(pkg *gogen.Package) (flags int) {
pkg.ForEachFile(func(fname string, file *gogen.File) {
flags |= file.CheckGopDeps(pkg)
})
return
}
func relativeBaseOf(mod *gopmod.Module) string {
if mod.HasModfile() {
return mod.Root()
}
dir, _ := os.Getwd()
return dir
}
// -----------------------------------------------------------------------------
// LoadFiles loads a Go+ package from specified files.
func LoadFiles(dir string, files []string, conf *Config) (out *gogen.Package, err error) {
if conf == nil {
conf = new(Config)
}
mod := conf.Mod
if mod == nil {
if mod, err = LoadMod(dir); err != nil {
err = errors.NewWith(err, `LoadMod(dir)`, -2, "gop.LoadMod", dir)
return
}
}
fset := conf.Fset
if fset == nil {
fset = token.NewFileSet()
}
pkgs, err := parser.ParseEntries(fset, files, parser.Config{
ClassKind: mod.ClassKind,
Filter: conf.Filter,
Mode: parser.ParseComments | parser.SaveAbsFile,
})
if err != nil {
err = errors.NewWith(err, `parser.ParseFiles(fset, files, parser.ParseComments)`, -2, "parser.ParseFiles", fset, files, parser.ParseComments)
return
}
if len(pkgs) != 1 {
err = errors.NewWith(ErrMultiPackges, `len(pkgs) != 1`, -1, "!=", len(pkgs), 1)
return
}
gop := conf.Gop
if gop == nil {
gop = gopenv.Get()
}
for _, pkg := range pkgs {
imp := conf.Importer
if imp == nil {
imp = NewImporter(mod, gop, fset)
}
clConf := &cl.Config{
Fset: fset,
RelativeBase: relativeBaseOf(mod),
Importer: imp,
LookupClass: mod.LookupClass,
}
out, err = cl.NewPackage("", pkg, clConf)
if err != nil {
if conf.IgnoreNotatedError {
err = ignNotatedErrs(err, pkg, fset)
}
}
break
}
afterLoad(mod, gop, out, nil, conf)
return
}
// -----------------------------------------------------------------------------
var (
ErrMultiPackges = errors.New("multiple packages")
ErrMultiTestPackges = errors.New("multiple test packages")
)
// -----------------------------------------------------------------------------
// GetFileClassType get gop module file classType.
func GetFileClassType(mod *gopmod.Module, file *ast.File, filename string) (classType string, isTest bool) {
return cl.GetFileClassType(file, filename, mod.LookupClass)
}
// -----------------------------------------------------------------------------