Skip to content
Jay Conrod edited this page Jul 7, 2021 · 21 revisions

Usage

The packages driver fundamentally works from the perspective of one or more targets. In order for it to function properly, the targets must be specified in the packages driver configuration, with environment variables.

These are:

  • GOPACKAGESDRIVER_BAZEL_TARGETS: specifies specific targets, //... works too (although this is not recommended without tag filters). It is possible to set targets to something other than go_ rules, as long as the go_ nodes are reachable via the deps attribute in the graph. Such as when go_binary(linkmode = "c-archive") -> cc_library.
  • GOPACKAGESDRIVER_BAZEL_QUERY: runs a bazel query to select targets before, common one should be kind(go_binary, //...). This should work for most cases.
  • GOPACKAGESDRIVER_BAZEL_TAG_FILTERS: makes use of the --build_tag_filters option to only build (filter) targets with certain tags. This is useful for when you want each target to define wether or not it should be part of the packages list. For instance, set GOPACKAGESDRIVER_BAZEL_TARGETS="//..." and GOPACKAGESDRIVER_BAZEL_TAG_FILTERS="completion" to only build targets with the completion tag in the whole workspace.

In addition, those environment variables are optional:

  • GOPACKAGESDRIVER_BAZEL: bazel binary, defaults to bazel
  • BUILD_WORKSPACE_DIRECTORY: directory of the bazel workspace (should be auto detected when using a launcher script because it invokes bazel run)

1. gopls

You'll need gopls >= v0.6.10 (released on Apr 13th 2021). If you are using VSCode, it should be automatic.

2. Create a launcher script

Create a launcher script, say tools/gopackagesdriver.sh:

#!/usr/bin/env bash
exec bazel run -- @io_bazel_rules_go//go/tools/gopackagesdriver "${@}"

3. Sample VSCode configuration

In .vscode/settings.json add the following:

    "go.goroot": "${workspaceFolder}/bazel-${workspaceFolderBasename}/external/go_sdk",
    "go.toolsEnvVars": {
      "GOPACKAGESDRIVER_BAZEL_QUERY": "kind(go_binary, //...)",
      "GOPACKAGESDRIVER": "${workspaceFolder}/tools/gopackagesdriver.sh"
    },
    "go.useLanguageServer": true,

Open VSCode, and after a while the packages should be properly detected after the build is done.

The same principles should apply for vim-go or any editor that uses gopls.

Limitations

  • CGo completion may not work, but at least it's not explicitly supported.
  • Errors are not handled
  • Query patterns are ignored and the whole graph is returned each time patterns are now used
  • Root packages detection is probably wrong it should be better now

Clone this wiki locally