-
Notifications
You must be signed in to change notification settings - Fork 387
/
Copy pathresolve.go
395 lines (359 loc) · 13.2 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
/* Copyright 2018 The Bazel Authors. 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 golang
import (
"errors"
"fmt"
"go/build"
"log"
"path"
"strings"
"github.com/bazelbuild/bazel-gazelle/config"
"github.com/bazelbuild/bazel-gazelle/label"
"github.com/bazelbuild/bazel-gazelle/pathtools"
"github.com/bazelbuild/bazel-gazelle/repo"
"github.com/bazelbuild/bazel-gazelle/resolve"
"github.com/bazelbuild/bazel-gazelle/rule"
)
func (*goLang) Imports(_ *config.Config, r *rule.Rule, f *rule.File) []resolve.ImportSpec {
if !isGoLibrary(r.Kind()) || isExtraLibrary(r) {
return nil
}
if importPath := r.AttrString("importpath"); importPath == "" {
return []resolve.ImportSpec{}
} else {
return []resolve.ImportSpec{{
Lang: goName,
Imp: importPath,
}}
}
}
func (*goLang) Embeds(r *rule.Rule, from label.Label) []label.Label {
embedStrings := r.AttrStrings("embed")
if isGoProtoLibrary(r.Kind()) {
embedStrings = append(embedStrings, r.AttrString("proto"))
embedStrings = append(embedStrings, r.AttrStrings("protos")...)
}
embedLabels := make([]label.Label, 0, len(embedStrings))
for _, s := range embedStrings {
l, err := label.Parse(s)
if err != nil {
continue
}
l = l.Abs(from.Repo, from.Pkg)
embedLabels = append(embedLabels, l)
}
return embedLabels
}
func (gl *goLang) Resolve(c *config.Config, ix *resolve.RuleIndex, rc *repo.RemoteCache, r *rule.Rule, importsRaw interface{}, from label.Label) {
if importsRaw == nil {
// may not be set in tests.
return
}
imports := importsRaw.(rule.PlatformStrings)
r.DelAttr("deps")
var resolve func(*config.Config, *resolve.RuleIndex, *repo.RemoteCache, string, label.Label) (label.Label, error)
switch r.Kind() {
case "go_proto_library":
resolve = resolveProto
default:
resolve = ResolveGo
}
deps, errs := imports.Map(func(imp string) (string, error) {
l, err := resolve(c, ix, rc, imp, from)
if err == errSkipImport {
return "", nil
} else if err != nil {
return "", err
}
for _, embed := range gl.Embeds(r, from) {
if embed.Equal(l) {
return "", nil
}
}
l = l.Rel(from.Repo, from.Pkg)
return l.String(), nil
})
for _, err := range errs {
log.Print(err)
}
if !deps.IsEmpty() {
if r.Kind() == "go_proto_library" {
// protos may import the same library multiple times by different names,
// so we need to de-duplicate them. Protos are not platform-specific,
// so it's safe to just flatten them.
r.SetAttr("deps", deps.Flat())
} else {
r.SetAttr("deps", deps)
}
}
}
var (
errSkipImport = errors.New("std or self import")
errNotFound = errors.New("rule not found")
)
// ResolveGo resolves a Go import path to a Bazel label, possibly using the
// given rule index and remote cache. Some special cases may be applied to
// known proto import paths, depending on the current proto mode.
//
// This may be used directly by other language extensions related to Go
// (gomock). Gazelle calls Language.Resolve instead.
func ResolveGo(c *config.Config, ix *resolve.RuleIndex, rc *repo.RemoteCache, imp string, from label.Label) (label.Label, error) {
gc := getGoConfig(c)
if build.IsLocalImport(imp) {
cleanRel := path.Clean(path.Join(from.Pkg, imp))
if build.IsLocalImport(cleanRel) {
return label.NoLabel, fmt.Errorf("relative import path %q from %q points outside of repository", imp, from.Pkg)
}
imp = path.Join(gc.prefix, cleanRel)
}
if IsStandard(imp) {
return label.NoLabel, errSkipImport
}
if l, ok := resolve.FindRuleWithOverride(c, resolve.ImportSpec{Lang: "go", Imp: imp}, "go"); ok {
return l, nil
}
if l, err := resolveWithIndexGo(c, ix, imp, from); err == nil || err == errSkipImport {
return l, err
} else if err != errNotFound {
return label.NoLabel, err
}
// Special cases for rules_go and bazel_gazelle.
// These have names that don't following conventions and they're
// typeically declared with http_archive, not go_repository, so Gazelle
// won't recognize them.
if !c.Bzlmod {
if pathtools.HasPrefix(imp, "github.com/bazelbuild/rules_go") {
pkg := pathtools.TrimPrefix(imp, "github.com/bazelbuild/rules_go")
return label.New("io_bazel_rules_go", pkg, "go_default_library"), nil
} else if pathtools.HasPrefix(imp, "github.com/bazelbuild/bazel-gazelle") {
pkg := pathtools.TrimPrefix(imp, "github.com/bazelbuild/bazel-gazelle")
return label.New("bazel_gazelle", pkg, "go_default_library"), nil
}
}
if !c.IndexLibraries {
// packages in current repo were not indexed, relying on prefix to decide what may have been in
// current repo
if pathtools.HasPrefix(imp, gc.prefix) {
pkg := path.Join(gc.prefixRel, pathtools.TrimPrefix(imp, gc.prefix))
libName := libNameByConvention(gc.goNamingConvention, imp, "")
return label.New("", pkg, libName), nil
}
}
if gc.depMode == vendorMode {
return resolveVendored(gc, imp)
}
var resolveFn func(string) (string, string, error)
if gc.depMode == staticMode {
resolveFn = rc.RootStatic
} else if gc.moduleMode || pathWithoutSemver(imp) != "" {
resolveFn = rc.Mod
} else {
resolveFn = rc.Root
}
return resolveToExternalLabel(c, resolveFn, imp)
}
// IsStandard returns whether a package is in the standard library.
func IsStandard(imp string) bool {
return stdPackages[imp]
}
func resolveWithIndexGo(c *config.Config, ix *resolve.RuleIndex, imp string, from label.Label) (label.Label, error) {
matches := ix.FindRulesByImportWithConfig(c, resolve.ImportSpec{Lang: "go", Imp: imp}, "go")
var bestMatch resolve.FindResult
var bestMatchIsVendored bool
var bestMatchVendorRoot string
var bestMatchEmbedsProtos bool
var matchError error
goRepositoryMode := getGoConfig(c).goRepositoryMode
for _, m := range matches {
// Apply vendoring logic for Go libraries. A library in a vendor directory
// is only visible in the parent tree. Vendored libraries supercede
// non-vendored libraries, and libraries closer to from.Pkg supercede
// those further up the tree.
//
// Also, in external repositories, prefer go_proto_library targets to checked-in .go files
// pregenerated from .proto files over go_proto_library targets. Ideally, the two should be
// in sync. If not, users can choose between the two by using the go_generate_proto
// directive.
isVendored := false
vendorRoot := ""
parts := strings.Split(m.Label.Pkg, "/")
for i := len(parts) - 1; i >= 0; i-- {
if parts[i] == "vendor" {
isVendored = true
vendorRoot = strings.Join(parts[:i], "/")
break
}
}
if isVendored && !label.New(m.Label.Repo, vendorRoot, "").Contains(from) {
// vendor directory not visible
continue
}
embedsProtos := false
for _, embed := range m.Embeds {
if strings.HasSuffix(embed.Name, goProtoSuffix) {
embedsProtos = true
}
}
if bestMatch.Label.Equal(label.NoLabel) ||
(isVendored && (!bestMatchIsVendored || len(vendorRoot) > len(bestMatchVendorRoot))) ||
(goRepositoryMode && !bestMatchEmbedsProtos && embedsProtos) {
// Current match is better
bestMatch = m
bestMatchIsVendored = isVendored
bestMatchVendorRoot = vendorRoot
bestMatchEmbedsProtos = embedsProtos
matchError = nil
} else if (!isVendored && bestMatchIsVendored) ||
(isVendored && len(vendorRoot) < len(bestMatchVendorRoot)) ||
(goRepositoryMode && bestMatchEmbedsProtos && !embedsProtos) {
// Current match is worse
} else {
// Match is ambiguous
// TODO: consider listing all the ambiguous rules here.
matchError = fmt.Errorf("rule %s imports %q which matches multiple rules: %s and %s. # gazelle:resolve may be used to disambiguate", from, imp, bestMatch.Label, m.Label)
}
}
if matchError != nil {
return label.NoLabel, matchError
}
if bestMatch.Label.Equal(label.NoLabel) {
return label.NoLabel, errNotFound
}
if bestMatch.IsSelfImport(from) {
return label.NoLabel, errSkipImport
}
return bestMatch.Label, nil
}
func resolveToExternalLabel(c *config.Config, resolveFn func(string) (string, string, error), imp string) (label.Label, error) {
prefix, repo, err := resolveFn(imp)
if err != nil {
return label.NoLabel, err
} else if prefix == "" && repo == "" {
return label.NoLabel, errSkipImport
}
var pkg string
if pathtools.HasPrefix(imp, prefix) {
pkg = pathtools.TrimPrefix(imp, prefix)
} else if impWithoutSemver := pathWithoutSemver(imp); pathtools.HasPrefix(impWithoutSemver, prefix) {
// We may have used minimal module compatibility to resolve a path
// without a semantic import version suffix to a repository that has one.
pkg = pathtools.TrimPrefix(impWithoutSemver, prefix)
}
// Determine what naming convention is used by the repository.
// If there is no known repository, it's probably declared in an http_archive
// somewhere like go_rules_dependencies, so use the old naming convention,
// unless the user has explicitly told us otherwise.
// If the repository uses the import_alias convention (default for
// go_repository), use the convention from the current directory unless the
// user has told us otherwise.
gc := getGoConfig(c)
nc := gc.repoNamingConvention[repo]
if nc == unknownNamingConvention {
if gc.goNamingConventionExternal != unknownNamingConvention {
nc = gc.goNamingConventionExternal
} else {
nc = goDefaultLibraryNamingConvention
}
} else if nc == importAliasNamingConvention {
if gc.goNamingConventionExternal != unknownNamingConvention {
nc = gc.goNamingConventionExternal
} else {
nc = gc.goNamingConvention
}
}
name := libNameByConvention(nc, imp, "")
return label.New(repo, pkg, name), nil
}
func resolveVendored(gc *goConfig, imp string) (label.Label, error) {
name := libNameByConvention(gc.goNamingConvention, imp, "")
return label.New("", path.Join("vendor", imp), name), nil
}
func resolveProto(c *config.Config, ix *resolve.RuleIndex, rc *repo.RemoteCache, imp string, from label.Label) (label.Label, error) {
if wellKnownProtos[imp] {
return label.NoLabel, errSkipImport
}
if l, ok := resolve.FindRuleWithOverride(c, resolve.ImportSpec{Lang: "proto", Imp: imp}, "go"); ok {
return l, nil
}
if l, err := resolveWithIndexProto(c, ix, imp, from); err == nil || err == errSkipImport {
return l, err
} else if err != errNotFound {
return label.NoLabel, err
}
// As a fallback, guess the label based on the proto file name. We assume
// all proto files in a directory belong to the same package, and the
// package name matches the directory base name. We also assume that protos
// in the vendor directory must refer to something else in vendor.
rel := path.Dir(imp)
if rel == "." {
rel = ""
}
if from.Pkg == "vendor" || strings.HasPrefix(from.Pkg, "vendor/") {
rel = path.Join("vendor", rel)
}
libName := libNameByConvention(getGoConfig(c).goNamingConvention, imp, "")
return label.New("", rel, libName), nil
}
// wellKnownProtos is the set of proto sets for which we don't need to add
// an explicit dependency in go_proto_library.
// TODO(jayconrod): generate from
// @io_bazel_rules_go//proto/wkt:WELL_KNOWN_TYPE_PACKAGES
var wellKnownProtos = map[string]bool{
"google/protobuf/any.proto": true,
"google/protobuf/api.proto": true,
"google/protobuf/compiler/plugin.proto": true,
"google/protobuf/descriptor.proto": true,
"google/protobuf/duration.proto": true,
"google/protobuf/empty.proto": true,
"google/protobuf/field_mask.proto": true,
"google/protobuf/source_context.proto": true,
"google/protobuf/struct.proto": true,
"google/protobuf/timestamp.proto": true,
"google/protobuf/type.proto": true,
"google/protobuf/wrappers.proto": true,
}
func resolveWithIndexProto(c *config.Config, ix *resolve.RuleIndex, imp string, from label.Label) (label.Label, error) {
matches := ix.FindRulesByImportWithConfig(c, resolve.ImportSpec{Lang: "proto", Imp: imp}, "go")
if len(matches) == 0 {
return label.NoLabel, errNotFound
}
if len(matches) > 1 {
return label.NoLabel, fmt.Errorf("multiple rules (%s and %s) may be imported with %q from %s", matches[0].Label, matches[1].Label, imp, from)
}
if matches[0].IsSelfImport(from) {
return label.NoLabel, errSkipImport
}
return matches[0].Label, nil
}
func isGoLibrary(kind string) bool {
return kind == "go_library" || isGoProtoLibrary(kind)
}
func isGoProtoLibrary(kind string) bool {
return kind == "go_proto_library" || kind == "go_grpc_library"
}
// isExtraLibrary returns true if this rule is one of a handful of proto
// libraries generated by maybeGenerateExtraLib. It should not be indexed for
// dependency resolution.
func isExtraLibrary(r *rule.Rule) bool {
if !strings.HasSuffix(r.Name(), "_gen") {
return false
}
switch r.AttrString("importpath") {
case "github.com/golang/protobuf/descriptor",
"github.com/golang/protobuf/protoc-gen-go/generator",
"github.com/golang/protobuf/ptypes":
return true
default:
return false
}
}