-
Notifications
You must be signed in to change notification settings - Fork 17
/
resolve.go
431 lines (354 loc) · 12.1 KB
/
resolve.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
422
423
424
425
426
427
428
429
430
431
package gazelle
import (
"fmt"
"os"
"path"
"strings"
"time"
common "aspect.build/cli/gazelle/common"
node "aspect.build/cli/gazelle/js/node"
proto "aspect.build/cli/gazelle/js/proto"
BazelLog "aspect.build/cli/pkg/logger"
"github.com/bazelbuild/bazel-gazelle/config"
"github.com/bazelbuild/bazel-gazelle/label"
"github.com/bazelbuild/bazel-gazelle/repo"
"github.com/bazelbuild/bazel-gazelle/resolve"
"github.com/bazelbuild/bazel-gazelle/rule"
"github.com/emirpasic/gods/sets/treeset"
)
// Resolver satisfies the resolve.Resolver interface. It resolves dependencies
// in rules generated by this extension.
type Resolver struct {
lang *typeScriptLang
}
func NewResolver(lang *typeScriptLang) resolve.Resolver {
return &Resolver{
lang: lang,
}
}
const (
Resolution_Error = -1
Resolution_None = 0
Resolution_NotFound = 1
Resolution_Package = 2
Resolution_Label = 3
Resolution_NativeNode = 4
Resolution_Override = 5
)
type ResolutionType = int
// Name returns the name of the language. This is the prefix of the kinds of
// rules generated. E.g. ts_project
func (*Resolver) Name() string { return LanguageName }
// Determine what rule (r) outputs which can be imported.
// For TypeScript this is all the import-paths pointing to files within the rule.
func (ts *Resolver) Imports(c *config.Config, r *rule.Rule, f *rule.File) []resolve.ImportSpec {
BazelLog.Debugf("Imports '%s:%s'", f.Pkg, r.Name())
switch r.Kind() {
case TsProtoLibraryKind:
return ts.protoLibraryImports(r, f)
case TsConfigKind:
return ts.tsconfigImports(r, f)
default:
return ts.sourceFileImports(r, f)
}
}
// TypeScript-importable ImportSpecs from a set of source files.
func (ts *Resolver) sourceFileImports(r *rule.Rule, f *rule.File) []resolve.ImportSpec {
srcs := r.AttrStrings("srcs")
provides := make([]resolve.ImportSpec, 0, len(srcs)+1)
// Sources that produce importable paths.
for _, src := range srcs {
src = path.Clean(path.Join(f.Pkg, src))
for _, impt := range toImportPaths(src) {
provides = append(provides, resolve.ImportSpec{
Lang: LanguageName,
Imp: impt,
})
}
}
if len(provides) == 0 {
return nil
}
return provides
}
func (ts *Resolver) tsconfigImports(r *rule.Rule, f *rule.File) []resolve.ImportSpec {
// Only the tsconfig file itself is exposed.
// The output is the same as the ts_config(src) input.
return []resolve.ImportSpec{
{
Lang: LanguageName,
Imp: path.Join(f.Pkg, r.AttrString("src")),
},
}
}
// TypeScript-importable ImportSpecs from a TsProtoLibrary rule.
func (ts *Resolver) protoLibraryImports(r *rule.Rule, f *rule.File) []resolve.ImportSpec {
protoSrcs := r.PrivateAttr("proto_library_srcs").([]string)
provides := make([]resolve.ImportSpec, 0, len(protoSrcs)+1)
for _, src := range protoSrcs {
src = path.Clean(path.Join(f.Pkg, src))
for _, dts := range proto.ToTsPaths(src) {
for _, impt := range toImportPaths(dts) {
provides = append(provides, resolve.ImportSpec{
Lang: LanguageName,
Imp: impt,
})
}
}
}
if len(provides) == 0 {
return nil
}
return provides
}
// Embeds returns a list of labels of rules that the given rule embeds. If
// a rule is embedded by another importable rule of the same language, only
// the embedding rule will be indexed. The embedding rule will inherit
// the imports of the embedded rule.
func (ts *Resolver) Embeds(r *rule.Rule, from label.Label) []label.Label {
BazelLog.Debugf("Embeds %q rules", from.String())
switch r.Kind() {
case TsProjectKind:
srcs := r.AttrStrings("srcs")
tsEmbeds := make([]label.Label, 0, len(srcs))
// The compiled dts and js files are accessible as embedded rules
for _, src := range srcs {
if isTranspiledSourceFileType(src) {
js := swapSourceExtension(src)
dts := path.Base(js) + ".d" + path.Ext(js)
tsEmbeds = append(tsEmbeds, label.New(from.Repo, from.Pkg, js))
tsEmbeds = append(tsEmbeds, label.New(from.Repo, from.Pkg, dts))
}
}
return tsEmbeds
}
// TODO(jbedard): ts_proto_library() embeds
// TODO(jbedard): implement other rule kinds
return make([]label.Label, 0)
}
// Resolve translates imported libraries for a given rule into Bazel
// dependencies. Information about imported libraries is returned for each
// rule generated by language.GenerateRules in
// language.GenerateResult.Imports. Resolve generates a "deps" attribute (or
// the appropriate language-specific equivalent) for each import according to
// language-specific rules and heuristics.
func (ts *Resolver) Resolve(
c *config.Config,
ix *resolve.RuleIndex,
rc *repo.RemoteCache,
r *rule.Rule,
importData interface{},
from label.Label,
) {
start := time.Now()
BazelLog.Infof("Resolve %q dependencies", from.String())
// TsProject imports are resolved as deps
if r.Kind() == TsProjectKind || r.Kind() == JsLibraryKind || r.Kind() == TsConfigKind || r.Kind() == TsProtoLibraryKind {
deps, err := ts.resolveModuleDeps(c, ix, importData.(*TsProjectInfo).imports, from)
if err != nil {
BazelLog.Fatalf("Resolution Error: ", err)
os.Exit(1)
}
if !deps.Empty() {
r.SetAttr("deps", deps.Labels())
}
}
BazelLog.Infof("Resolve %q DONE in %s", from.String(), time.Since(start).String())
}
func (ts *Resolver) resolveModuleDeps(
c *config.Config,
ix *resolve.RuleIndex,
modules *treeset.Set,
from label.Label,
) (*common.LabelSet, error) {
cfg := c.Exts[LanguageName].(*JsGazelleConfig)
deps := common.NewLabelSet(from)
resolutionErrors := []error{}
it := modules.Iterator()
for it.Next() {
mod := it.Value().(ImportStatement)
resolutionType, dep, err := ts.resolveModuleDep(c, ix, mod, from)
if err != nil {
return nil, err
}
types := ts.resolveImportTypes(resolutionType, from, mod.Imp)
for _, typesDep := range types {
deps.Add(typesDep)
}
if dep != nil {
deps.Add(dep)
}
// Neither the import or a type definition was found.
if resolutionType == Resolution_NotFound && len(types) == 0 {
if cfg.ValidateImportStatements() != ValidationOff {
BazelLog.Debugf("import %q for target %q not found", mod.ImportPath, from.String())
notFound := fmt.Errorf(
"Import %[1]q from %[2]q is an unknown dependency. Possible solutions:\n"+
"\t1. Instruct Gazelle to resolve to a known dependency using a directive:\n"+
"\t\t# gazelle:resolve [src-lang] js import-string label\n"+
"\t\t or\n"+
"\t\t# gazelle:js_resolve import-string-glob label\n"+
"\t2. Ignore the dependency using the '# gazelle:%[3]s %[1]s' directive.\n"+
"\t3. Disable Gazelle resolution validation using '# gazelle:%[4]s off'",
mod.ImportPath, mod.SourcePath, Directive_IgnoreImports, Directive_ValidateImportStatements,
)
resolutionErrors = append(resolutionErrors, notFound)
}
continue
}
}
// Log any resolution errorsResolution errors and error out.
if len(resolutionErrors) > 0 {
joinedErrs := ""
for _, err := range resolutionErrors {
joinedErrs = fmt.Sprintf("%s\n\n%s", joinedErrs, err)
}
switch cfg.ValidateImportStatements() {
case ValidationError:
fmt.Fprintf(os.Stderr, "Failed to validate dependencies for target %q:%v\n", from.String(), joinedErrs)
os.Exit(1)
case ValidationWarn:
fmt.Fprintf(os.Stderr, "Warning: Failed to validate dependencies for target %q:%v\n", from.String(), joinedErrs)
}
}
return deps, nil
}
func (ts *Resolver) resolveModuleDep(
c *config.Config,
ix *resolve.RuleIndex,
mod ImportStatement,
from label.Label,
) (ResolutionType, *label.Label, error) {
cfg := c.Exts[LanguageName].(*JsGazelleConfig)
imp := mod.ImportSpec
// Overrides
if override, ok := resolve.FindRuleWithOverride(c, imp, LanguageName); ok {
return Resolution_Override, &override, nil
}
// JS Overrides (js_resolve)
if res := cfg.GetResolution(imp.Imp); res != nil {
return Resolution_Override, res, nil
}
possible := make([]resolve.ImportSpec, 0, 1)
possible = append(possible, mod.ImportSpec)
for _, expandedImp := range mod.Alt {
possible = append(possible, resolve.ImportSpec{Lang: mod.Lang, Imp: expandedImp})
}
// Gazelle rule index. Try each potential expanded path
for _, eImp := range possible {
if matches := ix.FindRulesByImportWithConfig(c, eImp, LanguageName); len(matches) > 0 {
filteredMatches := make([]label.Label, 0, len(matches))
for _, match := range matches {
// Prevent from adding itself as a dependency.
if !match.IsSelfImport(from) {
filteredMatches = append(filteredMatches, match.Label)
}
}
// Too many results, don't know which is correct
if len(filteredMatches) > 1 {
return Resolution_Error, nil, fmt.Errorf(
"Import %q from %q resolved to multiple targets (%s)"+
" - this must be fixed using the \"gazelle:resolve\" directive",
mod.ImportPath, mod.SourcePath, targetListFromResults(matches))
}
// The matches were self imports, no dependency is needed
if len(filteredMatches) == 0 {
return Resolution_None, nil, nil
}
match := filteredMatches[0]
BazelLog.Tracef("resolve %q import %q as %q", mod.Imp, match)
return Resolution_Override, &match, nil
}
}
// References to a label such as a file or file-generating rule
if importLabel := ts.lang.GetImportLabel(imp.Imp); importLabel != nil {
return Resolution_Label, importLabel, nil
}
// References to an npm package, pnpm workspace projects etc.
if pkg := ts.resolvePackage(from, mod.Imp); pkg != nil {
return Resolution_Package, pkg, nil
}
// Native node imports
if node.IsNodeImport(imp.Imp) {
return Resolution_NativeNode, nil, nil
}
return Resolution_NotFound, nil, nil
}
func (ts *Resolver) resolvePackage(from label.Label, imp string) *label.Label {
// Imports of npm-like packages
// Trim to only the package name or scoped package name
parts := strings.SplitN(imp, "/", 2)
if parts[0][0] == "@"[0] {
parts[1] = strings.SplitN(parts[1], "/", 2)[0]
} else {
parts = parts[0:1]
}
impPkg := path.Join(parts...)
fromProject := ts.lang.pnpmProjects.GetProject(from.Pkg)
if fromProject == nil {
BazelLog.Tracef("resolve %q import %q project not found", from.String(), impPkg)
return nil
}
impPkgLabel := fromProject.Get(impPkg)
if impPkgLabel == nil {
BazelLog.Tracef("resolve %q import %q not found", from.String(), impPkg)
return nil
}
BazelLog.Tracef("resolve %q import %q to %q", from.String(), impPkg, impPkgLabel)
return impPkgLabel
}
func (ts *Resolver) resolveImportTypes(resolutionType ResolutionType, from label.Label, imp string) []*label.Label {
deps := make([]*label.Label, 0)
// Overrides are not extended with additional types
if resolutionType == Resolution_Override {
return deps
}
if resolutionType == Resolution_NativeNode {
// The @types package for native node
if typesNode := ts.resolveAtTypes(from, "node"); typesNode != nil {
deps = append(deps, typesNode)
}
} else {
// @types packages for any named imports
// The import may be a package, may be an unresolved import with only @types
if typesPkg := ts.resolveAtTypes(from, imp); typesPkg != nil {
deps = append(deps, typesPkg)
}
}
// Additional module definitions for the import
if typeModules := ts.lang.moduleTypes[imp]; typeModules != nil {
deps = append(deps, typeModules...)
}
return deps
}
func toAtTypesPackage(imp string) string {
pkgParts := strings.Split(imp, "/")
if imp[0] == '@' {
if len(pkgParts) < 2 {
BazelLog.Errorf("Invalid scoped package: %q", imp)
return ""
}
pkgParts = []string{pkgParts[0][1:], pkgParts[1]}
} else {
pkgParts = []string{pkgParts[0]}
}
return path.Join("@types", strings.Join(pkgParts, "__"))
}
// Find and resolve any @types package for an import
func (ts *Resolver) resolveAtTypes(from label.Label, imp string) *label.Label {
fromProject := ts.lang.pnpmProjects.GetProject(from.Pkg)
if fromProject == nil {
return nil
}
typesPkg := toAtTypesPackage(imp)
return fromProject.Get(typesPkg)
}
// targetListFromResults returns a string with the human-readable list of
// targets contained in the given results.
func targetListFromResults(results []resolve.FindResult) string {
list := make([]string, len(results))
for i, result := range results {
list[i] = result.Label.String()
}
return strings.Join(list, ", ")
}