Skip to content

Commit

Permalink
language/go should consider default_visibility set by OtherGen (bazel…
Browse files Browse the repository at this point in the history
…build#783)

Previously, the implementation of the language/go extension's GenerateRules method only considered args.File, and therefore missed scenarios where another extension (as recommended in the Issue) creates a package(default_visibility = ...)
  • Loading branch information
dnathe4th committed Oct 5, 2022
1 parent 05f5493 commit 9feecad
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
17 changes: 16 additions & 1 deletion language/go/generate.go
Expand Up @@ -181,7 +181,7 @@ func (gl *goLang) GenerateRules(args language.GenerateArgs) language.GenerateRes
g := &generator{
c: c,
rel: args.Rel,
shouldSetVisibility: args.File == nil || !args.File.HasDefaultVisibility(),
shouldSetVisibility: shouldSetVisibility(args),
}
var res language.GenerateResult
var rules []*rule.Rule
Expand Down Expand Up @@ -776,3 +776,18 @@ func escapeOption(opt string) string {
"$", "$$",
).Replace(opt)
}

func shouldSetVisibility(args language.GenerateArgs) bool {
if args.File != nil && args.File.HasDefaultVisibility() {
return false
}

for _, r := range args.OtherGen {
// This is kind of the same test as *File.HasDefaultVisibility(),
// but for previously defined rules.
if r.Kind() == "package" && r.Attr("default_visibility") != nil {
return false
}
}
return true
}
29 changes: 29 additions & 0 deletions language/go/generate_test.go
Expand Up @@ -262,6 +262,35 @@ func TestConsumedGenFiles(t *testing.T) {
}
}

// Test visibility attribute is only set if no default visibility is provided
// by the file or other rules.
func TestShouldSetVisibility(t *testing.T) {
if !shouldSetVisibility(language.GenerateArgs{}) {
t.Error("got 'False' for shouldSetVisibility with default args; expected 'True'")
}

if !shouldSetVisibility(language.GenerateArgs{
File: rule.EmptyFile("path", "pkg"),
}) {
t.Error("got 'False' for shouldSetVisibility with empty file; expected 'True'")
}

fileWithDefaultVisibile, _ := rule.LoadData("path", "pkg", []byte(`package(default_visibility = "//src:__subpackages__")`))
if shouldSetVisibility(language.GenerateArgs{
File: fileWithDefaultVisibile,
}) {
t.Error("got 'True' for shouldSetVisibility with file with default visibility; expected 'False'")
}

defaultVisibilityRule := rule.NewRule("package", "")
defaultVisibilityRule.SetAttr("default_visibility", []string{"//src:__subpackages__"})
if shouldSetVisibility(language.GenerateArgs{
OtherGen: []*rule.Rule{defaultVisibilityRule},
}) {
t.Error("got 'True' for shouldSetVisibility with rule defining a default visibility; expected 'False'")
}
}

func prebuiltProtoRules() []*rule.Rule {
protoRule := rule.NewRule("proto_library", "foo_proto")
protoRule.SetAttr("srcs", []string{"foo.proto"})
Expand Down

0 comments on commit 9feecad

Please sign in to comment.