bazelbuild / rules_go

Go rules for Bazel

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use package name instead of go_default_library to define a default library

DrMarcII opened this issue · comments

Currently if you have lib/BUILD with

go_library(
    name = "go_default_library",
    ...
)

That is used in test/test.go, you would import as:

import "go_prefix/lib"

But would have to have the following in test/BUILD file:

go_test(
    name = "test",
    ...
    deps = ["//lib:go_default_library"],
)

It would be cleaner if instead, you could set the name to "lib" in lib/BUILD and have the deps be "//lib" in test/BUILD while keeping the import in test/test.go the same.

TL;DR: will make bazel semantics act strangely.
FYI: If you use gazelle, you won't need to worry about target names in build files

rules_go supports both the OSS Go way: package/binary 1-to-1 with directory
but also the Bazel way: many libs/binaries[/tests] can be in a directory
in this case your import would be
import "go_prefix/lib/lib"

'go_default_library' (and companions) means "do it the OSS way", while anything else means do it the bazel-way.

The kythe project already accomplishes my suggestion through the use of a Skylark macro (maybe we can make this macro a standard part of rules_go?):
https://github.com/google/kythe/blob/master/tools/build_rules/go.bzl

At least one person has requested an even more generalizable approach (have an optional import_name parameter for go_library) that would allow us to accomplish the same thing and more:
https://groups.google.com/d/msg/bazel-discuss/04lYOfQvXec/HOslMu-UCQAJ

I'm the person requesting the importpath parameter.

I think DrMarcII's request is somewhat orthogonal to my request. In particular, I don't want to attain DrMarcII's desired behavior by adding an importpath specification to every one of my BUILD rules. I'd rather behavior described in this Issue be the default, but still have importpath as an override.

All of the Bazel+Go code I've seen relies on the Go OSS way already, since most Go code is written and organized without Bazel in mind. Using the package name instead of the "go_default_library" way would result in cleaner BUILD files in this common case, and the importpath parameter would provide flexibility to those who want to use the Bazel way.

The downside of this approach is that it breaks existing behavior.

The go rules are now capable of operating this way, and do also support an importpath parameter, but gazelle still generates build files with go_default_library type names.
I am going to tag this as a gazelle issue now, it's something we have talked about a lot and would like to make work, but there are some difficult edge cases (for instance, library rules should be named for their package and binary rules should be named for their directory by default, what do we do in cases where those are both the same name)

(Closing old Gazelle issues. This one is migrated to bazelbuild/bazel-gazelle#5).