Giter Site home page Giter Site logo

bazelbuild / rules_go Goto Github PK

View Code? Open in Web Editor NEW
1.3K 54.0 632.0 12.43 MB

Go rules for Bazel

License: Apache License 2.0

Python 1.39% Go 54.52% Assembly 0.34% C 0.39% Shell 0.32% C++ 0.18% Smarty 0.01% Objective-C 0.08% Starlark 42.74% Objective-C++ 0.03%
bazel bazel-rules golang cgo go

rules_go's Introduction

Go rules for Bazel

Mailing list: bazel-go-discuss

Slack: #go on Bazel Slack, #bazel on Go Slack

Announcements

2024-01-04

Release v0.44.2 is now available. This includes two bug fixes (#3808 and #3810) with the test timeout handler.

2023-12-29

Release v0.44.1 is now available. This release reverts a forced upgrade (#3803) of genproto from v0.44.0.

2023-12-15

Release v0.44.0 is now available. This release adds a stacktrace when a test times out and adds support for nogo in Bzlmod.

2023-11-20

Release v0.43.0 is now available. This release fixes a couple bugs and upgrades x/tools to the latest version.

2023-09-28

Release v0.42.0 is now available. This release fixes a couple bugs and adds support for patching the standard library.

2023-07-10

Release v0.41.0 is now available. rules_go no longer ship with @go_googleapis repo. It requires Gazelle v0.32.0 or later.

2023-06-28

Release v0.40.1 is now available. This release fixes a couple bugs in the go packages driver that were introduced in 0.40.0.

2023-06-22

Release v0.40.0 is now available. This release includes support for //nolint parsing, as well as a large set of additional changes. Please check the release notes for details.

2023-03-27

Release v0.39.0 is now available. This release includes a simpler interface for Bzlmod go_sdk registration, makes the //go tool available to users, and fixes various bugs.

2022-12-06

Release v0.37.0 is now available. This release includes support for generated code in the packages driver as well as various bugfixes.

2022-11-22

Release v0.36.0 is now available. This release adds a Go library to look up runfiles, and two command line flags to pass additional compiler and linker options.

2022-09-11

Release v0.35.0 is now available. This release supports switching Go SDK version from a build flag. Starting this release, rules_go requires Bazel 5.1.0, because it needs to read CPU architecture from Bazel to better support Apple M1 with Rosetta translation.

2022-07-19

Release v0.34.0 is now available. This release brings very experimental support for bzlmod, several improvements to nogo and gopackagesdriver.

2022-06-06

Release v0.33.0 is now available. This release consists mostly of bug fixes and deprecates the asm, compile, cover, and pack actions on go_context.

2022-05-11

Release v0.32.0 is now available. This adds gomock to rules_go and supports lcov format for code coverage report, as well as a long list of other changes listed in the release notes.

Contents

Documentation

Overview

The rules are in the beta stage of development. They support:

They currently do not support or have limited support for:

  • C/C++ integration other than cgo (SWIG)

The Go rules are tested and supported on the following host platforms:

  • Linux, macOS, Windows
  • amd64

Users have reported success on several other platforms, but the rules are only tested on those listed above.

Note: Since version v0.38.0, rules_go requires Bazel ≥ 5.4.0 to work.

The master branch is only guaranteed to work with the latest version of Bazel.

Setup

System setup

To build Go code with Bazel, you will need:

  • A recent version of Bazel.
  • A C/C++ toolchain (if using cgo). Bazel will attempt to configure the toolchain automatically.
  • Bash, patch, cat, and a handful of other Unix tools in PATH.

You normally won't need a Go toolchain installed. Bazel will download one.

See Using rules_go on Windows for Windows-specific setup instructions. Several additional tools need to be installed and configured.

Initial project setup

If you are using Bazel's new external dependency management system Bzlmod, refer to the dedicated Go with Bzlmod guide instead.

Create a file at the top of your repository named WORKSPACE, and add the snippet below (or add to your existing WORKSPACE). This tells Bazel to fetch rules_go and its dependencies. Bazel will download a recent supported Go toolchain and register it for use.

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "io_bazel_rules_go",
    integrity = "sha256-fHbWI2so/2laoozzX5XeMXqUcv0fsUrHl8m/aE8Js3w=",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
        "https://github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
    ],
)

load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")

go_rules_dependencies()

go_register_toolchains(version = "1.20.7")

You can use rules_go at master by using git_repository instead of http_archive and pointing to a recent commit.

Add a file named BUILD.bazel in the root directory of your project. You'll need a build file in each directory with Go code, but you'll also need one in the root directory, even if your project doesn't have Go code there. For a "Hello, world" binary, the file should look like this:

load("@io_bazel_rules_go//go:def.bzl", "go_binary")

go_binary(
    name = "hello",
    srcs = ["hello.go"],
)

You can build this target with bazel build //:hello.

Generating build files

If your project can be built with go build, you can generate and update your build files automatically using gazelle.

Add the bazel_gazelle repository and its dependencies to your WORKSPACE. It should look like this:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "io_bazel_rules_go",
    integrity = "sha256-fHbWI2so/2laoozzX5XeMXqUcv0fsUrHl8m/aE8Js3w=",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
        "https://github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
    ],
)

http_archive(
    name = "bazel_gazelle",
    integrity = "sha256-MpOL2hbmcABjA1R5Bj2dJMYO2o15/Uc5Vj9Q0zHLMgk=",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz",
        "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz",
    ],
)

load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies")

go_rules_dependencies()

go_register_toolchains(version = "1.20.7")

gazelle_dependencies()

Add the code below to the BUILD.bazel file in your project's root directory. Replace the string after prefix with an import path prefix that matches your project. It should be the same as your module path, if you have a go.mod file.

load("@bazel_gazelle//:def.bzl", "gazelle")

# gazelle:prefix github.com/example/project
gazelle(name = "gazelle")

This declares a gazelle binary rule, which you can run using the command below:

bazel run //:gazelle

This will generate a BUILD.bazel file with go_library, go_binary, and go_test targets for each package in your project. You can run the same command in the future to update existing build files with new source files, dependencies, and options.

Writing build files by hand

If your project doesn't follow go build conventions or you prefer not to use gazelle, you can write build files by hand.

In each directory that contains Go code, create a file named BUILD.bazel Add a load statement at the top of the file for the rules you use.

load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_test")

For each library, add a go_library rule like the one below. Source files are listed in the srcs attribute. Imported packages outside the standard library are listed in the deps attribute using Bazel labels that refer to corresponding go_library rules. The library's import path must be specified with the importpath attribute.

go_library(
    name = "foo_library",
    srcs = [
        "a.go",
        "b.go",
    ],
    importpath = "github.com/example/project/foo",
    deps = [
        "//tools",
        "@org_golang_x_utils//stuff",
    ],
    visibility = ["//visibility:public"],
)

For tests, add a go_test rule like the one below. The library being tested should be listed in an embed attribute.

go_test(
    name = "foo_test",
    srcs = [
        "a_test.go",
        "b_test.go",
    ],
    embed = [":foo_lib"],
    deps = [
        "//testtools",
        "@org_golang_x_utils//morestuff",
    ],
)

For binaries, add a go_binary rule like the one below.

go_binary(
    name = "foo",
    srcs = ["main.go"],
)

Adding external repositories

For each Go repository, add a go_repository rule to WORKSPACE like the one below. This rule comes from the Gazelle repository, so you will need to load it. gazelle update-repos can generate or update these rules automatically from a go.mod or Gopkg.lock file.

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

# Download the Go rules.
http_archive(
    name = "io_bazel_rules_go",
    integrity = "sha256-fHbWI2so/2laoozzX5XeMXqUcv0fsUrHl8m/aE8Js3w=",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
        "https://github.com/bazelbuild/rules_go/releases/download/v0.44.2/rules_go-v0.44.2.zip",
    ],
)

# Download Gazelle.
http_archive(
    name = "bazel_gazelle",
    integrity = "sha256-MpOL2hbmcABjA1R5Bj2dJMYO2o15/Uc5Vj9Q0zHLMgk=",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz",
        "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.35.0/bazel-gazelle-v0.35.0.tar.gz",
    ],
)

# Load macros and repository rules.
load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository")

# Declare Go direct dependencies.
go_repository(
    name = "org_golang_x_net",
    importpath = "golang.org/x/net",
    sum = "h1:zK/HqS5bZxDptfPJNq8v7vJfXtkU7r9TLIoSr1bXaP4=",
    version = "v0.0.0-20200813134508-3edf25e44fcc",
)

# Declare indirect dependencies and register toolchains.
go_rules_dependencies()

go_register_toolchains(version = "1.20.7")

gazelle_dependencies()

protobuf and gRPC

To generate code from protocol buffers, you'll need to add a dependency on com_google_protobuf to your WORKSPACE.

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "com_google_protobuf",
    sha256 = "d0f5f605d0d656007ce6c8b5a82df3037e1d8fe8b121ed42e536f569dec16113",
    strip_prefix = "protobuf-3.14.0",
    urls = [
        "https://mirror.bazel.build/github.com/protocolbuffers/protobuf/archive/v3.14.0.tar.gz",
        "https://github.com/protocolbuffers/protobuf/archive/v3.14.0.tar.gz",
    ],
)

load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps")

protobuf_deps()

You'll need a C/C++ toolchain registered for the execution platform (the platform where Bazel runs actions) to build protoc.

The proto_library rule is provided by the rules_proto repository. protoc-gen-go, the Go proto compiler plugin, is provided by the com_github_golang_protobuf repository. Both are declared by go_rules_dependencies. You won't need to declare an explicit dependency unless you specifically want to use a different version. See Overriding dependencies for instructions on using a different version.

gRPC dependencies are not declared by default (there are too many). You can declare them in WORKSPACE using go_repository. You may want to use gazelle update-repos to import them from go.mod.

See Proto dependencies, gRPC dependencies for more information. See also Avoiding conflicts.

Once all dependencies have been registered, you can declare proto_library and go_proto_library rules to generate and compile Go code from .proto files.

load("@rules_proto//proto:defs.bzl", "proto_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")

proto_library(
    name = "foo_proto",
    srcs = ["foo.proto"],
    deps = ["//bar:bar_proto"],
    visibility = ["//visibility:public"],
)

go_proto_library(
    name = "foo_go_proto",
    importpath = "github.com/example/protos/foo_proto",
    protos = [":foo_proto"],
    visibility = ["//visibility:public"],
)

A go_proto_library target may be imported and depended on like a normal go_library.

Note that recent versions of rules_go support both APIv1 (github.com/golang/protobuf) and APIv2 (google.golang.org/protobuf). By default, code is generated with github.com/golang/protobuf/cmd/protoc-gen-gen for compatibility with both interfaces. Client code may import use either runtime library or both.

FAQ

Go

Protocol buffers

Dependencies and testing

Can I still use the go command?

Yes, but not directly.

rules_go invokes the Go compiler and linker directly, based on the targets described with go_binary and other rules. Bazel and rules_go together fill the same role as the go command, so it's not necessary to use the go command in a Bazel workspace.

That said, it's usually still a good idea to follow conventions required by the go command (e.g., one package per directory, package paths match directory paths). Tools that aren't compatible with Bazel will still work, and your project can be depended on by non-Bazel projects.

If you need to use the go command to perform tasks that Bazel doesn't cover (such as adding a new dependency to go.mod), you can use the following Bazel invocation to run the go binary of the Bazel-configured Go SDK:

bazel run @io_bazel_rules_go//go -- <args>

Prefer this to running go directly since it ensures that the version of Go is identical to the one used by rules_go.

Does this work with Go modules?

Yes, but not directly. Bazel ignores go.mod files, and all package dependencies must be expressed through deps attributes in targets described with go_library and other rules.

You can download a Go module at a specific version as an external repository using go_repository, a workspace rule provided by gazelle. This will also generate build files using gazelle.

You can import go_repository rules from a go.mod file using gazelle update-repos.

What's up with the go_default_library name?

This was used to keep import paths consistent in libraries that can be built with go build before the importpath attribute was available.

In order to compile and link correctly, rules_go must know the Go import path (the string by which a package can be imported) for each library. This is now set explicitly with the importpath attribute. Before that attribute existed, the import path was inferred by concatenating a string from a special go_prefix rule and the library's package and label name. For example, if go_prefix was github.com/example/project, for a library //foo/bar:bar, rules_go would infer the import path as github.com/example/project/foo/bar/bar. The stutter at the end is incompatible with go build, so if the label name was go_default_library, the import path would not include it. So for the library //foo/bar:go_default_library, the import path would be github.com/example/project/foo/bar.

Since go_prefix was removed and the importpath attribute became mandatory (see #721), the go_default_library name no longer serves any purpose. We may decide to stop using it in the future (see #265).

How do I cross-compile?

You can cross-compile by setting the --platforms flag on the command line. For example:

$ bazel build --platforms=@io_bazel_rules_go//go/toolchain:linux_amd64 //cmd

By default, cgo is disabled when cross-compiling. To cross-compile with cgo, add a _cgo suffix to the target platform. You must register a cross-compiling C/C++ toolchain with Bazel for this to work.

$ bazel build --platforms=@io_bazel_rules_go//go/toolchain:linux_amd64_cgo //cmd

Platform-specific sources with build tags or filename suffixes are filtered automatically at compile time. You can selectively include platform-specific dependencies with select expressions (Gazelle does this automatically).

go_library(
    name = "foo",
    srcs = [
        "foo_linux.go",
        "foo_windows.go",
    ],
    deps = select({
        "@io_bazel_rules_go//go/platform:linux_amd64": [
            "//bar_linux",
        ],
        "@io_bazel_rules_go//go/platform:windows_amd64": [
            "//bar_windows",
        ],
        "//conditions:default": [],
    }),
)

To build a specific go_binary target for a target platform or using a specific golang SDK version, use the go_cross_binary rule. This is useful for producing multiple binaries for different platforms in a single build.

To build a specific go_test target for a target platform, set the goos and goarch attributes on that rule.

You can equivalently depend on a go_binary or go_test rule through a Bazel configuration transition on //command_line_option:platforms (there are problems with this approach prior to rules_go 0.23.0).

How do I access testdata?

Bazel executes tests in a sandbox, which means tests don't automatically have access to files. You must include test files using the data attribute. For example, if you want to include everything in the testdata directory:

go_test(
    name = "foo_test",
    srcs = ["foo_test.go"],
    data = glob(["testdata/**"]),
    importpath = "github.com/example/project/foo",
)

By default, tests are run in the directory of the build file that defined them. Note that this follows the Go testing convention, not the Bazel convention followed by other languages, which run in the repository root. This means that you can access test files using relative paths. You can change the test directory using the rundir attribute. See go_test.

Gazelle will automatically add a data attribute like the one above if you have a testdata directory unless it contains buildable .go files or build files, in which case, testdata is treated as a normal package.

Note that on Windows, data files are not directly available to tests, since test data files rely on symbolic links, and by default, Windows doesn't let unprivileged users create symbolic links. You can use the github.com/bazelbuild/rules_go/go/tools/bazel library to access data files.

How do I access go_binary executables from go_test?

The location where go_binary writes its executable file is not stable across rules_go versions and should not be depended upon. The parent directory includes some configuration data in its name. This prevents Bazel's cache from being poisoned when the same binary is built in different configurations. The binary basename may also be platform-dependent: on Windows, we add an .exe extension.

To depend on an executable in a go_test rule, reference the executable in the data attribute (to make it visible), then expand the location in args. The real location will be passed to the test on the command line. For example:

go_binary(
    name = "cmd",
    srcs = ["cmd.go"],
)

go_test(
    name = "cmd_test",
    srcs = ["cmd_test.go"],
    args = ["$(location :cmd)"],
    data = [":cmd"],
)

See //tests/core/cross for a full example of a test that accesses a binary.

Alternatively, you can set the out attribute of go_binary to a specific filename. Note that when out is set, the binary won't be cached when changing configurations.

go_binary(
    name = "cmd",
    srcs = ["cmd.go"],
    out = "cmd",
)

go_test(
    name = "cmd_test",
    srcs = ["cmd_test.go"],
    data = [":cmd"],
)

How do I avoid conflicts with protocol buffers?

See Avoiding conflicts in the proto documentation.

Can I use a vendored gRPC with go_proto_library?

This is not supported. When using go_proto_library with the @io_bazel_rules_go//proto:go_grpc compiler, an implicit dependency is added on @org_golang_google_grpc//:go_default_library. If you link another copy of the same package from //vendor/google.golang.org/grpc:go_default_library or anywhere else, you may experience conflicts at compile or run-time.

If you're using Gazelle with proto rule generation enabled, imports of google.golang.org/grpc will be automatically resolved to @org_golang_google_grpc//:go_default_library to avoid conflicts. The vendored gRPC should be ignored in this case.

If you specifically need to use a vendored gRPC package, it's best to avoid using go_proto_library altogether. You can check in pre-generated .pb.go files and build them with go_library rules. Gazelle will generate these rules when proto rule generation is disabled (add # gazelle:proto disable_global to your root build file).

How do I use different versions of dependencies?

See Overriding dependencies for instructions on overriding repositories declared in go_rules_dependencies.

How do I run Bazel on Travis CI?

References:

In order to run Bazel tests on Travis CI, you'll need to install Bazel in the before_install script. See our configuration file linked above.

You'll want to run Bazel with a number of flags to prevent it from consuming a huge amount of memory in the test environment.

  • --host_jvm_args=-Xmx500m --host_jvm_args=-Xms500m: Set the maximum and initial JVM heap size. Keeping the same means the JVM won't spend time growing the heap. The choice of heap size is somewhat arbitrary; other configuration files recommend limits as high as 2500m. Higher values mean a faster build, but higher risk of OOM kill.
  • --bazelrc=.test-bazelrc: Use a Bazel configuration file specific to Travis CI. You can put most of the remaining options in here.
  • build --spawn_strategy=standalone --genrule_strategy=standalone: Disable sandboxing for the build. Sandboxing may fail inside of Travis's containers because the mount system call is not permitted.
  • test --test_strategy=standalone: Disable sandboxing for tests as well.
  • --local_resources=1536,1.5,0.5: Set Bazel limits on available RAM in MB, available cores for compute, and available cores for I/O. Higher values mean a faster build, but higher contention and risk of OOM kill.
  • --noshow_progress: Suppress progress messages in output for cleaner logs.
  • --verbose_failures: Get more detailed failure messages.
  • --test_output=errors: Show test stderr in the Travis log. Normally, test output is written log files which Travis does not save or report.

Downloads on Travis are relatively slow (the network is heavily contended), so you'll want to minimize the amount of network I/O in your build. Downloading Bazel and a Go SDK is a huge part of that. To avoid downloading a Go SDK, you may request a container with a preinstalled version of Go in your .travis.yml file, then call go_register_toolchains(go_version = "host") in a Travis-specific WORKSPACE file.

You may be tempted to put Bazel's cache in your Travis cache. Although this can speed up your build significantly, Travis stores its cache on Amazon, and it takes a very long time to transfer. Clean builds seem faster in practice.

How do I test a beta version of the Go SDK?

rules_go only supports official releases of the Go SDK. However, you can still test beta and RC versions by passing a version like "1.16beta1" to go_register_toolchains. See also go_download_sdk.

load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")

go_rules_dependencies()

go_register_toolchains(version = "1.17beta1")

rules_go's People

Contributors

achew22 avatar ash2k avatar damienmg avatar evanj avatar fmeum avatar hanwen avatar hochhaus avatar ianthehat avatar jamydev avatar jayconrod avatar jmhodges avatar jmillikin-stripe avatar katre avatar kchodorow avatar linzhp avatar mering avatar mikedanese avatar pcj avatar phst avatar pmbethe09 avatar pmuetschard avatar robbertvanginkel avatar robfig avatar siddharthab avatar sluongng avatar steeve avatar tyler-french avatar vladmos avatar xjs avatar yugui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rules_go's Issues

gazelle vendor support

Is vendoring automatically supported when using gazelle/new_go_repository()?

As a specific example, when using new_go_repository() with a repository that uses vendoring (eg: https://github.com/rsc/letsencrypt) I see that gazelle creates BUILD files for the vendored repositories.

For example, adding the following to my WORKSPACE:

new_go_repository(
    name = "io_rsc_letsencrypt",
    commit = "a18c646c3d0772313b7b53c78847bb3eb6463f0b",
    importpath = "rsc.io/letsencrypt",
)

generates the following BUILD files:

ahochhaus@ahochhaus-pc:~/ll$ find -L bazel-* -name BUILD | grep letsen
bazel-ll/external/io_rsc_letsencrypt/BUILD
bazel-ll/external/io_rsc_letsencrypt/vendor/github.com/xenolf/lego/acme/BUILD

However when I build, the vendored repository (com_github_xenolf_lego) can't be found.

Supporting TestMain(m *testing.M)

Seems go_test rule doesn't allow a test which has TestMain(m *testing.M) function.
It reports an error similar to the message below:
github.com/bazelbuild/rules_go/bazel-out/local_linux-fastbuild/bin/examples/lib/a_test_main_test.go:16: cannot use lib.TestMain (type func(_testing.M)) as type func(_testing.T) in field value.

A straightforward solution is to update generate_test_main.go:76 like below (but I'm not sure if it's enough):
if !strings.HasPrefix(fn.Name.Name, "Test") || fn.Name.Name == "TestMain" { continue }

bazel resolves go imports incorrectly

For a simple repo structure like below, bazel fails to build when go files contain imports like $prefix/lib1. Instead, bazel builds only when lib2 imports lib1 via $prefix/lib1/lib1, which is erroneous when using the go tool to build.

$REPO/
 BUILD
 WORKSPACE
 lib1/
   lib1.go
   BUILD
 lib2/
   lib2_depends_on_lib1.go
   BUILD

The problem might stem from the go_prefix implementation. Quoting from go_prefix description:

In Go, imports are always fully qualified with a URL, eg. github.com/user/project. Hence, a label //foo:bar from within a Bazel workspace must be referred to as github.com/user/project/foo/bar

Which means a repo like above, if the BUILD file for lib1 declares a library with name lib1, then importing it requires go files to use $prefix/lib1/lib1 instead of the usual $prefix/lib1

cgo_library does not respect `includes` of cc_library dependencies

We're trying to build levigo (Go bindings for LevelDB) as a cgo_library() rule. The issue is that the LevelDB cc_library rule needs to have: includes = ["include"], for it and its dependents to build successfully. This (and other) target-specific flags are not being passed to the go tool cgo invocation. As a result, building the levigo rule is failing with:

go/batch.go:4:11: fatal error: 'leveldb/c.h' file not found

Given the symlink-forest shenanigans done by the go rules, I suspect it is far from straightforward to just slap the cc.compiler_flags into the cgo command line.

Bazel source folder layout and go tools.

Hi, rules_go maintainers

I've used bazel + rules_go in my company for about 8 months (since from it was in tools/build_rules). In general I am very satisfied with using bazel to build our highly collaborating modules, but I am always bothered by issues preventing other go tools to work with the folder layout, because of the way we organize code differently from standard Go:

app2/
app3/
...
3rdparty/
    |- vendor/
           |- github.com/
                  |- ...
BUILD`
WORKSPACE

I like this folder layout since it's very clean and easy to maintain, especially when Go files are mixed with other files like Java/Python. Bazel builds all of these apps nicely. The problem is that all go tools such as gocode, godoc, guru and IDEs like liteide, expect a GOPATH and src, pkg, bin folders under it, thus they ALL break with bazel's folder layout. The top level BUILD file adds a custom prefix which doesn't match the real folder.

I submitted a commit to let gocode to support bazel folder layout: nsf/gocode@725b543. It allows gocode to autocomplete AFTER the target has been built successfully (because it reads the .a file), so it's not perfect.

I also used some workarounds like create a GOPATH and symlinks to form a standard layout. With the workarounds some Go tools work a little better (Intellij works the best) but far from perfect.

Can the rules_go maintainers please give us suggestions to solve this problem?

Thanks!

Building grpc-gateway from new_git_repository

I'm attempting to build the runtime and other targets from https://github.com/grpc-ecosystem/grpc-gateway with rules_go and a BUILD file for new_git_repository build-file. I'm blocked with:

github.com/grpc-ecosystem/grpc-gateway/external/com_github_grpc_ecosystem_grpc_gateway/runtime/internal/stream_chunk.pb.go:14: package internal; expected runtime

that I believe to be related due to the issues discussed in bazelbuild/bazel#828 and #16.

new_git_repository(
  name = "com_github_grpc_ecosystem_grpc_gateway",
  remote = "https://github.com/grpc-ecosystem/grpc-gateway.git",
  commit = "ccd4e6b091a44f9f6b32848ffc63b3e8f8e26092",
  build_file = "//third_party/com_github_grpc_ecosystem_grpc_gateway:BUILD",
)
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_prefix")

go_prefix("github.com/grpc-ecosystem/grpc-gateway")

go_library(
    name = 'runtime',
    srcs = [
        "runtime/context.go",
        "runtime/convert.go",
        "runtime/doc.go",
        "runtime/errors.go",
        "runtime/handler.go",
        "runtime/marshal_json.go",
        "runtime/marshal_jsonpb.go",
        "runtime/marshaler.go",
        "runtime/marshaler_registry.go",
        "runtime/mux.go",
        "runtime/pattern.go",
        "runtime/proto2_convert.go",
        "runtime/query.go",
        "runtime/internal/stream_chunk.pb.go",
    ],
    deps = [
        "runtime/internal",
        "utilities",
        "@com_github_golang_protobuf//:jsonpb",
        "@com_github_golang_protobuf//:proto",
        "@org_golang_google_grpc//:codes",
        "@org_golang_google_grpc//:go_default_library",
        "@org_golang_google_grpc//:grpclog",
        "@org_golang_google_grpc//:metadata",
        "@org_golang_x_net//:context",
    ],
)

go_library(
    name    = 'runtime/internal',
    srcs = [
        "runtime/internal/stream_chunk.pb.go",
    ],
    deps = [
        "@com_github_golang_protobuf//:proto",
    ],
)

go_library(
    name = 'utilities',
    srcs = [
        "utilities/doc.go",
        "utilities/pattern.go",
        "utilities/trie.go",
    ],
)

Any workaround for this?


As #16 was closed by #57, I experimented with gazelle to see if this could somehow solve the issue, but didn't get farther than running the tool with:

bazel build '@io_bazel_rules_go//go/tools/gazelle/gazelle'
bazel-bin/external/io_bazel_rules_go/go/tools/gazelle/gazelle/gazelle \
-repo_root /private/var/tmp/_bazel_pcj/63330772b4917b139280caef8bb81867/external/com_github_grpc_ecosystem_grpc_gateway

I'm not seeing (or not recognizing) any output from above or any other go-related folder.

generate test main

When I use bazel to build my go_test, it shows the error:

ERROR: /root/testgo/hsa-service-center/src/servicecenter/controllers/BUILD:35:1: null failed: linux-sandbox failed: error executing command /root/.cache/bazel/_bazel_root/40633db3e907142ca23269a67b71fa41/execroot/src/_bin/linux-sandbox ... (remaining 3 argument(s) skipped). bazel-out/local-fastbuild/bin/servicecenter/controllers/instance_watcher_main_test.go:7: imported and not used: "servicecenter/controllers/instance_watcher" as undertest Target //servicecenter/controllers:instance_watcher failed to build

but when I delete the line https://github.com/bazelbuild/rules_go/blob/master/go/tools/generate_test_main.go#L95 ,
it works. Is it a bug?

Supports bazel 0.3.0?

I'm curious if rules_go is being tested against 0.3.0 in a CI matrix. On travis, I'm now getting:

/home/travis/.cache/bazel/external/io_bazel_rules_go/go/def.bzl:500:18: expected ConfigurationTransition or NoneType for 'cfg' while calling label but got string instead: host.

Which seems related to changing the cfg attributes from HOST_CFG to "host". So, I'm thinking of dropping 0.3.0 from my build matrix and requiring 0.3.1 instead.

Perhaps I've missed something so I thought I'd bring it up here.

cgo_library build fails with `/bin/bash: line 0: cd: HOME not set`

Building the following cgo project fails with /bin/bash: line 0: cd: HOME not set


$ ls
bazel-bin  bazel-cgotest  bazel-genfiles  bazel-out  bazel-testlogs  BUILD  cgo.go  WORKSPACE

cat BUILD 
load("@io_bazel_rules_go//go:def.bzl", "go_prefix", "cgo_library")

go_prefix("cgotest")

cgo_library(
    name = "cgo",
    srcs = ["cgo.go"],
)

$ cat WORKSPACE 
git_repository(
    name = "io_bazel_rules_go",
    remote = "https://github.com/bazelbuild/rules_go.git",
    tag = "0.0.2",
)
load("@io_bazel_rules_go//go:def.bzl", "go_repositories")
go_repositories()

The build itself

$ ~/bin/bazel build //:cgo --verbose_failures
WARNING: Sandboxed execution is not supported on your system and thus hermeticity of actions cannot be guaranteed. See http://bazel.io/docs/bazel-user-manual.html#sandboxing for more information. You can turn off this warning via --ignore_unsupported_sandboxing.
INFO: Found 1 target...
ERROR: /vagrant/cgotest/BUILD:5:1: error executing shell command: 'export GOROOT=$(pwd)/external/golang_linux_amd64/go/bin/.. && export CC=$(cd $(dirname /usr/bin/gcc); pwd)/$(basename /usr/bin/gcc) && export CXX=$CC && objdir=$(pwd)/bazel-out/local-fastbuild/genf...' failed: bash failed: error executing command 
(cd /home/vagrant/.cache/bazel/_bazel_vagrant/b4ea8fffb29363907600583bb5450a23/cgotest && \
exec env - \
    CGO_LDFLAGS='' \
    GOARCH=amd64 \
    GOOS=linux \
/bin/bash -c 'export GOROOT=$(pwd)/external/golang_linux_amd64/go/bin/.. && export CC=$(cd $(dirname /usr/bin/gcc); pwd)/$(basename /usr/bin/gcc) && export CXX=$CC && objdir=$(pwd)/bazel-out/local-fastbuild/genfiles/cgo.cgo.dir && mkdir -p $objdir && cd  && $GOROOT/bin/go tool cgo -objdir $objdir -- cgo.go && rm -f $objdir/_cgo_.o $objdir/_cgo_flags'): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 1.
/bin/bash: line 0: cd: HOME not set
Target //:cgo failed to build
INFO: Elapsed time: 0.463s, Critical Path: 0.08s

I think the cause is that ctx.label.package on line https://github.com/bazelbuild/rules_go/blob/master/go/def.bzl#L522 is an empty string. I tried figuring out what is supposed to initialize that variable, but I could not in the time I was willing to spend on it.

If I change cgo_library to go_library and comment out all cgo parts from cgo.go, then compilation succeeds.

I am using RHEL 7.2, OpenJDK 1.8 and current release of Bazel.

build tag support?

The README says that build tags aren't supported. I see that there's a filter_tags tool in the codebase.

What's there to do to hook these bits up? Or are they already hooked up and just need docs?

Implementation Question

Why re-implement all the logic to compile the golang sources instead of using the standard go tools from within bazel i.e. with a genrule or similar ?

cgo_library() cannot find source files when used with new_git_repository()

@yugui This is a followup to bb7e87b.

When using cgo_library() with new_git_repository() bazel is unable to find source files. For example, consider https://golang.org/x/sys/unix.

...

SYS_UNIX_BUILD = """
load("@io_bazel_rules_go//go:def.bzl", "go_prefix", "go_library", "cgo_library")
go_prefix("golang.org/x/sys/unix")
go_library(
    name = "go_default_library",
    srcs = glob([
        "unix/*_linux_amd64.s",
        "unix/*_linux.go",
        "unix/*_linux_amd64.go",
        "unix/*_unix.go",
        "unix/syscall.go",
        "unix/race0.go",
        "unix/str.go",
      ],
      exclude = ["unix/types_linux.go", "unix/gccgo_*"],
    ),
    deps = [
        ":types_linux",
    ],
    visibility = ["//visibility:public"],
)

cgo_library(
    name = "types_linux",
    srcs = ["unix/types_linux.go"],
)
"""
new_git_repository(
    name = "org_golang_x_sys_unix",
    remote = "https://go.googlesource.com/sys",
    commit = "076b546753157f758b316e59bcb51e6807c04057",
    build_file_content = SYS_UNIX_BUILD,
)

When building, I receive the following error:

ahochhaus@debian:~/ll$ b build ...
INFO: Found 51 targets...
ERROR: /home/ahochhaus/.cache/bazel/_bazel_ahochhaus/9b0316414c69160d24362f2991b802bb/external/org_golang_x_sys_unix/BUILD:23:1: error executing shell command: 'export GOROOT=$(pwd)/external/golang_linux_amd64/go/bin/.. && export CC=$(cd $(dirname /usr/bin/gcc); pwd)/$(basename /usr/bin/gcc) && export CXX=$CC && objdir=$(pwd)/bazel-out/local-fastbuild/genf...' failed: namespace-sandbox failed: error executing command /home/ahochhaus/.cache/bazel/_bazel_ahochhaus/9b0316414c69160d24362f2991b802bb/ll/_bin/namespace-sandbox ... (remaining 5 argument(s) skipped).
open unix/types_linux.go: no such file or directory
INFO: Elapsed time: 21.208s, Critical Path: 20.88s

Is cgo_library() expected to work with new_git_repository()?

Using vendored libraries that depend on other libraries

So as with your approach to vendoring, I manually created a BUILD file at my //goroot/src/github.com/etc location and include all the *.go files in the dependency. However, as the dependency imports other packages (also in the form of github.com), it will throw an "can't find import:" during compilation.

Is there any way to use vendored packages like this, which might have a long chain of dependencies?

Download all the go packages each time

I find it annoying that the rule has to download the whole go package each time (~100MB+).

Can we assume instead that the HOST has go installed and maybe just have a rule to enforce the version ?

Request for bumping version

As reported in #14, the only available tag v0.0.1 does not work fine with real applications.
So it would be better to dump the version to v0.0.2 with a commit after 3dc4372.

Also README.md needs to be updated so that it points the new version.

/bin/bash: Argument list too long

Trying to compile a library with several thousand (generated) go-files will cause failure because of a too long argument list passed to bash.

Compatibility with go tool

In the readme it says we can maintain compatibility with the Go tool by symbolic linking the WORKSPACE.

Can you give a more concrete example, I tried this and was not able to get it to work. So the Go files live inside the bazel workspace, and then we create a new $GOPATH, that only contains folders and symlinks for go files? I have a go_library() building in bazel fine, but when I try build it with go build "fully/qualified/name" It just says:

cannot find package "fully/qualified/name" in any of... etc

Warning with bazel 0.3.1

When using rules_go with bazel 0.3.1 I receive the following WARNING. This isn't a large issue for now, but it will cause an error in future versions.

WARNING: /home/ahochhaus/.cache/bazel/_bazel_ahochhaus/9b0316414c69160d24362f2991b802bb/external/io_bazel_rules_go_toolchain/WORKSPACE:1: Workspace name in /home/ahochhaus/.cache/bazel/_bazel_ahochhaus/9b0316414c69160d24362f2991b802bb/external/io_bazel_rules_go_toolchain/WORKSPACE (@golang_linux_amd64) does not match the name given in the repository's definition (@io_bazel_rules_go_toolchain); this will cause a build error in future versions.

Cannot compile a simple example app

Dear Bazel Go folks,

I have tried to create a simple example workspace loosely based on what's here in the repo and I am unable to import my sample library to a binary. I fail to see what problem could I have with the contents of the files and I see a suspicious line in the error message.

I have attached example.tar.gz, an archive that contains this simple example workspace.

Attempting to build //example/samplebin:my_bin_target, I see the following error:

[denes@rudanium example]$ bazel build example/samplebin:my_bin_target
INFO: Found 1 target...
ERROR: /home/denes/goexp/example/example/samplebin/BUILD:3:1: error executing shell command: 'rm -rf bazel-out/local-fastbuild/bin/example/samplebin/my_bin_target.a.dir && mkdir -p bazel-out/local-fastbuild/bin/example/samplebin/my_bin_target.a.dir && mkdir -p bazel-out/local-fastbuild/bin/...' failed: namespace-sandbox failed: error executing command /home/denes/.cache/bazel/_bazel_denes/533fb7a800c9d3f6af2a311f02e299bb/example/_bin/namespace-sandbox ... (remaining 5 argument(s) skipped).
github.com/bazelbuild/rules_go/example/samplebin/samplebin.go:5: can't find import: "example.org/repo/example/samplelib"
Target //example/samplebin:my_bin_target failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 16.683s, Critical Path: 0.76s

This line: github.com/bazelbuild/rules_go/example/samplebin/samplebin.go:5: can't find import: "example.org/repo/example/samplelib" is strange. Is it normal that it copies my go file into such directory structure that starts with github.com/bazelbuild/rules_go? Why not "example.org/repo" instead? (The string I specified as go_prefix) I suspect that this may be a bug but I admit I don't know much about the internals of these rules yet.

Will also look into the bzl file myself...

Bazel version 0.2.1, go version go1.6.1 linux/amd64, running this on Arch Linux.
Workspace: go-example.tar.gz

Thanks for your help,
Dénes

Vendored library linking failure

When one vendored library depends on another, the current rules have a build failure.

Repro: https://github.com/laramiel/bazel-golang-vendor-test.git

$ git clone https://github.com/laramiel/bazel-golang-vendor-test.git
$ cd bazel-golang-vendor-test
$ bazel test //vendor/...

Expected: tests in all subdirectories pass.
Actual: tinylib/msgp tests fail to link.

When run with bazel test //vendor/... --verbose_failures it appears that the go tool link command is looking for the fwd library in the wrong location.

Trouble using rules_go

https://github.com/Limdi/testing_go

bazel build //lib:go_default_library
bazel test //lib:lib_test

These give me errors, my workaround is to add @io_bazel_rules_go to the Labels so the thing uses the @io_bazel_rules_go//go/toolchain stuff instead of trying to find //go/toolchain in my current WORKSPACE.

I guess the @// syntax was once supposed to mean "stay in this repo to resolve this dependency" or something, but I didnt get it to work that way and I read it only worked while some tools-folder was available as a symlink or something, nevermind about that I suppose.

edit: Maybe that doesnt work either, so how to do this?

How to use .a files to build a go_test

How to use .a files to build a go_test? my *_test.go files import ginkgo and gomega, but it too troublesome to build ginkgo and gomega with bazel. So I want to use ginkgo.a and gomega.a to build my go_test. Here is my BUILD file:

`package( default_visibility = ["//visibility:public"], )
load("//go:def.bzl", "go_library", "go_test", "cgo_library")

go_test(
name = "main_controller",
srcs = ["main_controller_test.go"],
deps = [
":cgo_enabled"
],
)

cgo_library(
name = "cgo_enabled",
srcs = ["ginkgo.a", "gomega.a"],
)`

But bazel shows the error:

ERROR: /root/testgo/hsa-service-center/src/servicecenter/controllers/BUILD:39:1: Traceback (most recent call last): File "/root/testgo/hsa-service-center/src/servicecenter/controllers/BUILD", line 39 cgo_library(name = "cgo_enabled", srcs = ["gin..."]) File "/root/testgo/hsa-service-center/src/go/def.bzl", line 973, in cgo_library _cgo_import(name = "%s.cgo.importgen" % name, <6 more arguments>) File "/root/testgo/hsa-service-center/src/go/def.bzl", line 977, in _cgo_import go_srcs[0] List is empty. ERROR: error loading package 'servicecenter/controllers': Package 'servicecenter/controllers' contains errors
How to solve it?

Is it possible to get rid of the "go_default_library" name?

Hi all (but especially @yugui),

I've been wondering about the magic go_default_library name, which seems to have been a part of the Go+Bazel support since the beginning. However, since (virtually?) every Go directory (and hence virtually every BUILD file) will have exactly one Go library in it, why do we need to explicitly add the "go_default_library" text to everything?

I would have thought that it would make the BUILD files much cleaner if we simply assume that every go_library defines a library with the same name as the package, so instead of referring to //path/to/lib:go_default_library, we could simply refer to //path/to/lib (or //path/to/lib:lib). However, it's not clear to me whether this is technically possible or if there would be other ill effects.

Thanks, A

Example gazelle project layout

I'd like to start up a bazel go project with a vendor directory and gazelle without wading through a ton of documentation. I've shipped bazel projects in other languages before.

Is there an example in the tests somewhere @yugui?

go_test attr.library intentions

Imagine the dependency tree
//libtwo:lib_test -> //libtwo:go_default_library -> lib:go_default_library
does the library attribute mean deps of the library should get pulled in automatically? I assume it is supposed to do that and thats why im reporting here.

repro: https://github.com/limdi/testing_go

bazel test ...
....
INFO: Found 4 targets and 1 test target...
ERROR: /home/limdi/testing_go2/libtwo/BUILD:17:1: error executing shell command: 'rm -rf bazel-out/local_linux-fastbuild/bin/libtwo/lib_test.dir && mkdir -p bazel-out/local_linux-fastbuild/bin/libtwo/lib_test.dir && mkdir -p bazel-out/local_linux-fastbuild/bin/libtwo/lib_test.di...' failed: bash failed: error executing command /bin/bash -c ... (remaining 1 argument(s) skipped): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 1.
/home/limdi/.cache/bazel/_bazel_limdi/5dab422ce9814d504334f8f2f353d0aa/testing_go2/external/golang_linux_amd64/go/pkg/tool/linux_amd64/link: cannot open file /home/limdi/.cache/bazel/_bazel_limdi/5dab422ce9814d504334f8f2f353d0aa/testing_go2/external/golang_linux_amd64/go/pkg/linux_amd64/github.com/limdi/testing_go/lib/go_default_library.a: open /home/limdi/.cache/bazel/_bazel_limdi/5dab422ce9814d504334f8f2f353d0aa/testing_go2/external/golang_linux_amd64/go/pkg/linux_amd64/github.com/limdi/testing_go/lib/go_default_library.a: no such file or directory
INFO: Elapsed time: 981.661s, Critical Path: 0.69s

Executed 0 out of 1 tests: 1 fails to build.

My workaround: https://github.com/Limdi/rules_go/commit/f7b0346e1eb9506afc6cd715fa0f325c66b26f77

Protocol Buffer Generation

I've been working on rules for protobuf generation. The go support is largely based on @yugui https://github.com/grpc-ecosystem/grpc-gateway/blob/e958c5db30f7b99e1870db42dd5624322f112d0c/grpc-gateway.bzl and rules_go.

Could someone (@yugui?) review this and offer suggestions or contributions to get the hello world example to run? I have the protobuf generation working but I'm stuck on either a missing / import or incorrect package mapping to get it to compile. Changes are on the "go" branch.

Disclaimer: I'm primarily a java and js dev, golang is relatively new for me.

$ git clone https://github.com/pubref/rules_protobuf
$ cd rules_protobuf
$ git checkout go
$ bazel build examples/helloworld/go/client

@see rules_protobuf go branch
@see //bzl:go.bzl
@see //bzl:protoc.bzl

Thanks!
Paul

Vendoring example fails to build

Here's what I get when I try to build: https://github.com/khargosh/bazel-go-vendor .

~/c/bazel-go-vendor
git:(master)*  [1]fish> bazel build --verbose_failures //vendor/github.com/khargosh/bar/...
INFO: Found 1 target...
Target //vendor/github.com/khargosh/bar:go_default_library up-to-date:
  bazel-bin/vendor/github.com/khargosh/bar/go_default_library.a
INFO: Elapsed time: 0.112s, Critical Path: 0.00s

~/c/bazel-go-vendor
git:(master)* fish> bazel build --verbose_failures //shapes/...
INFO: Found 2 targets...
ERROR: /Users/yesudeep/code/bazel-go-vendor/shapes/BUILD:7:1: error executing shell command: 'rm -rf bazel-out/local-fastbuild/bin/shapes/shapes.a.dir && mkdir -p bazel-out/local-fastbuild/bin/shapes/shapes.a.dir && mkdir -p bazel-out/local-fastbuild/bin/shapes/shapes.a.dir/vendor/github.co...' failed: bash failed: error executing command
  (cd /private/var/tmp/_bazel_yesudeep/7c3ccaabdba34ca6ebd888f61d8d22c0/bazel-go-vendor && \
  exec env - \
    GOARCH=amd64 \
    GOOS=darwin \
  /bin/bash -c 'rm -rf bazel-out/local-fastbuild/bin/shapes/shapes.a.dir && mkdir -p bazel-out/local-fastbuild/bin/shapes/shapes.a.dir && mkdir -p bazel-out/local-fastbuild/bin/shapes/shapes.a.dir/vendor/github.com/khargosh/bar && ln -s ../../../../../../../../../bazel-out/local-fastbuild/bin/vendor/github.com/khargosh/bar/go_default_library.a bazel-out/local-fastbuild/bin/shapes/shapes.a.dir/vendor/github.com/khargosh/bar/go_default_library.a && mkdir -p bazel-out/local-fastbuild/bin/shapes/shapes.a.dir/shapes && ln -s ../../../../../../shapes/shapes.go bazel-out/local-fastbuild/bin/shapes/shapes.a.dir/shapes/shapes.go && export GOROOT=$(pwd)/external/golang_darwin_amd64/go/bin/.. && cd  bazel-out/local-fastbuild/bin/shapes/shapes.a.dir && ../../../../../external/golang_darwin_amd64/go/bin/go tool compile -o ../../../../../bazel-out/local-fastbuild/bin/shapes/shapes.a -pack -I . -importmap=vendor/github.com/khargosh/bar=vendor/github.com/khargosh/bar/go_default_library shapes/shapes.go'): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 1.
shapes/shapes.go:6: can't find import: "github.com/khargosh/bar"
INFO: Elapsed time: 0.151s, Critical Path: 0.04s

How do I get it to build?

new_go_repository() when importpath different from repository URL

Thanks for landing go_repository() and new_go_repository(). This functionality makes working with rules_go very pleasurable.

When porting some of my code, I came across the following problem. Some repositories (for example maxmind-golang) use a different importpath than the repository is located at.

In the case of maxmind-golang, the importpart is github.com/oschwald/maxminddb but the remote location is github.com/oschwald/maxminddb-golang. Can we add an optional param to override remote?

Can Gazelle Support Empty Go Prefixes?

Is it possible for the gazelle binary to support passing in empty go prefixes? This is especially helpful if our project has dependencies that pull in from different domains like gopkg.in, github.com, and/or golang.org.

go_binary cross-compilation

What's the correct way to build a go_binary for a linux platform on osx? For example, bazel build //my/server where ":server" is a go_binary rule works on my osx machine but fails with "can't find import: html/template" when invoked with --cpu armeabi_v7a. I was expecting a toolchain for k8 but the only available --cpu options are:

ERROR: No toolchain found for cpu 'k8'. Valid cpus are: [
  darwin,
  armeabi-v7a,
  x64_windows_msvc,
].

rules_go build fails on Debian linux

A full build of 97df516ee1b95740babf611d7a77e96d4c2e4d52 fails on Debian Jessie.

ahochhaus@ahochhaus-pc:~/rules_go$ git rev-parse HEAD
97df516ee1b95740babf611d7a77e96d4c2e4d52
ahochhaus@ahochhaus-pc:~/rules_go$ bazel build ...
WARNING: /home/ahochhaus/.cache/bazel/_bazel_ahochhaus/dbcc6ddb71ac1c7bbb1760502948969f/external/io_bazel_rules_go_toolchain/WORKSPACE:1: Workspace name in /home/ahochhaus/.cache/bazel/_bazel_ahochhaus/dbcc6ddb71ac1c7bbb1760502948969f/external/io_bazel_rules_go_toolchain/WORKSPACE (@golang_linux_amd64) does not match the name given in the repository's definition (@io_bazel_rules_go_toolchain); this will cause a build error in future versions.
INFO: Found 57 targets...
ERROR: /home/ahochhaus/rules_go/examples/cgo/example_command/BUILD:7:1: null failed: linux-sandbox failed: error executing command /home/ahochhaus/.cache/bazel/_bazel_ahochhaus/dbcc6ddb71ac1c7bbb1760502948969f/execroot/rules_go/_bin/linux-sandbox ... (remaining 3 argument(s) skipped).
/home/ahochhaus/.cache/bazel/_bazel_ahochhaus/dbcc6ddb71ac1c7bbb1760502948969f/execroot/rules_go/external/io_bazel_rules_go_toolchain/pkg/tool/linux_amd64/link: running /usr/bin/gcc failed: exit status 1
/usr/bin/ld: -relro: unknown -z option
/usr/bin/ld: use the --help option for usage information
collect2: error: ld returned 1 exit status

INFO: Elapsed time: 3.113s, Critical Path: 1.13s
ahochhaus@ahochhaus-pc:~/rules_go$ uname -a
Linux ahochhaus-pc.corp.samegoal.com 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt25-2+deb8u3 (2016-07-02) x86_64 GNU/Linux
ahochhaus@ahochhaus-pc:~/rules_go$ bazel version
Build label: 0.3.1
Build target: bazel-out/local-fastbuild/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Fri Jul 29 09:09:52 2016 (1469783392)
Build timestamp: 1469783392
Build timestamp as int: 1469783392

Is this expected?

buildmode shared

I saw that using -buildmode=c-shared is currently unsupported here:
#10

Any plans to add this or ideas of how difficult it would be to add?

Allow cc_binary to depend on cgo_library

Go allows the export of symbols, so it would be interesting to see its symbols exported and used inside a C binary, built all in bazel. Currently if I depend on a cgo_library() with a cc_binary, I just get the following:

in deps attribute of cc_binary rule //lib/go:testmain: go_library rule '//lib/go:test' is misplaced here (expected cc_inc_library, cc_library or objc_library)

go_test rule doesn't support TestMain

I should be able to create a function with the signature:

func TestMain(m *testing.M)

which is used to setup/teardown common work before/after each test. But go/tools/generate_test_main.go includes this function as one of the tests, which is incorrect.

The following patch appears to fix the problem:

diff --git a/go/tools/generate_test_main.go b/go/tools/generate_test_main.go
index b78f124..29fc4b9 100644
--- a/go/tools/generate_test_main.go
+++ b/go/tools/generate_test_main.go
@@ -76,6 +76,10 @@ func main() {
                        if !strings.HasPrefix(fn.Name.Name, "Test") {
                                continue
                        }
+                       if fn.Name.Name == "TestMain" {
+                               // TestMain is not, itself, a test
+                               continue
+                       }
                        cases.Names = append(cases.Names, fn.Name.Name)
                }
        }

But I don't see any tests for this rule so I'm not sure how to verify this change.

CC @yugui - I hear you're the guru on these rules :) Also CCing @kchodorow - are you the owner of this file/repo?

Why does the cgo_binary not handle pure Go code?

I would like to understand the reasoning behind why the cgo_binary target cannot compile pure Go code that does not import "C". link It seems to me that having to list out manually and separately the Go files that import C and those that do not is a little onerous for a large project.

cgo_library doesn't pass copts down to cgo

Hello,

Thanks for making rules_go! Here's a small bug report & potential fix:

Bug: cgo_binary doesn't pass copts down to the compiler flags in the cgo invocation.

Fix: github.com/ecaraszi/rules_go on branch cflags

I used this patch to successfully build the github.com/go-gl libraries (glfw 3.2, gl 4.1-core, and mathgl) and link a working example.

new_go_repository() binary naming

When using a repository which only contains a binary (eg: samegoal/teerun) the binary is named after the full repository (eg com_github_samegoal_teerun) instead of just the parent directory (eg: teerun).

For example:

new_go_repository(
    name = "com_github_samegoal_teerun",
    commit = "515e055985d243cb7f5384b86fa884ebcc0e27df",
    importpath = "github.com/samegoal/teerun",
)

Results in the binary bazel-bin/external/com_github_samegoal_teerun/com_github_samegoal_teerun when I would expect bazel-bin/external/com_github_samegoal_teerun/teerun which is more in line with the default go toolset.

Run benchmarks

Does a go_test support running benchmarks? I tried running the resulting binary with -test.bench=., but it doesn't seem to do anything, and I don't see any reference to benchmark handling in geneate_test_main.go

ERROR: 'alias' is not defined

I followed the instruction to build a go repo with bazel but I got the following error:
ERROR: /home/lucas/.cache/bazel/_bazel_lucas/193cc5f26c6c8c0e09cc62d097bb638a/external/io_bazel_rules_go/go/toolchain/BUILD:5:1: name 'alias' is not defined.
ERROR: /home/lucas/.cache/bazel/_bazel_lucas/193cc5f26c6c8c0e09cc62d097bb638a/external/io_bazel_rules_go/go/toolchain/BUILD:10:1: name 'alias' is not defined.
ERROR: /home/lucas/.cache/bazel/_bazel_lucas/193cc5f26c6c8c0e09cc62d097bb638a/external/io_bazel_rules_go/go/toolchain/BUILD:15:1: name 'alias' is not defined.
ERROR: /home/lucas/Documents/bazel_playaround/go_example/go/src/improbable.io/dictdash/BUILD:3:1: every rule of type go_library implicitly depends upon the target '@io_bazel_rules_go//go/toolchain:go_include', but this target could not be found because of: no such target '@io_bazel_rules_go//go/toolchain:go_include': target 'go_include' not declared in package 'go/toolchain' defined by /home/lucas/.cache/bazel/_bazel_lucas/193cc5f26c6c8c0e09cc62d097bb638a/external/io_bazel_rules_go/go/toolchain/BUILD.
ERROR: Loading failed; build aborted.

This is related to version 0.1.0, when I used version 0.0.4 it worked fine

generate_test_main.go: no such file or directory

Unable to get any git tests to build at HEAD, even in the following simple project with 4 files:

WORKSPACE

git_repository(
    name = "io_bazel_rules_go",
    remote = "https://github.com/bazelbuild/rules_go.git",
    tag = "0.0.2",
)
load("@io_bazel_rules_go//go:def.bzl", "go_repositories")

go_repositories()

BUILD

load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")

go_prefix("github.com/jakevoytko/bazel-test")

go_library(name="go_default_library",srcs=["test.go"])

go_test(name="test", srcs=["go_test.go"], deps=[":go_default_library"])

test.go

package bazel

func UnderTest(i int) int {
    return i + 2
}

go_test.go

package bazel

import (
    "fmt"
    "testing"
)

func TestTheThing(t *testing.T) {
    fmt.Println("hello")
}

command output:

Jacobs-MacBook-Pro:bazel jake$ bazel test :test
.
INFO: Found 1 test target...
ERROR: /private/var/tmp/_bazel_jake/5a307faf9a56c70a9ba44e4f95d550a5/external/io_bazel_rules_go/go/tools/BUILD:6:1: error executing shell command: 'rm -rf bazel-out/host/io_bazel_rules_go/go/tools/generate_test_main.a.dir && mkdir -p bazel-out/host/io_bazel_rules_go/go/tools/generate_test_main.a.dir && mkdir -p bazel-out/host/io_bazel_rules_go...' failed: bash failed: error executing command /bin/bash -c ... (remaining 1 argument(s) skipped): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 1.
open github.com/bazelbuild/rules_go/../io_bazel_rules_go/go/tools/generate_test_main.go: open github.com/bazelbuild/rules_go/../io_bazel_rules_go/go/tools/generate_test_main.go: no such file or directory
Target //:test failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 14.788s, Critical Path: 0.04s

bazel version:

Jacobs-MacBook-Pro:bazel jake$ bazel version
Build label: 0.3.0-2016-06-18 (@ff1332d)
Build target: bazel-out/local-fastbuild/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Sun Jun 19 00:09:35 2016 (1466294975)
Build timestamp: 1466294975
Build timestamp as int: 1466294975

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.