-
Notifications
You must be signed in to change notification settings - Fork 380
/
package.go
592 lines (544 loc) · 15.3 KB
/
package.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
/* Copyright 2017 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 (
"fmt"
"log"
"path"
"regexp"
"sort"
"strings"
"github.com/bazelbuild/bazel-gazelle/config"
"github.com/bazelbuild/bazel-gazelle/language/proto"
"github.com/bazelbuild/bazel-gazelle/pathtools"
"github.com/bazelbuild/bazel-gazelle/rule"
)
// goPackage contains metadata for a set of .go and .proto files that can be
// used to generate Go rules.
type goPackage struct {
name, dir, rel string
library, binary, test goTarget
proto protoTarget
hasTestdata bool
importPath string
}
// goTarget contains information used to generate an individual Go rule
// (library, binary, or test).
type goTarget struct {
sources, embedSrcs, imports, cppopts, copts, cxxopts, clinkopts platformStringsBuilder
cgo, hasInternalTest bool
}
// protoTarget contains information used to generate a go_proto_library rule.
type protoTarget struct {
name string
sources platformStringsBuilder
imports platformStringsBuilder
hasServices bool
}
// platformStringsBuilder is used to construct rule.PlatformStrings. Bazel
// has some requirements for deps list (a dependency cannot appear in more
// than one select expression; dependencies cannot be duplicated), so we need
// to build these carefully.
type platformStringsBuilder struct {
strs map[string]platformStringInfo
}
// platformStringInfo contains information about a single string (source,
// import, or option).
type platformStringInfo struct {
set platformStringSet
oss map[string]bool
archs map[string]bool
platforms map[rule.Platform]bool
}
type platformStringSet int
const (
genericSet platformStringSet = iota
osSet
archSet
platformSet
)
// Matches a package version, eg. the end segment of 'example.com/foo/v1'
var pkgVersionRe = regexp.MustCompile("^v[0-9]+$")
// addFile adds the file described by "info" to a target in the package "p" if
// the file is buildable.
//
// "cgo" tells whether any ".go" file in the package contains cgo code. This
// affects whether C files are added to targets.
//
// An error is returned if a file is buildable but invalid (for example, a
// test .go file containing cgo code). Files that are not buildable will not
// be added to any target (for example, .txt files).
func (pkg *goPackage) addFile(c *config.Config, er *embedResolver, info fileInfo, cgo bool) error {
switch {
case info.ext == unknownExt || !cgo && (info.ext == cExt || info.ext == csExt):
return nil
case info.ext == protoExt:
if pcMode := getProtoMode(c); pcMode == proto.LegacyMode {
// Only add files in legacy mode. This is used to generate a filegroup
// that contains all protos. In order modes, we get the .proto files
// from information emitted by the proto language extension.
pkg.proto.addFile(info)
}
case info.isTest:
if info.isCgo {
return fmt.Errorf("%s: use of cgo in test not supported", info.path)
}
pkg.test.addFile(c, er, info)
if !info.isExternalTest {
pkg.test.hasInternalTest = true
}
default:
pkg.library.addFile(c, er, info)
}
return nil
}
// isCommand returns true if the package name is "main".
func (pkg *goPackage) isCommand() bool {
return pkg.name == "main"
}
// isBuildable returns true if anything in the package is buildable.
// This is true if the package has Go code that satisfies build constraints
// on any platform or has proto files not in legacy mode.
func (pkg *goPackage) isBuildable(c *config.Config) bool {
return pkg.firstGoFile() != "" || !pkg.proto.sources.isEmpty()
}
// firstGoFile returns the name of a .go file if the package contains at least
// one .go file, or "" otherwise.
func (pkg *goPackage) firstGoFile() string {
goSrcs := []platformStringsBuilder{
pkg.library.sources,
pkg.binary.sources,
pkg.test.sources,
}
for _, sb := range goSrcs {
if sb.strs != nil {
for s := range sb.strs {
if strings.HasSuffix(s, ".go") {
return s
}
}
}
}
return ""
}
func (pkg *goPackage) haveCgo() bool {
return pkg.library.cgo || pkg.binary.cgo || pkg.test.cgo
}
func (pkg *goPackage) inferImportPath(c *config.Config) error {
if pkg.importPath != "" {
log.Panic("importPath already set")
}
gc := getGoConfig(c)
if !gc.prefixSet {
return fmt.Errorf("%s: go prefix is not set, so importpath can't be determined for rules. Set a prefix with a '# gazelle:prefix' comment or with -go_prefix on the command line", pkg.dir)
}
pkg.importPath = InferImportPath(c, pkg.rel)
return nil
}
// libNameFromImportPath returns a a suitable go_library name based on the import path.
// Major version suffixes (eg. "v1") are dropped.
func libNameFromImportPath(dir string) string {
i := strings.LastIndexAny(dir, "/\\")
if i < 0 {
return dir
}
name := dir[i+1:]
if pkgVersionRe.MatchString(name) {
dir := dir[:i]
i = strings.LastIndexAny(dir, "/\\")
if i >= 0 {
name = dir[i+1:]
}
}
return strings.ReplaceAll(name, ".", "_")
}
// libNameByConvention returns a suitable name for a go_library using the given
// naming convention, the import path, and the package name.
func libNameByConvention(nc namingConvention, imp string, pkgName string) string {
if nc == goDefaultLibraryNamingConvention {
return defaultLibName
}
name := libNameFromImportPath(imp)
isCommand := pkgName == "main"
if name == "" {
if isCommand {
name = "lib"
} else {
name = pkgName
}
} else if isCommand {
name += "_lib"
}
return name
}
// testNameByConvention returns a suitable name for a go_test using the given
// naming convention and the import path.
func testNameByConvention(nc namingConvention, imp string) string {
if nc == goDefaultLibraryNamingConvention {
return defaultTestName
}
libName := libNameFromImportPath(imp)
if libName == "" {
libName = "lib"
}
return libName + "_test"
}
// binName returns a suitable name for a go_binary.
func binName(rel, prefix, repoRoot string) string {
return pathtools.RelBaseName(rel, prefix, repoRoot)
}
func InferImportPath(c *config.Config, rel string) string {
gc := getGoConfig(c)
if rel == gc.prefixRel {
return gc.prefix
} else {
fromPrefixRel := strings.TrimPrefix(rel, gc.prefixRel+"/")
return path.Join(gc.prefix, fromPrefixRel)
}
}
func goProtoPackageName(pkg proto.Package) string {
if value, ok := pkg.Options["go_package"]; ok {
if strings.LastIndexByte(value, '/') == -1 {
return value
} else {
if i := strings.LastIndexByte(value, ';'); i != -1 {
return value[i+1:]
} else {
return path.Base(value)
}
}
}
return strings.Replace(pkg.Name, ".", "_", -1)
}
func goProtoImportPath(c *config.Config, pkg proto.Package, rel string) string {
if value, ok := pkg.Options["go_package"]; ok {
if strings.LastIndexByte(value, '/') == -1 {
return InferImportPath(c, rel)
} else if i := strings.LastIndexByte(value, ';'); i != -1 {
return value[:i]
} else {
return value
}
}
return InferImportPath(c, rel)
}
func (t *goTarget) addFile(c *config.Config, er *embedResolver, info fileInfo) {
t.cgo = t.cgo || info.isCgo
add := getPlatformStringsAddFunction(c, info, nil)
add(&t.sources, info.name)
add(&t.imports, info.imports...)
if er != nil {
for _, embed := range info.embeds {
embedSrcs, err := er.resolve(embed)
if err != nil {
log.Print(err)
continue
}
add(&t.embedSrcs, embedSrcs...)
}
}
for _, cppopts := range info.cppopts {
optAdd := add
if !cppopts.empty() {
optAdd = getPlatformStringsAddFunction(c, info, cppopts)
}
optAdd(&t.cppopts, cppopts.opts)
}
for _, copts := range info.copts {
optAdd := add
if !copts.empty() {
optAdd = getPlatformStringsAddFunction(c, info, copts)
}
optAdd(&t.copts, copts.opts)
}
for _, cxxopts := range info.cxxopts {
optAdd := add
if !cxxopts.empty() {
optAdd = getPlatformStringsAddFunction(c, info, cxxopts)
}
optAdd(&t.cxxopts, cxxopts.opts)
}
for _, clinkopts := range info.clinkopts {
optAdd := add
if !clinkopts.empty() {
optAdd = getPlatformStringsAddFunction(c, info, clinkopts)
}
optAdd(&t.clinkopts, clinkopts.opts)
}
}
func protoTargetFromProtoPackage(name string, pkg proto.Package) protoTarget {
target := protoTarget{name: name}
for f := range pkg.Files {
target.sources.addGenericString(f)
}
for i := range pkg.Imports {
target.imports.addGenericString(i)
}
target.hasServices = pkg.HasServices
return target
}
func (t *protoTarget) addFile(info fileInfo) {
t.sources.addGenericString(info.name)
for _, imp := range info.imports {
t.imports.addGenericString(imp)
}
t.hasServices = t.hasServices || info.hasServices
}
// getPlatformStringsAddFunction returns a function used to add strings to
// a *platformStringsBuilder under the same set of constraints. This is a
// performance optimization to avoid evaluating constraints repeatedly.
func getPlatformStringsAddFunction(c *config.Config, info fileInfo, cgoTags *cgoTagsAndOpts) func(sb *platformStringsBuilder, ss ...string) {
isOSSpecific, isArchSpecific := isOSArchSpecific(info, cgoTags)
v := getGoConfig(c).rulesGoVersion
switch {
case !isOSSpecific && !isArchSpecific:
if checkConstraints(c, "", "", info.goos, info.goarch, info.tags, cgoTags) {
return func(sb *platformStringsBuilder, ss ...string) {
for _, s := range ss {
sb.addGenericString(s)
}
}
}
case isOSSpecific && !isArchSpecific:
var osMatch []string
for _, os := range rule.KnownOSs {
if rulesGoSupportsOS(v, os) &&
checkConstraints(c, os, "", info.goos, info.goarch, info.tags, cgoTags) {
osMatch = append(osMatch, os)
}
}
if len(osMatch) > 0 {
return func(sb *platformStringsBuilder, ss ...string) {
for _, s := range ss {
sb.addOSString(s, osMatch)
}
}
}
case !isOSSpecific && isArchSpecific:
var archMatch []string
for _, arch := range rule.KnownArchs {
if rulesGoSupportsArch(v, arch) &&
checkConstraints(c, "", arch, info.goos, info.goarch, info.tags, cgoTags) {
archMatch = append(archMatch, arch)
}
}
if len(archMatch) > 0 {
return func(sb *platformStringsBuilder, ss ...string) {
for _, s := range ss {
sb.addArchString(s, archMatch)
}
}
}
default:
var platformMatch []rule.Platform
for _, platform := range rule.KnownPlatforms {
if rulesGoSupportsPlatform(v, platform) &&
checkConstraints(c, platform.OS, platform.Arch, info.goos, info.goarch, info.tags, cgoTags) {
platformMatch = append(platformMatch, platform)
}
}
if len(platformMatch) > 0 {
return func(sb *platformStringsBuilder, ss ...string) {
for _, s := range ss {
sb.addPlatformString(s, platformMatch)
}
}
}
}
return func(_ *platformStringsBuilder, _ ...string) {}
}
func (sb *platformStringsBuilder) isEmpty() bool {
return sb.strs == nil
}
func (sb *platformStringsBuilder) hasGo() bool {
for s := range sb.strs {
if strings.HasSuffix(s, ".go") {
return true
}
}
return false
}
func (sb *platformStringsBuilder) addGenericString(s string) {
if sb.strs == nil {
sb.strs = make(map[string]platformStringInfo)
}
sb.strs[s] = platformStringInfo{set: genericSet}
}
func (sb *platformStringsBuilder) addOSString(s string, oss []string) {
if sb.strs == nil {
sb.strs = make(map[string]platformStringInfo)
}
si, ok := sb.strs[s]
if !ok {
si.set = osSet
si.oss = make(map[string]bool)
}
switch si.set {
case genericSet:
return
case osSet:
for _, os := range oss {
si.oss[os] = true
}
default:
si.convertToPlatforms()
for _, os := range oss {
for _, arch := range rule.KnownOSArchs[os] {
si.platforms[rule.Platform{OS: os, Arch: arch}] = true
}
}
}
sb.strs[s] = si
}
func (sb *platformStringsBuilder) addArchString(s string, archs []string) {
if sb.strs == nil {
sb.strs = make(map[string]platformStringInfo)
}
si, ok := sb.strs[s]
if !ok {
si.set = archSet
si.archs = make(map[string]bool)
}
switch si.set {
case genericSet:
return
case archSet:
for _, arch := range archs {
si.archs[arch] = true
}
default:
si.convertToPlatforms()
for _, arch := range archs {
for _, os := range rule.KnownArchOSs[arch] {
si.platforms[rule.Platform{OS: os, Arch: arch}] = true
}
}
}
sb.strs[s] = si
}
func (sb *platformStringsBuilder) addPlatformString(s string, platforms []rule.Platform) {
if sb.strs == nil {
sb.strs = make(map[string]platformStringInfo)
}
si, ok := sb.strs[s]
if !ok {
si.set = platformSet
si.platforms = make(map[rule.Platform]bool)
}
switch si.set {
case genericSet:
return
default:
si.convertToPlatforms()
for _, p := range platforms {
si.platforms[p] = true
}
}
sb.strs[s] = si
}
func (sb *platformStringsBuilder) build() rule.PlatformStrings {
var ps rule.PlatformStrings
for s, si := range sb.strs {
switch si.set {
case genericSet:
ps.Generic = append(ps.Generic, s)
case osSet:
if ps.OS == nil {
ps.OS = make(map[string][]string)
}
for os := range si.oss {
ps.OS[os] = append(ps.OS[os], s)
}
case archSet:
if ps.Arch == nil {
ps.Arch = make(map[string][]string)
}
for arch := range si.archs {
ps.Arch[arch] = append(ps.Arch[arch], s)
}
case platformSet:
if ps.Platform == nil {
ps.Platform = make(map[rule.Platform][]string)
}
for p := range si.platforms {
ps.Platform[p] = append(ps.Platform[p], s)
}
}
}
sort.Strings(ps.Generic)
if ps.OS != nil {
for _, ss := range ps.OS {
sort.Strings(ss)
}
}
if ps.Arch != nil {
for _, ss := range ps.Arch {
sort.Strings(ss)
}
}
if ps.Platform != nil {
for _, ss := range ps.Platform {
sort.Strings(ss)
}
}
return ps
}
func (sb *platformStringsBuilder) buildFlat() []string {
strs := make([]string, 0, len(sb.strs))
for s := range sb.strs {
strs = append(strs, s)
}
sort.Strings(strs)
return strs
}
func (si *platformStringInfo) convertToPlatforms() {
switch si.set {
case genericSet:
log.Panic("cannot convert generic string to platforms")
case platformSet:
return
case osSet:
si.set = platformSet
si.platforms = make(map[rule.Platform]bool)
for os := range si.oss {
for _, arch := range rule.KnownOSArchs[os] {
si.platforms[rule.Platform{OS: os, Arch: arch}] = true
}
}
si.oss = nil
case archSet:
si.set = platformSet
si.platforms = make(map[rule.Platform]bool)
for arch := range si.archs {
for _, os := range rule.KnownArchOSs[arch] {
si.platforms[rule.Platform{OS: os, Arch: arch}] = true
}
}
si.archs = nil
}
}
var semverRex = regexp.MustCompile(`^.*?(/v\d+)(?:/.*)?$`)
// pathWithoutSemver removes a semantic version suffix from path.
// For example, if path is "example.com/foo/v2/bar", pathWithoutSemver
// will return "example.com/foo/bar". If there is no semantic version suffix,
// "" will be returned.
func pathWithoutSemver(path string) string {
m := semverRex.FindStringSubmatchIndex(path)
if m == nil {
return ""
}
v := path[m[2]+2 : m[3]]
if v[0] == '0' || v == "1" {
return ""
}
return path[:m[2]] + path[m[3]:]
}